ngram
listlengths
0
82k
[ "select, MetaData,\\ update, delete, insert, extract, union, func, PrimaryKeyConstraint, \\", "update( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT", "(\"*\", \"mssql\"): self.assert_compile( t.insert(). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"INSERT", "def test_extract(self): t = table('t', column('col1')) for field in 'day',", "select([t]). order_by( t.c.somecolumn.collate(\"Latin1_General_CS_AS_KS_WS_CI\").asc()), \"SELECT sometable.somecolumn FROM sometable \" \"ORDER BY", "Column('id', Integer, primary_key=True), schema=\"foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT foo.dbo.test.id FROM", "= Table('test', metadata, Column('id', Integer, autoincrement=False, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE", ":x_1 ORDER BY t.y\", checkparams={'x_1': 5} ) def test_primary_key_no_identity(self): metadata", "Column('id', Integer, primary_key=True), schema='paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM paj.test", "result_map = c._create_result_map() for col in cols: is_(result_map[col.key][1][0], col) def", "in set(c._create_result_map()['x'][1]) assert t1.c.y in set(c._create_result_map()['y'][1]) def test_offset_dont_misapply_labelreference(self): m =", "class SchemaTest(fixtures.TestBase): def setup(self): t = Table('sometable', MetaData(), Column('pk_column', Integer),", "Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"foo.dbo\" ) self.assert_compile( select([tbl]),", "self.ddl_compiler = dialect.ddl_compiler(dialect, schema.CreateTable(t)) def _column_spec(self): return self.ddl_compiler.get_column_specification(self.column) def test_that_mssql_default_nullability_emits_null(self):", ":somecolumn_1\" ) def test_delete_hint(self): t = table('sometable', column('somecolumn')) for targ", "\"#other\", meta, Column(\"sym\", String), Column(\"newval\", Integer) ) stmt = table.update().values(", "col3, t1.col4 AS col4 ' 'FROM t1 WHERE t1.col2 IN", "def test_insert_hint(self): t = table('sometable', column('somecolumn')) for targ in (None,", "mytable SET name=:name OUTPUT ' 'LEN(inserted.name) AS length_1') def test_delete_returning(self):", "MetaData() tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"Foo.dbo\",", "' 'FROM t2 WHERE t2.col2 IN (:col2_3, ' ':col2_4)) AS", "but not the OFFSET # of zero, so produces TOP", "(SELECT t.x AS x, t.y \" \"AS y, ROW_NUMBER() OVER", "> 5)\" ) def test_drop_index_w_schema(self): m = MetaData() t1 =", "'t1', column('col1'), column('col2'), column('col3'), column('col4')) t2 = table( 't2', column('col1'),", "= t1.join(t2, t1.c.a == t2.c.a).\\ select().with_hint(t1, 'WITH (NOLOCK)') self.assert_compile( join,", "WITH (PAGLOCK) \" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_delete_exclude_hint(self):", ") def test_join_with_hint(self): t1 = table('t1', column('a', Integer), column('b', String),", "metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False) ) idx =", "Column('x', Integer), Column('y', Integer), Column('z', Integer)) idx = Index(\"foo\", tbl.c.x.desc(),", "insert, extract, union, func, PrimaryKeyConstraint, \\ UniqueConstraint, Index, Sequence, literal", "CLUSTERED (y))\" ) def test_index_clustering(self): metadata = MetaData() tbl =", "for darg in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == t2.c.somecolumn). values(somecolumn=\"x\").", "table = Table( \"sometable\", meta, Column(\"sym\", String), Column(\"val\", Integer), schema=\"schema\"", "paj.test WHERE paj.test.id = ' ':id_1') s = select([tbl.c.id]).where(tbl.c.id ==", "INDEX foo ON test (x) INCLUDE (y)\" ) def test_index_extra_include_2(self):", "\\ UniqueConstraint, Index, Sequence, literal from sqlalchemy import testing from", "x, t.y AS y, \" \"ROW_NUMBER() OVER (ORDER BY t.y)", "\" \"id2 INTEGER NOT NULL IDENTITY(1,1))\" ) def test_identity_start_0(self): metadata", "ASC\" ) def test_join_with_hint(self): t1 = table('t1', column('a', Integer), column('b',", "def test_offset_using_window(self): t = table('t', column('x', Integer), column('y', Integer)) s", "None eq_(\"test_column VARCHAR(max)\", self._column_spec()) def test_that_mssql_specified_nullable_emits_null(self): self.column.nullable = True eq_(\"test_column", "NOT NULL IDENTITY(1,1), \" \"PRIMARY KEY (id))\" ) def test_identity_no_primary_key(self):", "def test_table_uc_explicit_nonclustered(self): metadata = MetaData() tbl = Table('test', metadata, Column('x',", "t2.a, t2.b, t2.c ' 'FROM t1 WITH (NOLOCK) JOIN t2", "SchemaTest(fixtures.TestBase): def setup(self): t = Table('sometable', MetaData(), Column('pk_column', Integer), Column('test_column',", "NULL, \" \"PRIMARY KEY (id))\" ) def test_primary_key_defaults_to_identity(self): metadata =", "autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\"), UniqueConstraint(\"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE", "autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x", ":col2_4) ORDER BY col3, col4') self.assert_compile(u.alias('bar').select(), 'SELECT bar.col3, bar.col4 FROM", "'SELECT t1.col3 AS col3, t1.col4 AS col4 ' 'FROM t1", "t.c.col1)]), 'SELECT DATEPART(%s, t.col1) AS anon_1 FROM t' % field)", "in (\"*\", \"mssql\"): self.assert_compile( t.insert(). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg),", "= MetaData() t = Table( 'sometable', m, Column('col1', Integer), Column('col2',", "ms-sql dialect removes ORDER BY clauses from subqueries\"\"\" table1 =", "'foo()') m = MetaData() t = Table( 'sometable', m, Column('col1',", "test_schema_autosplit_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('id',", "t1 = table( 't1', column('col1'), column('col2'), column('col3'), column('col4')) t2 =", "dialect = mssql.dialect() for identifier, expected_schema, expected_owner in [ (\"foo\",", "'FROM t1 WHERE t1.col2 IN (:col2_1, ' ':col2_2) UNION SELECT", "'mytable', column('myid', Integer), column('name', String(128)), column('description', String(128))) d = delete(table1).returning(table1.c.myid,", "select([table1.c.myid], order_by=[table1.c.myid]).alias('foo') crit = q.c.myid == table1.c.myid self.assert_compile(select(['*'], crit), \"SELECT", "select([t2.c.col3.label('col3'), t2.c.col4.label('col4')], t2.c.col2.in_(['t2col2r2', 't2col2r3'])) u = union(s1, s2, order_by=['col3', 'col4'])", ") def test_identity_separate_from_primary_key(self): metadata = MetaData() tbl = Table('test', metadata,", "'inserted.myid, inserted.name VALUES ' '(:name)') i = insert(table1, values=dict(name='foo')).returning(table1) self.assert_compile(i,", "self.assert_compile(func.foo(1, 2), 'foo(:foo_1, :foo_2)') self.assert_compile(func.current_time(), 'CURRENT_TIME') self.assert_compile(func.foo(), 'foo()') m =", "Column('y', Integer), Column('z', Integer)) idx = Index(\"foo\", tbl.c.x, mssql_include=['y']) self.assert_compile(schema.CreateIndex(idx),", "tbl = Table('test', metadata, Column('id', Integer, autoincrement=False, primary_key=True)) self.assert_compile( schema.CreateTable(tbl),", "table('t', column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20)", "Integer, autoincrement=False) ) idx = Index(\"myidx\", tbl.c.x, tbl.c.y, mssql_clustered=False) self.assert_compile(", "table('t', column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0)", "foo ON test (x) INCLUDE (y)\" ) def test_index_extra_include_2(self): metadata", "test_update_exclude_hint(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\").", "test_function(self): self.assert_compile(func.foo(1, 2), 'foo(:foo_1, :foo_2)') self.assert_compile(func.current_time(), 'CURRENT_TIME') self.assert_compile(func.foo(), 'foo()') m", "with subsequent compile # calls for i in range(2): self.assert_compile(", "sometable.somecolumn FROM sometable \" \"ORDER BY sometable.somecolumn COLLATE \" \"Latin1_General_CS_AS_KS_WS_CI", "TABLE test (id INTEGER NOT NULL IDENTITY(5,1))\" ) def test_table_pkc_clustering(self):", "now self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL", "Table, Column, select, MetaData,\\ update, delete, insert, extract, union, func,", "= table('othertable', column('somecolumn')) # for darg in (\"*\", \"mssql\"): #", "= MetaData() tbl = Table('test', metadata, Column('id', Integer, autoincrement=False, primary_key=True),", "SET somecolumn=:somecolumn \" \"FROM sometable, othertable WITH (PAGLOCK) \" \"WHERE", "self.column = t.c.test_column dialect = mssql.dialect() self.ddl_compiler = dialect.ddl_compiler(dialect, schema.CreateTable(t))", "t1.x = t2.x)\" \") AS mssql_rn \" \"FROM t1 \"", "t): for darg in (\"*\", \"mssql\"): self.assert_compile( t.insert(). values(somecolumn=\"x\"). with_hint(\"WITH", "' '(SELECT paj.test.id FROM paj.test ' 'WHERE paj.test.id = :id_1)')", "= :x_1) AS anon_1 \" \"WHERE mssql_rn > :param_1 AND", "column('myid', Integer), column('name', String(128)), column('description', String(128))) u = update( table1,", "metadata, Column('id', Integer, Sequence('', 0), primary_key=True)) with testing.expect_deprecated( \"Use of", "column('col3'), column('col4')) s1, s2 = select( [t1.c.col3.label('col3'), t1.c.col4.label('col4')], t1.c.col2.in_(['t1col2r1', 't1col2r2'])),", "mssql_include=['y']) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test (x) INCLUDE (y)\"", "checkparams={'param_1': 20, 'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2)", "sometable.somecolumn FROM sometable') def test_select_with_nolock(self): t = table('sometable', column('somecolumn')) self.assert_compile(", "def test_force_schema_quoted_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table( 'test', metadata,", "extract, union, func, PrimaryKeyConstraint, \\ UniqueConstraint, Index, Sequence, literal from", "subqueries\"\"\" table1 = table('mytable', column('myid', Integer), column('name', String), column('description', String),", "testing.expect_deprecated( \"Use of Sequence with SQL Server in order to", "[banana split].paj.test WHERE ' '[banana split].paj.test.id IN (' 'SELECT [banana", "nullable=True)) with testing.expect_deprecated( \"Use of Sequence with SQL Server in", "(x), UNIQUE CLUSTERED (y))\" ) def test_index_clustering(self): metadata = MetaData()", "WHERE [schema].sometable.sym = [#other].sym\", ) # TODO: not supported yet.", "Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10) self.assert_compile( s, \"SELECT TOP", "table('sometable', column('somecolumn')) t2 = table('othertable', column('somecolumn')) for darg in (\"*\",", "None, \"Foo.Bar\"), (\"[Foo.Bar].[bat]\", \"Foo.Bar\", \"bat\"), ]: schema, owner = base._owner_plus_db(dialect,", "Column('col2', Integer)) self.assert_compile(select([func.max(t.c.col1)]), 'SELECT max(sometable.col1) AS max_1 FROM ' 'sometable')", "self.assert_compile( select([tbl]), \"SELECT foo.dbo.test.id FROM foo.dbo.test\" ) def test_schema_autosplit_w_dot_case_sensitive(self): metadata", "tbl = Table('test', metadata, Column('id', Integer, autoincrement=True), Column('id2', Integer, autoincrement=True),", "\"PRIMARY KEY (id))\" ) def test_sequence_start_0(self): metadata = MetaData() tbl", "t = table('sometable', column('somecolumn')) self.assert_compile(t.insert(), 'INSERT INTO sometable (somecolumn) VALUES", "\" \"FROM (SELECT t1.x AS x, t1.y AS y, \"", "sql.delete(t1).where(t1.c.c1 == t2.c.c1) self.assert_compile( q, \"DELETE FROM t1 FROM t1,", "= MetaData() tbl = Table('test', metadata, Column('id', Integer, autoincrement=True)) self.assert_compile(", "= MetaData() table = Table( \"sometable\", meta, Column(\"sym\", String), Column(\"val\",", "for targ in (None, t): for darg in (\"*\", \"mssql\"):", "Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10) self.assert_compile( s,", "union, func, PrimaryKeyConstraint, \\ UniqueConstraint, Index, Sequence, literal from sqlalchemy", "= MetaData() tbl = Table('test', metadata, Column('id', Integer, Sequence('', 0),", "ORDER BY t.y\", checkparams={'x_1': 5} ) def test_primary_key_no_identity(self): metadata =", "foo(t.x) DESC) AS mssql_rn FROM t) \" \"AS anon_1 WHERE", "# ) def test_strict_binds(self): \"\"\"test the 'strict' compiler binds.\"\"\" from", "s, \"SELECT anon_1.x, anon_1.y FROM (SELECT t.x AS x, t.y", "primary_key=True), schema=quoted_name(\"foo.dbo\", True) ) self.assert_compile( select([tbl]), \"SELECT [foo.dbo].test.id FROM [foo.dbo].test\"", "t1.c, t2.a, t2.b, t2.c ' 'FROM t1 WITH (NOLOCK) JOIN", "(x INTEGER NULL, y INTEGER NULL, \" \"UNIQUE NONCLUSTERED (x,", "\"CREATE CLUSTERED INDEX foo ON test (id)\" ) def test_index_ordering(self):", "self.assert_compile( t.delete().where(t.c.somecolumn == \"q\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"DELETE FROM", "self.assert_compile( s, \"SELECT TOP 10 t.x, t.y FROM t WHERE", "mssql.dialect() def test_true_false(self): self.assert_compile( sql.false(), \"0\" ) self.assert_compile( sql.true(), \"1\"", "test_true_false(self): self.assert_compile( sql.false(), \"0\" ) self.assert_compile( sql.true(), \"1\" ) def", "\"CREATE TABLE test (x INTEGER NOT NULL, y INTEGER NOT", "Integer, primary_key=True), schema='banana.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM banana.paj.test WHERE", "test_update(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.update(t.c.somecolumn == 7), 'UPDATE sometable", "sometable.somecolumn COLLATE \" \"Latin1_General_CS_AS_KS_WS_CI ASC\" ) def test_join_with_hint(self): t1 =", "tbl.c.x, mssql_include=['y']) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test (x) INCLUDE", "set(c._create_result_map()['x'][1]) def test_offset_using_window(self): t = table('t', column('x', Integer), column('y', Integer))", "Column('id', Integer, Sequence('', start=5), nullable=True)) with testing.expect_deprecated( \"Use of Sequence", "values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT ' 'inserted.myid,", "\" \"IN ('x', 'y', 'z')\", ), ( t.c.foo.in_([None]), \"sometable.foo IN", "INDEX foo ON test (id)\" ) def test_index_ordering(self): metadata =", "= s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1]) assert t.c.y", "== other.c.sym) self.assert_compile( stmt, \"UPDATE [schema].sometable SET val=\" \"[#other].newval FROM", "in (\"*\", \"mssql\"): # self.assert_compile( # t.delete().where(t.c.somecolumn==t2.c.somecolumn). # with_hint(\"WITH (PAGLOCK)\",", "== 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM banana.paj.test WHERE ' 'banana.paj.test.id IN", "zero, but not the OFFSET # of zero, so produces", "TABLE test (id INTEGER NOT NULL IDENTITY(1,1)\" \")\" ) def", "column(\"b\", Integer), column(\"c\", Integer), ) join = t1.join(t2, t1.c.a ==", "\" \"WHERE [banana split].[paj with a space].test.id = :id_1)\" )", "anon_1 \" \"WHERE mssql_rn > :param_1 AND mssql_rn <= :param_2", "metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer, autoincrement=True))", ") t2 = table('t2', column(\"a\", Integer), column(\"b\", Integer), column(\"c\", Integer),", "(somecolumn) VALUES ' '(:somecolumn)') def test_update(self): t = table('sometable', column('somecolumn'))", "String(128)), column('description', String(128))) u = update( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(u,", "split].paj.test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE", "' 'FROM banana.paj.test WHERE ' 'banana.paj.test.id = :id_1)') def test_delete_schema_multipart_needs_quoting(self):", "FROM t1 ' 'WHERE t1.col2 IN (:col2_1, :col2_2) UNION '", "= mytable.myid\") def test_force_schema_quoted_name_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table(", "test_strict_binds(self): \"\"\"test the 'strict' compiler binds.\"\"\" from sqlalchemy.dialects.mssql.base import MSSQLStrictCompiler", "x, t.y \" \"AS y, ROW_NUMBER() OVER (ORDER BY t.y)", "\" \"WHERE [schema].sometable.sym = [#other].sym)\", ) stmt = table.update().values(val=other.c.newval).\\ where(table.c.sym", "column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10) self.assert_compile(", "'SELECT [banana split].paj.test.id FROM ' '[banana split].paj.test WHERE ' '[banana", "(\"foo.bar\", \"foo\", \"bar\"), (\"Foo.Bar\", \"Foo\", \"Bar\"), (\"[Foo.Bar]\", None, \"Foo.Bar\"), (\"[Foo.Bar].[bat]\",", "self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT ' 'inserted.myid, inserted.name VALUES", "select([tbl]), \"SELECT [Foo].dbo.test.id FROM [Foo].dbo.test\" ) def test_owner_database_pairs(self): dialect =", "= :x_1 ORDER BY t.y\", checkparams={'x_1': 5} ) def test_limit_zero_using_top(self):", "== 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.q, anon_1.p, anon_1.y \"", "IN (:col2_3, ' ':col2_4)) AS bar') def test_function(self): self.assert_compile(func.foo(1, 2),", "column('x', Integer), column('y', Integer)) order_by = select([t2.c.y]).where(t1.c.x == t2.c.x).as_scalar() s", "u = union(s1, s2, order_by=['col3', 'col4']) self.assert_compile(u, 'SELECT t1.col3 AS", "Integer), column('b', String), column('c', String), ) t2 = table('t2', column(\"a\",", "OUTPUT ' 'LEN(inserted.name) AS length_1 VALUES ' '(:name)') def test_limit_using_top(self):", "'month', 'year': self.assert_compile( select([extract(field, t.c.col1)]), 'SELECT DATEPART(%s, t.col1) AS anon_1", "test_function_overrides(self): self.assert_compile(func.current_date(), \"GETDATE()\") self.assert_compile(func.length(3), \"LEN(:length_1)\") def test_extract(self): t = table('t',", "ON test (x, y)\" ) def test_table_uc_explicit_nonclustered(self): metadata = MetaData()", "= table('t', column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x ==", "== 1), 'DELETE FROM banana.paj.test WHERE ' 'banana.paj.test.id = :id_1')", "space].test \" \"WHERE [banana split].[paj with a space].test.id = :id_1)\"", "NULL, \" \"PRIMARY KEY CLUSTERED (x, y))\" ) def test_table_pkc_explicit_nonclustered(self):", "def test_delete_schema_multipart(self): metadata = MetaData() tbl = Table( 'test', metadata,", "FROM t1 AS a1, t2 WHERE a1.c1 = t2.c1\" )", "= table.update().values(val=other.c.newval).\\ where(table.c.sym == other.c.sym) self.assert_compile( stmt, \"UPDATE [schema].sometable SET", "Table('test', metadata, Column('id', Integer, autoincrement=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "(x DESC, y)\" ) def test_create_index_expr(self): m = MetaData() t1", "' 'FROM t1 WHERE t1.col2 IN (:col2_1, ' ':col2_2) UNION", "(SELECT mytable.myid AS \" \"myid FROM mytable) AS foo, mytable", "for darg in (\"*\", \"mssql\"): self.assert_compile( t.insert(). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\",", "darg in (\"*\", \"mssql\"): # self.assert_compile( # t.delete().where(t.c.somecolumn==t2.c.somecolumn). # with_hint(\"WITH", "column('col1')) for field in 'day', 'month', 'year': self.assert_compile( select([extract(field, t.c.col1)]),", "m = MetaData() t1 = Table('foo', m, Column('x', Integer) )", "dialect_name=darg), \"UPDATE sometable WITH (PAGLOCK) \" \"SET somecolumn=:somecolumn \" \"WHERE", "self.assert_compile(t.select().where(t.c.somecolumn != t.select()), 'SELECT sometable.somecolumn FROM ' 'sometable WHERE sometable.somecolumn", "deleted.myid, ' 'deleted.name') d = delete(table1).where(table1.c.name == 'bar' ).returning(table1.c.myid, table1.c.name)", "schema='banana.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM banana.paj.test WHERE ' 'banana.paj.test.id", "\"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(1,1), \" \"id2", "(SELECT ' 't1.col3 AS col3, t1.col4 AS col4 FROM t1", "String(128))) i = insert( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(i, 'INSERT INTO", "primary_key=True), schema='paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM paj.test WHERE paj.test.id", "'SELECT sometable.somecolumn FROM sometable') def test_select_with_nolock(self): t = table('sometable', column('somecolumn'))", "t2 WHERE t1.x = t2.x)\" \") AS mssql_rn \" \"FROM", "= MetaData() tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True),", ") c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t1.c.x in set(c._create_result_map()['x'][1])", "column('foo')) for expr, compile in [ ( select([literal(\"x\"), literal(\"y\")]), \"SELECT", "column(\"c\", Integer), ) join = t1.join(t2, t1.c.a == t2.c.a).\\ select().with_hint(t1,", "':somecolumn_1', dict(somecolumn=10)) def test_insert_hint(self): t = table('sometable', column('somecolumn')) for targ", "insert( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT", "TABLE test (x INTEGER NOT NULL, y INTEGER NULL, \"", "m, Column('x', Integer)) expr1 = func.foo(t.c.x).label('x') expr2 = func.foo(t.c.x).label('y') stmt1", "tbl.c.x.desc(), \"y\") self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test (x DESC,", "'mytable', column('myid', Integer), column('name', String(128)), column('description', String(128))) i = insert(", "\"SELECT sometable.foo FROM sometable WHERE sometable.foo \" \"IN ('x', 'y',", "val=\" \"[#other].newval FROM [schema].sometable, \" \"[#other] WHERE [schema].sometable.sym = [#other].sym\",", "AS anon_1 \" \"WHERE mssql_rn > :param_1 AND mssql_rn <=", "= table( 't2', column('col1'), column('col2'), column('col3'), column('col4')) s1, s2 =", "self._column_spec()) def test_that_mssql_specified_nullable_emits_null(self): self.column.nullable = True eq_(\"test_column VARCHAR(max) NULL\", self._column_spec())", "TOP 0 t.x, t.y FROM t WHERE t.x = :x_1", ") def test_table_uc_explicit_nonclustered(self): metadata = MetaData() tbl = Table('test', metadata,", "Sequence('', start=5), primary_key=False)) with testing.expect_deprecated( \"Use of Sequence with SQL", "def test_table_pkc_clustering(self): metadata = MetaData() tbl = Table('test', metadata, Column('x',", "yet. # def test_delete_from_hint(self): # t = table('sometable', column('somecolumn')) #", "KEY NONCLUSTERED (x, y))\" ) def test_table_idx_explicit_nonclustered(self): metadata = MetaData()", "from sqlalchemy.dialects import mssql from sqlalchemy.dialects.mssql import mxodbc from sqlalchemy.testing", "Integer, Sequence('', start=5), primary_key=False)) with testing.expect_deprecated( \"Use of Sequence with", "= MetaData() tbl = Table('test', metadata, Column('id', Integer, autoincrement=False, primary_key=True))", "m = MetaData() t = Table('sometable', m, Column('somecolumn', Integer), schema='test_schema')", "OUTPUT deleted.myid, ' 'deleted.name') d = delete(table1).where(table1.c.name == 'bar' ).returning(table1.c.myid,", "' '(:name)') def test_limit_using_top(self): t = table('t', column('x', Integer), column('y',", "select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" ) def test_schema_autosplit_w_dot_case_insensitive(self): metadata =", "test_limit_zero_offset_using_window(self): t = table('t', column('x', Integer), column('y', Integer)) s =", "field) def test_update_returning(self): table1 = table( 'mytable', column('myid', Integer), column('name',", "def test_select_w_order_by_collate(self): m = MetaData() t = Table('sometable', m, Column('somecolumn',", "table('sometable', column('somecolumn')) self.assert_compile(t.update(t.c.somecolumn == 7), 'UPDATE sometable SET somecolumn=:somecolum' 'n", "> :param_1\" ) self.assert_compile( stmt2, \"SELECT anon_1.y FROM (SELECT foo(t.x)", "y))\" ) def test_table_pkc_explicit_nonclustered(self): metadata = MetaData() tbl = Table('test',", ":name_1') def test_insert_returning(self): table1 = table( 'mytable', column('myid', Integer), column('name',", "t.x = :x_1) AS anon_1 \" \"WHERE mssql_rn > :param_1", "this is what # the two autoincrements will do right", "\"SELECT TOP 10 t.x, t.y FROM t WHERE t.x =", "this will be rejected by the database, just asserting this", "metadata, Column('id', Integer, mssql_identity_increment=5, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "VALUES (:somecolumn)\" ) def test_update_hint(self): t = table('sometable', column('somecolumn')) for", ") self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" ) def test_schema_autosplit_w_dot_case_insensitive(self):", "in (None, t): for darg in (\"*\", \"mssql\"): self.assert_compile( t.delete().where(t.c.somecolumn", "\"SELECT [foo.dbo].test.id FROM [foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_insensitive(self): metadata = MetaData()", "Table('test', metadata, Column('id', Integer, mssql_identity_start=0, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "1) self.assert_compile( tbl.delete().where(tbl.c.id.in_(s)), \"DELETE FROM [banana split].[paj with a space].test", "OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description VALUES (:name)') i =", "# this will be rejected by the database, just asserting", "self.assert_compile(t.select().where(t.c.somecolumn == t.select()), 'SELECT sometable.somecolumn FROM ' 'sometable WHERE sometable.somecolumn", "' 'deleted.name WHERE mytable.name = :name_1') def test_insert_returning(self): table1 =", "Column('id', Integer, primary_key=True), schema=\"Foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT [Foo].dbo.test.id FROM", "test_identity_no_primary_key(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "FROM t2 WHERE t1.x = t2.x)\" \") AS mssql_rn \"", "a1\") def test_update_from_hint(self): t = table('sometable', column('somecolumn')) t2 = table('othertable',", "Integer)) idx = Index(\"foo\", tbl.c.id, mssql_clustered=True) self.assert_compile(schema.CreateIndex(idx), \"CREATE CLUSTERED INDEX", "'test', metadata, Column('id', Integer, primary_key=True), schema=\"foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT", "'DELETE FROM paj.test WHERE paj.test.id IN ' '(SELECT paj.test.id FROM", "s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10) self.assert_compile( s, \"SELECT TOP 10", "[#other] \" \"WHERE [schema].sometable.sym = [#other].sym)\", ) stmt = table.update().values(val=other.c.newval).\\", "== 5).order_by(t.c.y).limit(0) self.assert_compile( s, \"SELECT TOP 0 t.x, t.y FROM", "c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1]) def", "(id))\" ) def test_primary_key_defaults_to_identity(self): metadata = MetaData() tbl = Table('test',", "(id INTEGER NOT NULL IDENTITY(0,1), \" \"PRIMARY KEY (id))\" )", "test (x DESC, y)\" ) def test_create_index_expr(self): m = MetaData()", "selectable=targ, dialect_name=darg), \"INSERT INTO sometable WITH (PAGLOCK) \" \"(somecolumn) VALUES", "UNION ' 'SELECT t2.col3 AS col3, t2.col4 AS col4 '", "def test_in_with_subqueries(self): \"\"\"Test removal of legacy behavior that converted \"x==subquery\"", "# selectable=t2, # dialect_name=darg), # \"\" # ) def test_strict_binds(self):", "PrimaryKeyConstraint, \\ UniqueConstraint, Index, Sequence, literal from sqlalchemy import testing", "' '(:name)') i = insert(table1, values=dict(name='foo')).returning(table1) self.assert_compile(i, 'INSERT INTO mytable", "'test', metadata, Column('id', Integer, primary_key=True), schema='banana split.paj') self.assert_compile(tbl.delete(tbl.c.id == 1),", "select([t]).where(t.c.foo.in_(['x', 'y', 'z'])), \"SELECT sometable.foo FROM sometable WHERE sometable.foo \"", "a1, t2 WHERE a1.c1 = t2.c1\" ) self.assert_compile(sql.delete(a1), \"DELETE FROM", "\"(SELECT [#other].newval FROM [#other] \" \"WHERE [schema].sometable.sym = [#other].sym)\", )", "tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"foo.dbo\", True)", "a space].test.id \" \"FROM [banana split].[paj with a space].test \"", "test_identity_increment_5(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "Integer, Sequence('', start=5), nullable=True)) with testing.expect_deprecated( \"Use of Sequence with", "other.c.sym).as_scalar()) self.assert_compile( stmt, \"UPDATE [schema].sometable SET val=\" \"(SELECT [#other].newval FROM", "(None, t): for darg in (\"*\", \"mssql\"): self.assert_compile( t.insert(). values(somecolumn=\"x\").", "= table('sometable', column('foo')) for expr, compile in [ ( select([literal(\"x\"),", "= sql.delete(t1).where(t1.c.c1 == t2.c.c1) self.assert_compile( q, \"DELETE FROM t1 FROM", "\" \"x INTEGER NOT NULL IDENTITY(1,1), \" \"PRIMARY KEY (id))\"", "MetaData,\\ update, delete, insert, extract, union, func, PrimaryKeyConstraint, \\ UniqueConstraint,", "metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer, autoincrement=True),", "= table( 'mytable', column('myid', Integer), column('name', String(128)), column('description', String(128))) d", "'n WHERE sometable.somecolumn = ' ':somecolumn_1', dict(somecolumn=10)) def test_insert_hint(self): t", "anon_1.y \" \"FROM (SELECT t1.x AS x, t1.y AS y,", "\"Latin1_General_CS_AS_KS_WS_CI ASC\" ) def test_join_with_hint(self): t1 = table('t1', column('a', Integer),", ") def test_delete_extra_froms_alias(self): a1 = table('t1', column('c1')).alias('a1') t2 = table('t2',", "Index(\"foo\", tbl.c.x, mssql_include=['y']) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test (x)", "'DELETE FROM [banana split].[paj with a ' 'space].test WHERE [banana", "KEY (id))\" ) def test_identity_illegal_two_autoincrements(self): metadata = MetaData() tbl =", "in set(c._create_result_map()['y'][1]) def test_limit_offset_w_ambiguous_cols(self): t = table('t', column('x', Integer), column('y',", "self.assert_compile( q, \"DELETE FROM t1 FROM t1, t2 WHERE t1.c1", "INTEGER NOT NULL IDENTITY(5,1))\" ) def test_sequence_ignore_nullability(self): metadata = MetaData()", "self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL, \"", "self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(5,1))\"", "!= t.select()), 'SELECT sometable.somecolumn FROM ' 'sometable WHERE sometable.somecolumn !=", "True) ) self.assert_compile( select([tbl]), \"SELECT [foo.dbo].test.id FROM [foo.dbo].test\" ) def", "== 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM paj.test WHERE paj.test.id IN '", "BY t.y\", checkparams={'x_1': 5} ) def test_primary_key_no_identity(self): metadata = MetaData()", "(x INTEGER NOT NULL, y INTEGER NULL, \" \"PRIMARY KEY", "test_table_idx_explicit_nonclustered(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('x',", "TABLE test (x INTEGER NOT NULL, y INTEGER NOT NULL,", "String(128)), column('description', String(128))) d = delete(table1).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM", "FROM t' % field) def test_update_returning(self): table1 = table( 'mytable',", "inserted.name, ' 'inserted.description WHERE mytable.name = ' ':name_1') u =", ":somecolumn_1\" ) def test_delete_extra_froms(self): t1 = table('t1', column('c1')) t2 =", "[t.c.x, t.c.x.label('q'), t.c.x.label('p'), t.c.y] s = select(cols).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile(", "\"\"\"test that the ms-sql dialect removes ORDER BY clauses from", "name='foo')).returning(table1).where(table1.c.name == 'bar') self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT '", "Table('t', m, Column('x', Integer)) expr1 = func.foo(t.c.x).label('x') expr2 = func.foo(t.c.x).label('y')", ") def test_index_extra_include_1(self): metadata = MetaData() tbl = Table( 'test',", "\" \"sometable.somecolumn = :somecolumn_1\" ) def test_delete_extra_froms(self): t1 = table('t1',", "anon_1.x, anon_1.y \" \"FROM (SELECT t1.x AS x, t1.y AS", "[foo.dbo].test\" ) def test_force_schema_quoted_name_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table(", "String) ) self.column = t.c.test_column dialect = mssql.dialect() self.ddl_compiler =", "WHERE t2.col2 IN ' '(:col2_3, :col2_4) ORDER BY col3, col4')", "schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL, \" \"x", "t2 WHERE a1.c1 = t2.c1\" ) self.assert_compile(sql.delete(a1), \"DELETE FROM t1", "'space].test WHERE [banana split].[paj ' 'with a space].test.id = :id_1')", "values=dict( name='foo')).returning(table1).where(table1.c.name == 'bar') self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT", "column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).offset(20) # test that", "\"PRIMARY KEY (id))\" ) def test_identity_increment_5(self): metadata = MetaData() tbl", "schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(1,5), \"", "= Table( 'test', metadata, Column('x', Integer), Column('y', Integer), Column('z', Integer))", "= s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 4) result_map = c._create_result_map() for col in", "assert t.c.x in set(c._create_result_map()['x'][1]) def test_offset_using_window(self): t = table('t', column('x',", "test_identity_illegal_two_autoincrements(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "set(c._create_result_map()['y'][1]) def test_limit_offset_w_ambiguous_cols(self): t = table('t', column('x', Integer), column('y', Integer))", "sql.true(), \"1\" ) def test_select(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.select(),", "(\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ,", "select is not altered with subsequent compile # calls for", "def test_index_extra_include_2(self): metadata = MetaData() tbl = Table( 'test', metadata,", "tbl = Table('test', metadata, Column('id', Integer, Sequence('', start=5), nullable=True)) with", "== 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.y \" \"FROM (SELECT", "mytable SET name=:name OUTPUT ' 'inserted.myid, inserted.name') u = update(table1,", "FROM [schema].sometable, \" \"[#other] WHERE [schema].sometable.sym = [#other].sym\", ) #", "= ' ':id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE", "c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1]) assert", "IDENTITY(0,1), \" \"PRIMARY KEY (id))\" ) def test_sequence_non_primary_key(self): metadata =", ") self.column = t.c.test_column dialect = mssql.dialect() self.ddl_compiler = dialect.ddl_compiler(dialect,", "dialect=mxodbc_dialect) def test_in_with_subqueries(self): \"\"\"Test removal of legacy behavior that converted", "Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x,", "primary_key=True), schema=\"[Foo.dbo]\" ) self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" )", "= select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0).offset(0) # render the LIMIT of zero,", "\"FROM (SELECT t.x AS x, t.y AS y, \" \"ROW_NUMBER()", "[schema].sometable.sym = [#other].sym\", ) # TODO: not supported yet. #", "== 'bar') self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT ' 'inserted.myid,", "(\"*\", \"mssql\"): # self.assert_compile( # t.delete().where(t.c.somecolumn==t2.c.somecolumn). # with_hint(\"WITH (PAGLOCK)\", #", "0 t.x, t.y FROM t \" \"WHERE t.x = :x_1", "table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT '", "MetaData() t = Table('t', m, Column('x', Integer)) expr1 = func.foo(t.c.x).label('x')", "test (id)\" ) def test_index_ordering(self): metadata = MetaData() tbl =", "will be rejected by the database, just asserting this is", "a1 FROM t1 AS a1, t2 WHERE a1.c1 = t2.c1\"", "metadata, Column('id', Integer, primary_key=True), schema=\"Foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT [Foo].dbo.test.id", "tbl.c.x, tbl.c.y, mssql_clustered=False) self.assert_compile( schema.CreateIndex(idx), \"CREATE NONCLUSTERED INDEX myidx ON", "table('sometable', column('somecolumn')) self.assert_compile(t.count(), 'SELECT count(sometable.somecolumn) AS ' 'tbl_row_count FROM sometable')", "(SELECT banana.paj.test.id ' 'FROM banana.paj.test WHERE ' 'banana.paj.test.id = :id_1)')", "Table('sometable', m, Column('somecolumn', Integer), schema='test_schema') self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT", "join, 'SELECT t1.a, t1.b, t1.c, t2.a, t2.b, t2.c ' 'FROM", "from sqlalchemy import Integer, String, Table, Column, select, MetaData,\\ update,", "table( 't1', column('col1'), column('col2'), column('col3'), column('col4')) t2 = table( 't2',", "= :id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM", "y))\" ) def test_table_idx_explicit_nonclustered(self): metadata = MetaData() tbl = Table(", "from subqueries\"\"\" table1 = table('mytable', column('myid', Integer), column('name', String), column('description',", "FROM mytable) AS foo, mytable WHERE \" \"foo.myid = mytable.myid\")", "\"SELECT [Foo].dbo.test.id FROM [Foo].dbo.test\" ) def test_owner_database_pairs(self): dialect = mssql.dialect()", "with_hint(\"WITH (PAGLOCK)\", selectable=t2, dialect_name=darg), \"UPDATE sometable SET somecolumn=:somecolumn \" \"FROM", "def test_join_with_hint(self): t1 = table('t1', column('a', Integer), column('b', String), column('c',", "[banana split].paj.test.id FROM ' '[banana split].paj.test WHERE ' '[banana split].paj.test.id", "schema=\"foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT foo.dbo.test.id FROM foo.dbo.test\" ) def", ":id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile( tbl.delete().where(tbl.c.id.in_(s)), \"DELETE FROM", "5} ) def test_limit_zero_using_top(self): t = table('t', column('x', Integer), column('y',", "with a ' 'space].test WHERE [banana split].[paj ' 'with a", "= s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t1.c.x in set(c._create_result_map()['x'][1]) assert t1.c.y", "select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM paj.test WHERE paj.test.id IN", "col3, t2.col4 AS col4 ' 'FROM t2 WHERE t2.col2 IN", "Sequence('', start=5), nullable=True)) with testing.expect_deprecated( \"Use of Sequence with SQL", "AS a1\") def test_update_from_hint(self): t = table('sometable', column('somecolumn')) t2 =", "self.assert_compile(func.current_time(), 'CURRENT_TIME') self.assert_compile(func.foo(), 'foo()') m = MetaData() t = Table(", "\" \"PRIMARY KEY (id))\" ) def test_sequence_start_0(self): metadata = MetaData()", "[banana split].[paj with a space].test.id \" \"FROM [banana split].[paj with", "length_1 VALUES ' '(:name)') def test_limit_using_top(self): t = table('t', column('x',", "test_create_index_expr(self): m = MetaData() t1 = Table('foo', m, Column('x', Integer)", "Index(\"foo\", tbl.c.x.desc(), \"y\") self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test (x", "[banana split].[paj with a space].test \" \"WHERE [banana split].[paj with", "\"WHERE t1.x = :x_1) AS anon_1 \" \"WHERE mssql_rn >", "schema=\"schema\" ) other = Table( \"#other\", meta, Column(\"sym\", String), Column(\"newval\",", "[Foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table(", "5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 4) result_map = c._create_result_map()", "test_table_pkc_clustering(self): metadata = MetaData() tbl = Table('test', metadata, Column('x', Integer,", "VARCHAR(max)\", self._column_spec()) def test_that_mssql_specified_nullable_emits_null(self): self.column.nullable = True eq_(\"test_column VARCHAR(max) NULL\",", "MetaData() tbl = Table('test', metadata, Column('id', Integer, autoincrement=True), Column('id2', Integer,", "Integer), Column('test_column', String) ) self.column = t.c.test_column dialect = mssql.dialect()", "t1.x AS x, t1.y AS y, \" \"ROW_NUMBER() OVER (ORDER", "metadata, Column('x', Integer), Column('y', Integer), Column('z', Integer)) idx = Index(\"foo\",", "meta = MetaData() table = Table( \"sometable\", meta, Column(\"sym\", String),", "' 'LEN(inserted.name) AS length_1 VALUES ' '(:name)') def test_limit_using_top(self): t", "= table( 'mytable', column('myid', Integer), column('name', String(128)), column('description', String(128))) i", "t.x AS q, t.x AS p, t.y AS y, \"", "is_ from sqlalchemy import schema from sqlalchemy.sql import table, column,", "WITH (PAGLOCK) \" \"SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn = :somecolumn_1\"", "WITH (NOLOCK)') def test_select_w_order_by_collate(self): m = MetaData() t = Table('sometable',", "Column('id', Integer, primary_key=True), schema='banana.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM banana.paj.test", "'inserted.description WHERE mytable.name = ' ':name_1') u = update(table1, values=dict(name='foo'", "test_sequence_start_0(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "i in range(2): self.assert_compile( s, \"SELECT anon_1.x, anon_1.y FROM (SELECT", "test_delete_schema_multipart_needs_quoting(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('id',", "Integer), column('y', Integer)) cols = [t.c.x, t.c.x.label('q'), t.c.x.label('p'), t.c.y] s", "test (id INTEGER NOT NULL IDENTITY(1,1), \" \"id2 INTEGER NOT", "NULL, y INTEGER NULL, \" \"UNIQUE NONCLUSTERED (x, y))\" )", "fixtures, AssertsCompiledSQL from sqlalchemy import sql from sqlalchemy import Integer,", "Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0).offset(0) # render", "\"SELECT anon_1.x, anon_1.y \" \"FROM (SELECT t.x AS x, t.y", "Column('id', Integer, autoincrement=False, primary_key=True), Column('x', Integer, autoincrement=True) ) self.assert_compile( schema.CreateTable(tbl),", "mssql_identity_increment=5, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT", "update(table1, values=dict(name='foo')).returning(table1) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT ' 'inserted.myid,", "[banana split].[paj with a space].test.id IN \" \"(SELECT [banana split].[paj", "MetaData() tbl = Table('test', metadata, Column('id', Integer)) idx = Index(\"foo\",", "= table('t2', column(\"a\", Integer), column(\"b\", Integer), column(\"c\", Integer), ) join", "self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM banana.paj.test WHERE ' 'banana.paj.test.id IN (SELECT banana.paj.test.id", "mxodbc_dialect = mxodbc.dialect() mxodbc_dialect.statement_compiler = MSSQLStrictCompiler t = table('sometable', column('foo'))", "s2, order_by=['col3', 'col4']) self.assert_compile(u, 'SELECT t1.col3 AS col3, t1.col4 AS", "= mssql.dialect() def test_true_false(self): self.assert_compile( sql.false(), \"0\" ) self.assert_compile( sql.true(),", "TOP 0 t.x, t.y FROM t \" \"WHERE t.x =", "__dialect__ = mssql.dialect() def test_true_false(self): self.assert_compile( sql.false(), \"0\" ) self.assert_compile(", "PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER", "NOT NULL, \" \"PRIMARY KEY (id))\" ) def test_primary_key_defaults_to_identity(self): metadata", "'test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False) ) idx", "t1.col2 IN (:col2_1, ' ':col2_2) UNION SELECT t2.col3 AS col3,", "legacy behavior that converted \"x==subquery\" to use IN. \"\"\" t", "WHERE t.x = :x_1) AS \" \"anon_1 WHERE mssql_rn >", "def test_count(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.count(), 'SELECT count(sometable.somecolumn) AS", "t1 = Table('foo', m, Column('x', Integer) ) self.assert_compile( schema.CreateIndex(Index(\"bar\", t1.c.x", "self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT ' 'LEN(inserted.name) AS length_1", "= t2.a' ) def test_insert(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.insert(),", "t = Table('sometable', m, Column('somecolumn', Integer), schema='test_schema') self.assert_compile( t.select().with_hint(t, 'WITH", "t2.c ' 'FROM t1 WITH (NOLOCK) JOIN t2 ON t1.a", "t1 AS a1, t2 WHERE a1.c1 = t2.c1\" ) self.assert_compile(sql.delete(a1),", "[banana split].paj.test WHERE ' '[banana split].paj.test.id = :id_1') s =", "== 5).order_by(order_by) \\ .limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.y \"", "\"PRIMARY KEY (id))\" ) def test_identity_no_primary_key(self): metadata = MetaData() tbl", ":id_1)') def test_delete_schema_multipart_both_need_quoting(self): metadata = MetaData() tbl = Table('test', metadata,", "(x, y)\" ) def test_table_uc_explicit_nonclustered(self): metadata = MetaData() tbl =", "INTEGER NOT NULL, \" \"PRIMARY KEY (id))\" ) def test_primary_key_defaults_to_identity(self):", "test (id INTEGER NOT NULL IDENTITY(5,1))\" ) def test_table_pkc_clustering(self): metadata", "for darg in (\"*\", \"mssql\"): self.assert_compile( t.delete().where(t.c.somecolumn == \"q\"). with_hint(\"WITH", "= table('sometable', column('somecolumn')) t2 = table('othertable', column('somecolumn')) for darg in", "'LEN(inserted.name) AS length_1 VALUES ' '(:name)') def test_limit_using_top(self): t =", ") self.assert_compile( stmt2, \"SELECT anon_1.y FROM (SELECT foo(t.x) AS y,", "\" \"WHERE mssql_rn > :param_1 AND mssql_rn <= :param_2 +", "\"WHERE sometable.somecolumn = othertable.somecolumn\" ) def test_update_to_select_schema(self): meta = MetaData()", "' 'SELECT t2.col3 AS col3, t2.col4 AS col4 ' 'FROM", "self.assert_compile(select(['*'], crit), \"SELECT * FROM (SELECT mytable.myid AS \" \"myid", "!= ' '(SELECT sometable.somecolumn FROM ' 'sometable)') @testing.uses_deprecated def test_count(self):", "AS mssql_rn \" \"FROM t \" \"WHERE t.x = :x_1)", "= MetaData() tbl = Table('test', metadata, Column('id', Integer, primary_key=True), schema='paj')", "column('y', Integer)) order_by = select([t2.c.y]).where(t1.c.x == t2.c.x).as_scalar() s = select([t1]).where(t1.c.x", "sometable.somecolumn = ' ':somecolumn_1', dict(somecolumn=10)) def test_insert_hint(self): t = table('sometable',", "def test_table_idx_explicit_nonclustered(self): metadata = MetaData() tbl = Table( 'test', metadata,", "\"x INTEGER NOT NULL IDENTITY(1,1), \" \"PRIMARY KEY (id))\" )", "(SELECT t.x AS x, t.x AS q, t.x AS p,", "idx = Index(\"myidx\", tbl.c.x, tbl.c.y, mssql_clustered=False) self.assert_compile( schema.CreateIndex(idx), \"CREATE NONCLUSTERED", "return self.ddl_compiler.get_column_specification(self.column) def test_that_mssql_default_nullability_emits_null(self): eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_none_nullability_does_not_emit_nullability(self):", "column('c1')) q = sql.delete(t1).where(t1.c.c1 == t2.c.c1) self.assert_compile( q, \"DELETE FROM", "'(SELECT sometable.somecolumn FROM ' 'sometable)') self.assert_compile(t.select().where(t.c.somecolumn != t.select()), 'SELECT sometable.somecolumn", "VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_none_nullability_does_not_emit_nullability(self): self.column.nullable = None eq_(\"test_column VARCHAR(max)\",", "test_limit_offset_with_correlated_order_by(self): t1 = table('t1', column('x', Integer), column('y', Integer)) t2 =", "tbl = Table('test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False),", "' 'banana.paj.test.id IN (SELECT banana.paj.test.id ' 'FROM banana.paj.test WHERE '", "schema from sqlalchemy.sql import table, column, quoted_name from sqlalchemy.dialects import", "test_update_from_hint(self): t = table('sometable', column('somecolumn')) t2 = table('othertable', column('somecolumn')) for", "import fixtures, AssertsCompiledSQL from sqlalchemy import sql from sqlalchemy import", "(\"Foo.Bar\", \"Foo\", \"Bar\"), (\"[Foo.Bar]\", None, \"Foo.Bar\"), (\"[Foo.Bar].[bat]\", \"Foo.Bar\", \"bat\"), ]:", "def test_delete_extra_froms_alias(self): a1 = table('t1', column('c1')).alias('a1') t2 = table('t2', column('c1'))", "'deleted.name') d = delete(table1).where(table1.c.name == 'bar' ).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE", "Integer, autoincrement=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT", "self.assert_compile( schema.DropIndex(Index(\"idx_foo\", t1.c.x)), \"DROP INDEX idx_foo ON bar.foo\" ) def", "mytable.myid\") def test_force_schema_quoted_name_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table( 'test',", "\"ROW_NUMBER() OVER (ORDER BY foo(t.x) DESC) AS mssql_rn FROM t)", ") def test_index_extra_include_2(self): metadata = MetaData() tbl = Table( 'test',", "INTEGER NOT NULL, \" \"PRIMARY KEY NONCLUSTERED (x, y))\" )", "eq_(schema, expected_schema) def test_delete_schema(self): metadata = MetaData() tbl = Table('test',", "with_hint(\"XYZ\", \"mysql\"), \"UPDATE sometable SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn =", "KEY (id))\" ) def test_identity_no_primary_key(self): metadata = MetaData() tbl =", "table('sometable', column('somecolumn')) self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"XYZ\", \"mysql\"), \"UPDATE", "paj.test.id = ' ':id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)),", "checkparams={'param_1': 20, 'param_2': 10, 'x_1': 5} ) c = s.compile(dialect=mssql.dialect())", "WHERE mssql_rn > :param_1\" ) def test_limit_zero_offset_using_window(self): t = table('t',", "= base._owner_plus_db(dialect, identifier) eq_(owner, expected_owner) eq_(schema, expected_schema) def test_delete_schema(self): metadata", "def test_limit_using_top(self): t = table('t', column('x', Integer), column('y', Integer)) s", "( t.c.foo.in_([None]), \"sometable.foo IN (NULL)\" ) ]: self.assert_compile(expr, compile, dialect=mxodbc_dialect)", ") self.assert_compile( select([tbl]), \"SELECT [foo.dbo].test.id FROM [foo.dbo].test\" ) def test_force_schema_quoted_name_w_dot_case_sensitive(self):", "affect \"): self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT", "\"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(0,1), \" \"PRIMARY", "self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"XYZ\", \"mysql\"), \"UPDATE sometable SET", "String), column('description', String), ) q = select([table1.c.myid], order_by=[table1.c.myid]).alias('foo') crit =", "BY t.y) AS \" \"mssql_rn FROM t WHERE t.x =", "[#other].newval FROM [#other] \" \"WHERE [schema].sometable.sym = [#other].sym)\", ) stmt", "MSSQLStrictCompiler mxodbc_dialect = mxodbc.dialect() mxodbc_dialect.statement_compiler = MSSQLStrictCompiler t = table('sometable',", "quoted_name from sqlalchemy.dialects import mssql from sqlalchemy.dialects.mssql import mxodbc from", "AS y, \" \"ROW_NUMBER() OVER (ORDER BY t.y) AS mssql_rn", "= update( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(u, 'UPDATE mytable SET name=:name", "self.assert_compile(expr, compile, dialect=mxodbc_dialect) def test_in_with_subqueries(self): \"\"\"Test removal of legacy behavior", "\"ROW_NUMBER() OVER (ORDER BY t.y) AS mssql_rn \" \"FROM t", "(SELECT t1.x AS x, t1.y AS y, \" \"ROW_NUMBER() OVER", "\"CREATE INDEX bar ON foo (x > 5)\" ) def", "(PAGLOCK) \" \"SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn = :somecolumn_1\" )", "split.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM [banana split].paj.test WHERE '", "t.y FROM t WHERE t.x = :x_1 ORDER BY t.y\",", "y)\" ) def test_create_index_expr(self): m = MetaData() t1 = Table('foo',", "paj.test.id = :id_1)') def test_delete_schema_multipart(self): metadata = MetaData() tbl =", "t1.c.x in set(c._create_result_map()['x'][1]) assert t1.c.y in set(c._create_result_map()['y'][1]) def test_offset_dont_misapply_labelreference(self): m", "column('x', Integer), column('y', Integer)) cols = [t.c.x, t.c.x.label('q'), t.c.x.label('p'), t.c.y]", "compile # calls for i in range(2): self.assert_compile( s, \"SELECT", "import base class CompileTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = mssql.dialect() def test_true_false(self):", "NULL IDENTITY(5,1))\" ) def test_table_pkc_clustering(self): metadata = MetaData() tbl =", "FROM [foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_insensitive(self): metadata = MetaData() tbl =", "'WITH (NOLOCK)') self.assert_compile( join, 'SELECT t1.a, t1.b, t1.c, t2.a, t2.b,", "test_delete_hint(self): t = table('sometable', column('somecolumn')) for targ in (None, t):", "MetaData() tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"foo.dbo\"", "'x' AS anon_1, 'y' AS anon_2\", ), ( select([t]).where(t.c.foo.in_(['x', 'y',", "TABLE test (x INTEGER NULL, y INTEGER NULL, \" \"UNIQUE", "tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema='banana split.paj')", "compile, dialect=mxodbc_dialect) def test_in_with_subqueries(self): \"\"\"Test removal of legacy behavior that", "Integer, autoincrement=False, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER", "\"q\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"DELETE FROM sometable WITH (PAGLOCK)", "def test_insert(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.insert(), 'INSERT INTO sometable", "expected_owner in [ (\"foo\", None, \"foo\"), (\"foo.bar\", \"foo\", \"bar\"), (\"Foo.Bar\",", "'param_2': 10, 'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2)", "schema.DropIndex(Index(\"idx_foo\", t1.c.x)), \"DROP INDEX idx_foo ON bar.foo\" ) def test_index_extra_include_1(self):", "Column('y', Integer, autoincrement=False), UniqueConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "NOT NULL, y INTEGER NOT NULL, \" \"PRIMARY KEY CLUSTERED", "in set(c._create_result_map()['x'][1]) assert t.c.y in set(c._create_result_map()['y'][1]) def test_limit_offset_w_ambiguous_cols(self): t =", "with_hint(\"WITH (PAGLOCK)\", # selectable=t2, # dialect_name=darg), # \"\" # )", "Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "5).order_by(t.c.y).limit(0) self.assert_compile( s, \"SELECT TOP 0 t.x, t.y FROM t", "'WITH (NOLOCK)'), 'SELECT test_schema.sometable.somecolumn ' 'FROM test_schema.sometable WITH (NOLOCK)') def", "literal(\"y\")]), \"SELECT 'x' AS anon_1, 'y' AS anon_2\", ), (", "FROM [Foo.dbo].test\" ) def test_schema_autosplit_w_dot_case_insensitive(self): metadata = MetaData() tbl =", "FROM sometable WITH (PAGLOCK) \" \"WHERE sometable.somecolumn = :somecolumn_1\" )", "q, \"DELETE FROM a1 FROM t1 AS a1, t2 WHERE", "t2 = table( 't2', column('col1'), column('col2'), column('col3'), column('col4')) s1, s2", "Integer, autoincrement=False, primary_key=True), Column('x', Integer, autoincrement=True) ) self.assert_compile( schema.CreateTable(tbl), \"CREATE", "5).order_by(t.c.y).limit(0).offset(0) # render the LIMIT of zero, but not the", "\"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_delete_exclude_hint(self): t = table('sometable',", "WHERE a1.c1 = t2.c1\" ) self.assert_compile(sql.delete(a1), \"DELETE FROM t1 AS", "WHERE mssql_rn > :param_1\", checkparams={'param_1': 20, 'x_1': 5} ) c", "Table('test', metadata, Column('id', Integer, autoincrement=False, primary_key=True), Column('x', Integer, autoincrement=True) )", "\"FROM sometable, othertable WITH (PAGLOCK) \" \"WHERE sometable.somecolumn = othertable.somecolumn\"", "m = MetaData() t = Table( 'sometable', m, Column('col1', Integer),", "= Table('test', metadata, Column('id', Integer, autoincrement=True), Column('id2', Integer, autoincrement=True), )", "Table('sometable', MetaData(), Column('pk_column', Integer), Column('test_column', String) ) self.column = t.c.test_column", "Integer), Column('y', Integer), Column('z', Integer)) idx = Index(\"foo\", tbl.c.x, mssql_include=['y'])", "clauses from subqueries\"\"\" table1 = table('mytable', column('myid', Integer), column('name', String),", "Integer), Column('y', Integer), Column('z', Integer)) idx = Index(\"foo\", tbl.c.x, mssql_include=[tbl.c.y])", "Table('sometable', m, Column('somecolumn', String)) self.assert_compile( select([t]). order_by( t.c.somecolumn.collate(\"Latin1_General_CS_AS_KS_WS_CI\").asc()), \"SELECT sometable.somecolumn", "@testing.uses_deprecated def test_count(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.count(), 'SELECT count(sometable.somecolumn)", "mytable) AS foo, mytable WHERE \" \"foo.myid = mytable.myid\") def", "a space') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM [banana split].[paj with", "AS foo, mytable WHERE \" \"foo.myid = mytable.myid\") def test_force_schema_quoted_name_w_dot_case_insensitive(self):", "column('col2'), column('col3'), column('col4')) s1, s2 = select( [t1.c.col3.label('col3'), t1.c.col4.label('col4')], t1.c.col2.in_(['t1col2r1',", "Integer), column('y', Integer)) t2 = table('t2', column('x', Integer), column('y', Integer))", "test_primary_key_defaults_to_identity(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "= MetaData() tbl = Table('test', metadata, Column('id', Integer, Sequence('', start=5),", "s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile( tbl.delete().where(tbl.c.id.in_(s)), \"DELETE FROM [banana", "'test', metadata, Column('x', Integer), Column('y', Integer), Column('z', Integer)) idx =", "= insert(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT", "NULL, y INTEGER NOT NULL, \" \"PRIMARY KEY NONCLUSTERED (x,", "Integer), column('name', String(128)), column('description', String(128))) d = delete(table1).returning(table1.c.myid, table1.c.name) self.assert_compile(d,", "BY foo(t.x) DESC) AS mssql_rn FROM t) \" \"AS anon_1", "NULL IDENTITY(1,5), \" \"PRIMARY KEY (id))\" ) def test_sequence_start_0(self): metadata", "stmt = table.update().values( val=select([other.c.newval]). where(table.c.sym == other.c.sym).as_scalar()) self.assert_compile( stmt, \"UPDATE", "= Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"Foo.dbo\", True) )", "self.assert_compile( # t.delete().where(t.c.somecolumn==t2.c.somecolumn). # with_hint(\"WITH (PAGLOCK)\", # selectable=t2, # dialect_name=darg),", "table('t2', column('c1')) q = sql.delete(a1).where(a1.c.c1 == t2.c.c1) self.assert_compile( q, \"DELETE", "Integer, autoincrement=True) ) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER", "== 'bar' ).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM mytable OUTPUT deleted.myid,", "# self.assert_compile( # t.delete().where(t.c.somecolumn==t2.c.somecolumn). # with_hint(\"WITH (PAGLOCK)\", # selectable=t2, #", "MetaData() table = Table( \"sometable\", meta, Column(\"sym\", String), Column(\"val\", Integer),", "INDEX foo ON test (x DESC, y)\" ) def test_create_index_expr(self):", "t2.y FROM t2 WHERE t1.x = t2.x)\" \") AS mssql_rn", "\"WHERE mssql_rn > :param_1 AND mssql_rn <= :param_2 + :param_1\",", "identifier, expected_schema, expected_owner in [ (\"foo\", None, \"foo\"), (\"foo.bar\", \"foo\",", "FROM sometable WHERE \" \"sometable.somecolumn = :somecolumn_1\" ) def test_delete_extra_froms(self):", "c._create_result_map() for col in cols: is_(result_map[col.key][1][0], col) def test_limit_offset_with_correlated_order_by(self): t1", "owner = base._owner_plus_db(dialect, identifier) eq_(owner, expected_owner) eq_(schema, expected_schema) def test_delete_schema(self):", "INTEGER NOT NULL, \" \"x INTEGER NOT NULL IDENTITY(1,1), \"", "Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).offset(20) # test", "= Table('test', metadata, Column('id', Integer, primary_key=True), schema='paj') self.assert_compile(tbl.delete(tbl.c.id == 1),", "in 'day', 'month', 'year': self.assert_compile( select([extract(field, t.c.col1)]), 'SELECT DATEPART(%s, t.col1)", "t.c.y in set(c._create_result_map()['y'][1]) def test_limit_offset_w_ambiguous_cols(self): t = table('t', column('x', Integer),", "'foo(:foo_1, :foo_2)') self.assert_compile(func.current_time(), 'CURRENT_TIME') self.assert_compile(func.foo(), 'foo()') m = MetaData() t", "# with_hint(\"WITH (PAGLOCK)\", # selectable=t2, # dialect_name=darg), # \"\" #", "' '(SELECT sometable.somecolumn FROM ' 'sometable)') self.assert_compile(t.select().where(t.c.somecolumn != t.select()), 'SELECT", "\"sometable.somecolumn = :somecolumn_1\" ) def test_delete_extra_froms(self): t1 = table('t1', column('c1'))", "= Table( \"sometable\", meta, Column(\"sym\", String), Column(\"val\", Integer), schema=\"schema\" )", "= table('t', column('x', Integer), column('y', Integer)) cols = [t.c.x, t.c.x.label('q'),", "Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\"), UniqueConstraint(\"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "def test_select_with_nolock_schema(self): m = MetaData() t = Table('sometable', m, Column('somecolumn',", "\"FROM t \" \"WHERE t.x = :x_1) AS anon_1 \"", "assert t1.c.y in set(c._create_result_map()['y'][1]) def test_offset_dont_misapply_labelreference(self): m = MetaData() t", "Integer, autoincrement=False), Column('y', Integer, autoincrement=False), UniqueConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl),", "bar.foo\" ) def test_index_extra_include_1(self): metadata = MetaData() tbl = Table(", "' '[banana split].paj.test WHERE ' '[banana split].paj.test.id = :id_1)') def", "self.assert_compile(t.select(), 'SELECT sometable.somecolumn FROM sometable') def test_select_with_nolock(self): t = table('sometable',", "Integer, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT", "Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl),", "= sql.delete(a1).where(a1.c.c1 == t2.c.c1) self.assert_compile( q, \"DELETE FROM a1 FROM", "mssql.dialect() for identifier, expected_schema, expected_owner in [ (\"foo\", None, \"foo\"),", "t = table('sometable', column('somecolumn')) self.assert_compile(t.select(), 'SELECT sometable.somecolumn FROM sometable') def", "Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\"), UniqueConstraint(\"y\", mssql_clustered=True)) self.assert_compile(", "== t.select()), 'SELECT sometable.somecolumn FROM ' 'sometable WHERE sometable.somecolumn =", "col) def test_limit_offset_with_correlated_order_by(self): t1 = table('t1', column('x', Integer), column('y', Integer))", "Column('pk_column', Integer), Column('test_column', String) ) self.column = t.c.test_column dialect =", "rejected by the database, just asserting this is what #", "\"UPDATE sometable SET somecolumn=:somecolumn \" \"FROM sometable, othertable WITH (PAGLOCK)", "mytable.name = :name_1') def test_insert_returning(self): table1 = table( 'mytable', column('myid',", "just asserting this is what # the two autoincrements will", "s, \"SELECT TOP 0 t.x, t.y FROM t WHERE t.x", "\"FROM (SELECT t1.x AS x, t1.y AS y, \" \"ROW_NUMBER()", "' ':id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM", "render the LIMIT of zero, but not the OFFSET #", "t1 ' 'WHERE t1.col2 IN (:col2_1, :col2_2) UNION ' 'SELECT", "anon_1.y FROM (SELECT t.x AS x, t.y \" \"AS y,", "= table('t1', column('x', Integer), column('y', Integer)) t2 = table('t2', column('x',", "self.assert_compile( select([tbl]), \"SELECT [foo.dbo].test.id FROM [foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_insensitive(self): metadata", "String(128))) u = update( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(u, 'UPDATE mytable", "0 self.assert_compile( s, \"SELECT TOP 0 t.x, t.y FROM t", "SET name=:name OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description') u =", "in set(c._create_result_map()['x'][1]) def test_limit_offset_using_window(self): t = table('t', column('x', Integer), column('y',", "test_in_with_subqueries(self): \"\"\"Test removal of legacy behavior that converted \"x==subquery\" to", "tbl = Table('test', metadata, Column('id', Integer, mssql_identity_increment=5, primary_key=True)) self.assert_compile( schema.CreateTable(tbl),", "\"FROM [banana split].[paj with a space].test \" \"WHERE [banana split].[paj", "= Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"[Foo.dbo]\" ) self.assert_compile(", "[schema].sometable, \" \"[#other] WHERE [schema].sometable.sym = [#other].sym\", ) # TODO:", "autoincrement=False), Column('y', Integer, autoincrement=False), UniqueConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE", ":x_1 ORDER BY t.y\", checkparams={'x_1': 5} ) def test_limit_zero_using_top(self): t", "the database, just asserting this is what # the two", "anon_2\", ), ( select([t]).where(t.c.foo.in_(['x', 'y', 'z'])), \"SELECT sometable.foo FROM sometable", "values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"INSERT INTO sometable WITH (PAGLOCK)", "t2 = table('t2', column(\"a\", Integer), column(\"b\", Integer), column(\"c\", Integer), )", "AS anon_2\", ), ( select([t]).where(t.c.foo.in_(['x', 'y', 'z'])), \"SELECT sometable.foo FROM", "t WHERE t.x = :x_1 ORDER BY t.y\", checkparams={'x_1': 5}", "table('t2', column('c1')) q = sql.delete(t1).where(t1.c.c1 == t2.c.c1) self.assert_compile( q, \"DELETE", "sometable WITH (PAGLOCK) \" \"SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn =", "\"SELECT [foo.dbo].test.id FROM [foo.dbo].test\" ) def test_force_schema_quoted_name_w_dot_case_sensitive(self): metadata = MetaData()", "set(c._create_result_map()['x'][1]) assert t.c.y in set(c._create_result_map()['y'][1]) def test_limit_offset_w_ambiguous_cols(self): t = table('t',", "inserted.name VALUES ' '(:name)') i = insert(table1, values=dict(name='foo')).returning(table1) self.assert_compile(i, 'INSERT", "test_delete_schema(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "schema='banana split.paj with a space') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM", "IN \" \"(SELECT [banana split].[paj with a space].test.id \" \"FROM", "col4 FROM t2 WHERE t2.col2 IN ' '(:col2_3, :col2_4) ORDER", "'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t1.c.x", "column('somecolumn')) self.assert_compile(t.select(), 'SELECT sometable.somecolumn FROM sometable') def test_select_with_nolock(self): t =", "banana.paj.test WHERE ' 'banana.paj.test.id = :id_1)') def test_delete_schema_multipart_needs_quoting(self): metadata =", "' 'space].test WHERE [banana split].[paj ' 'with a space].test.id =", "AS p, t.y AS y, \" \"ROW_NUMBER() OVER (ORDER BY", "sometable.somecolumn = :somecolumn_1\" ) def test_delete_exclude_hint(self): t = table('sometable', column('somecolumn'))", "= t2.x)\" \") AS mssql_rn \" \"FROM t1 \" \"WHERE", "test_owner_database_pairs(self): dialect = mssql.dialect() for identifier, expected_schema, expected_owner in [", "LIMIT of zero, but not the OFFSET # of zero,", "Column('id', Integer, mssql_identity_increment=5, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id", ") def test_force_schema_quoted_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table( 'test',", "Table('test', metadata, Column('id', Integer, Sequence('', start=5), nullable=True)) with testing.expect_deprecated( \"Use", "bar.col3, bar.col4 FROM (SELECT ' 't1.col3 AS col3, t1.col4 AS", "= update(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT", "NOT NULL, \" \"PRIMARY KEY NONCLUSTERED (x, y))\" ) def", ") def test_delete_exclude_hint(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.delete(). where(t.c.somecolumn", "metadata, Column('id', Integer, primary_key=True), schema='banana split.paj with a space') self.assert_compile(tbl.delete(tbl.c.id", "s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t1.c.x in set(c._create_result_map()['x'][1]) assert t1.c.y in", "NULL IDENTITY(1,1))\" ) def test_identity_start_0(self): metadata = MetaData() tbl =", "test_delete_returning(self): table1 = table( 'mytable', column('myid', Integer), column('name', String(128)), column('description',", "CompileTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = mssql.dialect() def test_true_false(self): self.assert_compile( sql.false(), \"0\"", "def test_owner_database_pairs(self): dialect = mssql.dialect() for identifier, expected_schema, expected_owner in", "t) \" \"AS anon_1 WHERE mssql_rn > :param_1\" ) def", "ON foo (x > 5)\" ) def test_drop_index_w_schema(self): m =", "schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(1,1), \"", "t = table('sometable', column('somecolumn')) t2 = table('othertable', column('somecolumn')) for darg", "\"DELETE FROM t1 AS a1\") def test_update_from_hint(self): t = table('sometable',", "table( 'mytable', column('myid', Integer), column('name', String(128)), column('description', String(128))) u =", "column('myid', Integer), column('name', String(128)), column('description', String(128))) i = insert( table1,", "t2.c.col2.in_(['t2col2r2', 't2col2r3'])) u = union(s1, s2, order_by=['col3', 'col4']) self.assert_compile(u, 'SELECT", "y INTEGER NOT NULL, \" \"PRIMARY KEY NONCLUSTERED (x, y))\"", "def test_delete_from_hint(self): # t = table('sometable', column('somecolumn')) # t2 =", "t): for darg in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == \"q\").", "'INSERT INTO mytable (name) OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description", "= mssql.dialect() self.ddl_compiler = dialect.ddl_compiler(dialect, schema.CreateTable(t)) def _column_spec(self): return self.ddl_compiler.get_column_specification(self.column)", "paj.test.id IN ' '(SELECT paj.test.id FROM paj.test ' 'WHERE paj.test.id", "String, Table, Column, select, MetaData,\\ update, delete, insert, extract, union,", "\"DELETE FROM [banana split].[paj with a space].test \" \"WHERE [banana", "INTEGER NOT NULL, \" \"PRIMARY KEY CLUSTERED (x, y))\" )", ") def test_strict_binds(self): \"\"\"test the 'strict' compiler binds.\"\"\" from sqlalchemy.dialects.mssql.base", "foo(t.x) AS x, \" \"ROW_NUMBER() OVER (ORDER BY foo(t.x) DESC)", ") self.assert_compile( select([tbl]), \"SELECT [foo.dbo].test.id FROM [foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_insensitive(self):", ") self.assert_compile( schema.DropIndex(Index(\"idx_foo\", t1.c.x)), \"DROP INDEX idx_foo ON bar.foo\" )", "Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "MetaData() tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"[Foo.dbo]\"", "\"foo\"), (\"foo.bar\", \"foo\", \"bar\"), (\"Foo.Bar\", \"Foo\", \"Bar\"), (\"[Foo.Bar]\", None, \"Foo.Bar\"),", "Integer), Column('z', Integer)) idx = Index(\"foo\", tbl.c.x.desc(), \"y\") self.assert_compile(schema.CreateIndex(idx), \"CREATE", "self.assert_compile( stmt, \"UPDATE [schema].sometable SET val=\" \"[#other].newval FROM [schema].sometable, \"", "sometable.somecolumn FROM ' 'sometable WHERE sometable.somecolumn != ' '(SELECT sometable.somecolumn", "VALUES ' '(:name)') def test_limit_using_top(self): t = table('t', column('x', Integer),", "q, t.x AS p, t.y AS y, \" \"ROW_NUMBER() OVER", "(id INTEGER NOT NULL IDENTITY(1,1)\" \")\" ) def test_identity_separate_from_primary_key(self): metadata", "\"SELECT TOP 0 t.x, t.y FROM t WHERE t.x =", "String(128)), column('description', String(128))) i = insert( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(i,", ") def test_sequence_ignore_nullability(self): metadata = MetaData() tbl = Table('test', metadata,", "t.y\", checkparams={'x_1': 5} ) def test_primary_key_no_identity(self): metadata = MetaData() tbl", "self.assert_compile(t.insert(), 'INSERT INTO sometable (somecolumn) VALUES ' '(:somecolumn)') def test_update(self):", "a ' 'space].test WHERE [banana split].[paj ' 'with a space].test.id", "eq_(owner, expected_owner) eq_(schema, expected_schema) def test_delete_schema(self): metadata = MetaData() tbl", "self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER NULL, y INTEGER", "CLUSTERED INDEX foo ON test (id)\" ) def test_index_ordering(self): metadata", "IN. \"\"\" t = table('sometable', column('somecolumn')) self.assert_compile(t.select().where(t.c.somecolumn == t.select()), 'SELECT", "assert t.c.x in set(c._create_result_map()['x'][1]) def test_limit_offset_using_window(self): t = table('t', column('x',", "q.c.myid == table1.c.myid self.assert_compile(select(['*'], crit), \"SELECT * FROM (SELECT mytable.myid", "Integer), Column('z', Integer)) idx = Index(\"foo\", tbl.c.x, mssql_include=['y']) self.assert_compile(schema.CreateIndex(idx), \"CREATE", "eq_(len(c._result_columns), 4) result_map = c._create_result_map() for col in cols: is_(result_map[col.key][1][0],", "values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"UPDATE sometable WITH (PAGLOCK) \"", "(id INTEGER NOT NULL IDENTITY(5,1))\" ) def test_table_pkc_clustering(self): metadata =", "meta, Column(\"sym\", String), Column(\"newval\", Integer) ) stmt = table.update().values( val=select([other.c.newval]).", "set(c._create_result_map()['x'][1]) def test_limit_offset_using_window(self): t = table('t', column('x', Integer), column('y', Integer))", "1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM [banana split].paj.test WHERE ' '[banana split].paj.test.id", "from sqlalchemy import schema from sqlalchemy.sql import table, column, quoted_name", "with a space].test.id \" \"FROM [banana split].[paj with a space].test", "dialect_name=darg), \"INSERT INTO sometable WITH (PAGLOCK) \" \"(somecolumn) VALUES (:somecolumn)\"", "MetaData() tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"foo.dbo\",", "\" \"[#other] WHERE [schema].sometable.sym = [#other].sym\", ) # TODO: not", "s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM [banana split].paj.test", "\"mssql\"): self.assert_compile( t.insert(). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"INSERT INTO", "Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "not the OFFSET # of zero, so produces TOP 0", "# test that the select is not altered with subsequent", "WHERE sometable.somecolumn = ' '(SELECT sometable.somecolumn FROM ' 'sometable)') self.assert_compile(t.select().where(t.c.somecolumn", "(id))\" ) def test_identity_increment_5(self): metadata = MetaData() tbl = Table('test',", "anon_1 FROM t' % field) def test_update_returning(self): table1 = table(", "SQL Server in order to affect \"): self.assert_compile( schema.CreateTable(tbl), \"CREATE", "x, t1.y AS y, \" \"ROW_NUMBER() OVER (ORDER BY \"", "= Table('t', m, Column('x', Integer)) expr1 = func.foo(t.c.x).label('x') expr2 =", "t = table('sometable', column('foo')) for expr, compile in [ (", "test_primary_key_no_identity(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "\"WHERE [banana split].[paj with a space].test.id = :id_1)\" ) def", "t2.c.x).as_scalar() s = select([t1]).where(t1.c.x == 5).order_by(order_by) \\ .limit(10).offset(20) self.assert_compile( s,", "schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER NULL, y INTEGER NULL,", "# t.delete().where(t.c.somecolumn==t2.c.somecolumn). # with_hint(\"WITH (PAGLOCK)\", # selectable=t2, # dialect_name=darg), #", "schema, owner = base._owner_plus_db(dialect, identifier) eq_(owner, expected_owner) eq_(schema, expected_schema) def", "== table1.c.myid self.assert_compile(select(['*'], crit), \"SELECT * FROM (SELECT mytable.myid AS", "mssql_identity_start=0, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT", "a space].test \" \"WHERE [banana split].[paj with a space].test.id =", "\" \"(SELECT t2.y FROM t2 WHERE t1.x = t2.x)\" \")", "s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.y", "Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"[Foo.dbo]\" ) self.assert_compile( select([tbl]),", "INTEGER NOT NULL IDENTITY(1,1), \" \"id2 INTEGER NOT NULL IDENTITY(1,1))\"", "SET somecolumn=:somecolum' 'n WHERE sometable.somecolumn = ' ':somecolumn_1', dict(somecolumn=10)) def", "from sqlalchemy.dialects.mssql import base class CompileTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = mssql.dialect()", "column('col4')) s1, s2 = select( [t1.c.col3.label('col3'), t1.c.col4.label('col4')], t1.c.col2.in_(['t1col2r1', 't1col2r2'])), \\", "sometable.somecolumn FROM ' 'sometable WHERE sometable.somecolumn = ' '(SELECT sometable.somecolumn", "primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL", "mssql_rn > :param_1 AND mssql_rn <= :param_2 + :param_1\", checkparams={'param_1':", "NOT NULL IDENTITY(1,1), \" \"PRIMARY KEY (id))\" ) def test_identity_illegal_two_autoincrements(self):", "self.assert_compile(func.current_date(), \"GETDATE()\") self.assert_compile(func.length(3), \"LEN(:length_1)\") def test_extract(self): t = table('t', column('col1'))", "\\ .limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.y \" \"FROM (SELECT", "join = t1.join(t2, t1.c.a == t2.c.a).\\ select().with_hint(t1, 'WITH (NOLOCK)') self.assert_compile(", "= MetaData() tbl = Table('test', metadata, Column('id', Integer, mssql_identity_start=0, primary_key=True))", "Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s,", ":param_1\", checkparams={'param_1': 20, 'param_2': 10, 'x_1': 5} ) c =", "' ':col2_4)) AS bar') def test_function(self): self.assert_compile(func.foo(1, 2), 'foo(:foo_1, :foo_2)')", "Table( 'test', metadata, Column('x', Integer), Column('y', Integer), Column('z', Integer)) idx", ") def test_update_to_select_schema(self): meta = MetaData() table = Table( \"sometable\",", "( select([literal(\"x\"), literal(\"y\")]), \"SELECT 'x' AS anon_1, 'y' AS anon_2\",", "= update( table1, values=dict( name='foo')).returning(table1).where(table1.c.name == 'bar') self.assert_compile(u, 'UPDATE mytable", "sometable.somecolumn FROM ' 'sometable)') @testing.uses_deprecated def test_count(self): t = table('sometable',", "column('c', String), ) t2 = table('t2', column(\"a\", Integer), column(\"b\", Integer),", "Column(\"val\", Integer), schema=\"schema\" ) other = Table( \"#other\", meta, Column(\"sym\",", "= table('othertable', column('somecolumn')) for darg in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn", "Integer)) t2 = table('t2', column('x', Integer), column('y', Integer)) order_by =", ") def test_create_index_expr(self): m = MetaData() t1 = Table('foo', m,", "split].[paj with a space].test.id \" \"FROM [banana split].[paj with a", "AS anon_1, 'y' AS anon_2\", ), ( select([t]).where(t.c.foo.in_(['x', 'y', 'z'])),", "t.c.foo.in_([None]), \"sometable.foo IN (NULL)\" ) ]: self.assert_compile(expr, compile, dialect=mxodbc_dialect) def", "\\ select([t2.c.col3.label('col3'), t2.c.col4.label('col4')], t2.c.col2.in_(['t2col2r2', 't2col2r3'])) u = union(s1, s2, order_by=['col3',", "def test_delete_schema_multipart_both_need_quoting(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "VALUES (:name)') i = insert(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(i, 'INSERT INTO", "KEY (id))\" ) def test_sequence_start_0(self): metadata = MetaData() tbl =", "x, \" \"ROW_NUMBER() OVER (ORDER BY foo(t.x) DESC) AS mssql_rn", "'[banana split].paj.test.id = :id_1)') def test_delete_schema_multipart_both_need_quoting(self): metadata = MetaData() tbl", "t2 = table('othertable', column('somecolumn')) # for darg in (\"*\", \"mssql\"):", "self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM paj.test WHERE paj.test.id = '", "Table('test', metadata, Column('id', Integer)) idx = Index(\"foo\", tbl.c.id, mssql_clustered=True) self.assert_compile(schema.CreateIndex(idx),", "AS col4 ' 'FROM t2 WHERE t2.col2 IN (:col2_3, '", "test (id INTEGER NOT NULL IDENTITY(1,5), \" \"PRIMARY KEY (id))\"", "Column('id', Integer, autoincrement=True), Column('id2', Integer, autoincrement=True), ) # this will", "Table('test', metadata, Column('id', Integer, primary_key=True), schema='paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE", ") def test_schema_autosplit_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table( 'test',", "'SELECT bar.col3, bar.col4 FROM (SELECT ' 't1.col3 AS col3, t1.col4", "col4 ' 'FROM t1 WHERE t1.col2 IN (:col2_1, ' ':col2_2)", "metadata, Column('id', Integer, primary_key=True), schema='banana.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM", "(ORDER BY foo(t.x) DESC) AS mssql_rn FROM t) \" \"AS", "FROM t WHERE t.x = :x_1) AS \" \"anon_1 WHERE", "Table('test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), UniqueConstraint(\"x\", \"y\",", "= table('sometable', column('somecolumn')) self.assert_compile(t.insert(), 'INSERT INTO sometable (somecolumn) VALUES '", "= table('sometable', column('somecolumn')) for targ in (None, t): for darg", "column('somecolumn')) self.assert_compile(t.select().where(t.c.somecolumn == t.select()), 'SELECT sometable.somecolumn FROM ' 'sometable WHERE", "NOT NULL, y INTEGER NULL, \" \"PRIMARY KEY (x), UNIQUE", "= select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.y \"", "\" \"ORDER BY sometable.somecolumn COLLATE \" \"Latin1_General_CS_AS_KS_WS_CI ASC\" ) def", "t.y) AS mssql_rn \" \"FROM t \" \"WHERE t.x =", "= MSSQLStrictCompiler t = table('sometable', column('foo')) for expr, compile in", "table('sometable', column('somecolumn')) self.assert_compile( t.delete(). where(t.c.somecolumn == \"q\"). with_hint(\"XYZ\", dialect_name=\"mysql\"), \"DELETE", "test_limit_offset_using_window(self): t = table('t', column('x', Integer), column('y', Integer)) s =", "eq_(\"test_column VARCHAR(max)\", self._column_spec()) def test_that_mssql_specified_nullable_emits_null(self): self.column.nullable = True eq_(\"test_column VARCHAR(max)", "meta, Column(\"sym\", String), Column(\"val\", Integer), schema=\"schema\" ) other = Table(", "stmt2, \"SELECT anon_1.y FROM (SELECT foo(t.x) AS y, \" \"ROW_NUMBER()", "table1.c.name) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT ' 'inserted.myid, inserted.name", ":param_1\", checkparams={'param_1': 20, 'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns),", "'INSERT INTO mytable (name) OUTPUT ' 'inserted.myid, inserted.name VALUES '", "\"DELETE FROM t1 FROM t1, t2 WHERE t1.c1 = t2.c1\"", "OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description WHERE mytable.name = '", "set(c._create_result_map()['y'][1]) def test_offset_dont_misapply_labelreference(self): m = MetaData() t = Table('t', m,", ":id_1)') def test_delete_schema_multipart_needs_quoting(self): metadata = MetaData() tbl = Table( 'test',", "q = sql.delete(a1).where(a1.c.c1 == t2.c.c1) self.assert_compile( q, \"DELETE FROM a1", ":param_1\" ) def test_limit_zero_offset_using_window(self): t = table('t', column('x', Integer), column('y',", "' 'inserted.myid, inserted.name') u = update(table1, values=dict(name='foo')).returning(table1) self.assert_compile(u, 'UPDATE mytable", "== 5).order_by(t.c.y).limit(10) self.assert_compile( s, \"SELECT TOP 10 t.x, t.y FROM", "schema='test_schema') self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT test_schema.sometable.somecolumn ' 'FROM test_schema.sometable", "test_offset_using_window(self): t = table('t', column('x', Integer), column('y', Integer)) s =", "Column('col1', Integer), Column('col2', Integer)) self.assert_compile(select([func.max(t.c.col1)]), 'SELECT max(sometable.col1) AS max_1 FROM", "'strict' compiler binds.\"\"\" from sqlalchemy.dialects.mssql.base import MSSQLStrictCompiler mxodbc_dialect = mxodbc.dialect()", "[schema].sometable.sym = [#other].sym)\", ) stmt = table.update().values(val=other.c.newval).\\ where(table.c.sym == other.c.sym)", "Index(\"foo\", tbl.c.x, mssql_include=[tbl.c.y]) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test (x)", "mytable SET name=:name OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description') u", "self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT ' 'LEN(inserted.name) AS length_1')", "autoincrement=False, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT", "IDENTITY(1,5), \" \"PRIMARY KEY (id))\" ) def test_sequence_start_0(self): metadata =", "tbl = Table( 'test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer,", "assert t.c.x in set(c._create_result_map()['x'][1]) assert t.c.y in set(c._create_result_map()['y'][1]) def test_limit_offset_w_ambiguous_cols(self):", ") self.assert_compile( select([tbl]), \"SELECT foo.dbo.test.id FROM foo.dbo.test\" ) def test_schema_autosplit_w_dot_case_sensitive(self):", "'bar') self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT ' 'inserted.myid, inserted.name,", "\" \"FROM (SELECT t.x AS x, t.y AS y, \"", "\"PRIMARY KEY (id))\" ) def test_primary_key_defaults_to_identity(self): metadata = MetaData() tbl", "NULL IDENTITY(1,1), \" \"PRIMARY KEY (id))\" ) def test_identity_illegal_two_autoincrements(self): metadata", "'WHERE t1.col2 IN (:col2_1, :col2_2) UNION ' 'SELECT t2.col3 AS", "test_drop_index_w_schema(self): m = MetaData() t1 = Table('foo', m, Column('x', Integer),", "'DELETE FROM banana.paj.test WHERE ' 'banana.paj.test.id IN (SELECT banana.paj.test.id '", "foo.dbo.test\" ) def test_schema_autosplit_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table(", "\"Foo\", \"Bar\"), (\"[Foo.Bar]\", None, \"Foo.Bar\"), (\"[Foo.Bar].[bat]\", \"Foo.Bar\", \"bat\"), ]: schema,", "column(\"a\", Integer), column(\"b\", Integer), column(\"c\", Integer), ) join = t1.join(t2,", "y, \" \"ROW_NUMBER() OVER (ORDER BY \" \"(SELECT t2.y FROM", "count(sometable.somecolumn) AS ' 'tbl_row_count FROM sometable') def test_noorderby_insubquery(self): \"\"\"test that", "'DELETE FROM [banana split].paj.test WHERE ' '[banana split].paj.test.id IN ('", "sometable WHERE \" \"sometable.somecolumn = :somecolumn_1\" ) def test_delete_extra_froms(self): t1", "self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT ' 'inserted.myid, inserted.name') u", "NOT NULL IDENTITY(1,5), \" \"PRIMARY KEY (id))\" ) def test_sequence_start_0(self):", "Integer), schema=\"schema\" ) other = Table( \"#other\", meta, Column(\"sym\", String),", "def test_noorderby_insubquery(self): \"\"\"test that the ms-sql dialect removes ORDER BY", "'mytable', column('myid', Integer), column('name', String(128)), column('description', String(128))) u = update(", "c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t1.c.x in set(c._create_result_map()['x'][1]) assert", "from sqlalchemy import sql from sqlalchemy import Integer, String, Table,", "WHERE t1.col2 IN (:col2_1, ' ':col2_2) UNION SELECT t2.col3 AS", "t1 = table('t1', column('x', Integer), column('y', Integer)) t2 = table('t2',", "anon_1.x, anon_1.y \" \"FROM (SELECT t.x AS x, t.y AS", "self.assert_compile( select([tbl]), \"SELECT [Foo].dbo.test.id FROM [Foo].dbo.test\" ) def test_owner_database_pairs(self): dialect", "= t2.c1\" ) def test_delete_extra_froms_alias(self): a1 = table('t1', column('c1')).alias('a1') t2", "test_update_hint(self): t = table('sometable', column('somecolumn')) for targ in (None, t):", "sometable WITH (NOLOCK)') def test_select_with_nolock_schema(self): m = MetaData() t =", "FROM t1 AS a1\") def test_update_from_hint(self): t = table('sometable', column('somecolumn'))", "5).order_by(t.c.y).offset(20) # test that the select is not altered with", "sometable WITH (PAGLOCK) \" \"(somecolumn) VALUES (:somecolumn)\" ) def test_update_hint(self):", "eq_(len(c._result_columns), 2) assert t1.c.x in set(c._create_result_map()['x'][1]) assert t1.c.y in set(c._create_result_map()['y'][1])", "[foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table(", "\"Use of Sequence with SQL Server in order to affect", "Sequence('', 0), primary_key=True)) with testing.expect_deprecated( \"Use of Sequence with SQL", "[Foo.dbo].test.id FROM [Foo.dbo].test\" ) def test_schema_autosplit_w_dot_case_insensitive(self): metadata = MetaData() tbl", "= Index(\"foo\", tbl.c.x, mssql_include=[tbl.c.y]) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test", "column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0) self.assert_compile( s, \"SELECT", "IN (:col2_1, ' ':col2_2) UNION SELECT t2.col3 AS col3, '", "def test_delete_exclude_hint(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.delete(). where(t.c.somecolumn ==", "(PAGLOCK) \" \"(somecolumn) VALUES (:somecolumn)\" ) def test_update_hint(self): t =", "\"CREATE NONCLUSTERED INDEX myidx ON test (x, y)\" ) def", "\"(somecolumn) VALUES (:somecolumn)\" ) def test_update_hint(self): t = table('sometable', column('somecolumn'))", "def test_create_index_expr(self): m = MetaData() t1 = Table('foo', m, Column('x',", "values=dict(name='foo')).returning(table1) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT ' 'inserted.myid, inserted.name,", "t.c.y] s = select(cols).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x,", "\"mssql\"): self.assert_compile( t.delete().where(t.c.somecolumn == \"q\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"DELETE", "Integer, autoincrement=False), Column('y', Integer, autoincrement=False) ) idx = Index(\"myidx\", tbl.c.x,", "Integer), Column('col2', Integer)) self.assert_compile(select([func.max(t.c.col1)]), 'SELECT max(sometable.col1) AS max_1 FROM '", "= table('t2', column('c1')) q = sql.delete(t1).where(t1.c.c1 == t2.c.c1) self.assert_compile( q,", "a space].test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(", "' 'sometable)') self.assert_compile(t.select().where(t.c.somecolumn != t.select()), 'SELECT sometable.somecolumn FROM ' 'sometable", "\"\"\"Test removal of legacy behavior that converted \"x==subquery\" to use", "column('somecolumn')) self.assert_compile(t.update(t.c.somecolumn == 7), 'UPDATE sometable SET somecolumn=:somecolum' 'n WHERE", "Column, select, MetaData,\\ update, delete, insert, extract, union, func, PrimaryKeyConstraint,", "'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 4) result_map =", "Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl),", "MetaData(), Column('pk_column', Integer), Column('test_column', String) ) self.column = t.c.test_column dialect", "Column('x', Integer, autoincrement=True) ) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id", "table('sometable', column('somecolumn')) self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT sometable.somecolumn FROM sometable", "t1.c.col4.label('col4')], t1.c.col2.in_(['t1col2r1', 't1col2r2'])), \\ select([t2.c.col3.label('col3'), t2.c.col4.label('col4')], t2.c.col2.in_(['t2col2r2', 't2col2r3'])) u =", "WHERE ' '[banana split].paj.test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id ==", "column('col1'), column('col2'), column('col3'), column('col4')) s1, s2 = select( [t1.c.col3.label('col3'), t1.c.col4.label('col4')],", "s = select([t1]).where(t1.c.x == 5).order_by(order_by) \\ .limit(10).offset(20) self.assert_compile( s, \"SELECT", "= table('sometable', column('somecolumn')) self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT sometable.somecolumn FROM", "\"PRIMARY KEY (id))\" ) def test_identity_illegal_two_autoincrements(self): metadata = MetaData() tbl", "anon_1.q, anon_1.p, anon_1.y \" \"FROM (SELECT t.x AS x, t.x", "Column('id', Integer, mssql_identity_start=0, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id", "tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"Foo.dbo\", True)", ") self.assert_compile( select([tbl]), \"SELECT [Foo].dbo.test.id FROM [Foo].dbo.test\" ) def test_owner_database_pairs(self):", "in order to affect \"): self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "self.assert_compile(d, 'DELETE FROM mytable OUTPUT deleted.myid, ' 'deleted.name') d =", "q = sql.delete(t1).where(t1.c.c1 == t2.c.c1) self.assert_compile( q, \"DELETE FROM t1", "' 'sometable') def test_function_overrides(self): self.assert_compile(func.current_date(), \"GETDATE()\") self.assert_compile(func.length(3), \"LEN(:length_1)\") def test_extract(self):", "' 'inserted.description WHERE mytable.name = ' ':name_1') u = update(table1,", "= Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"Foo.dbo\" ) self.assert_compile(", "primary_key=False)) with testing.expect_deprecated( \"Use of Sequence with SQL Server in", "sometable, othertable WITH (PAGLOCK) \" \"WHERE sometable.somecolumn = othertable.somecolumn\" )", "that converted \"x==subquery\" to use IN. \"\"\" t = table('sometable',", "\"DELETE FROM sometable WITH (PAGLOCK) \" \"WHERE sometable.somecolumn = :somecolumn_1\"", "[schema].sometable SET val=\" \"[#other].newval FROM [schema].sometable, \" \"[#other] WHERE [schema].sometable.sym", "'test', metadata, Column('id', Integer, primary_key=True), schema=\"Foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT", "def test_delete_extra_froms(self): t1 = table('t1', column('c1')) t2 = table('t2', column('c1'))", "' 'sometable)') @testing.uses_deprecated def test_count(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.count(),", "test_update_returning(self): table1 = table( 'mytable', column('myid', Integer), column('name', String(128)), column('description',", "Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False) ) idx = Index(\"myidx\",", "2), 'foo(:foo_1, :foo_2)') self.assert_compile(func.current_time(), 'CURRENT_TIME') self.assert_compile(func.foo(), 'foo()') m = MetaData()", "stmt, \"UPDATE [schema].sometable SET val=\" \"[#other].newval FROM [schema].sometable, \" \"[#other]", "autoincrement=True), Column('id2', Integer, autoincrement=True), ) # this will be rejected", "t1 = table('t1', column('c1')) t2 = table('t2', column('c1')) q =", "= Table( 'test', metadata, Column('id', Integer, primary_key=True), schema='banana.paj') self.assert_compile(tbl.delete(tbl.c.id ==", "bar') def test_function(self): self.assert_compile(func.foo(1, 2), 'foo(:foo_1, :foo_2)') self.assert_compile(func.current_time(), 'CURRENT_TIME') self.assert_compile(func.foo(),", "'banana.paj.test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE", "self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT sometable.somecolumn FROM sometable WITH (NOLOCK)')", "' 'inserted.myid, inserted.name, ' 'inserted.description') u = update( table1, values=dict(", "WHERE sometable.somecolumn = ' ':somecolumn_1', dict(somecolumn=10)) def test_insert_hint(self): t =", "'banana.paj.test.id = :id_1)') def test_delete_schema_multipart_needs_quoting(self): metadata = MetaData() tbl =", "y INTEGER NULL, \" \"PRIMARY KEY (x), UNIQUE CLUSTERED (y))\"", "= MetaData() t1 = Table('foo', m, Column('x', Integer) ) self.assert_compile(", "FROM ' 'sometable)') @testing.uses_deprecated def test_count(self): t = table('sometable', column('somecolumn'))", "= :id_1)') def test_delete_schema_multipart_both_need_quoting(self): metadata = MetaData() tbl = Table('test',", "mssql_clustered=True) self.assert_compile(schema.CreateIndex(idx), \"CREATE CLUSTERED INDEX foo ON test (id)\" )", "s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1]) assert t.c.y in", "= insert(table1, values=dict(name='foo')).returning(table1) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT '", "self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test (x) INCLUDE (y)\" )", "idx_foo ON bar.foo\" ) def test_index_extra_include_1(self): metadata = MetaData() tbl", "INTO mytable (name) OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description VALUES", "= select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10) self.assert_compile( s, \"SELECT TOP 10 t.x,", "# TODO: not supported yet. # def test_delete_from_hint(self): # t", "t.delete().where(t.c.somecolumn==t2.c.somecolumn). # with_hint(\"WITH (PAGLOCK)\", # selectable=t2, # dialect_name=darg), # \"\"", "\"SELECT 'x' AS anon_1, 'y' AS anon_2\", ), ( select([t]).where(t.c.foo.in_(['x',", "Column('id', Integer, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER", "schema=quoted_name(\"Foo.dbo\", True) ) self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" )", "[t1.c.col3.label('col3'), t1.c.col4.label('col4')], t1.c.col2.in_(['t1col2r1', 't1col2r2'])), \\ select([t2.c.col3.label('col3'), t2.c.col4.label('col4')], t2.c.col2.in_(['t2col2r2', 't2col2r3'])) u", "t.x = :x_1 ORDER BY t.y\", checkparams={'x_1': 5} ) c", "(NOLOCK)') def test_select_with_nolock_schema(self): m = MetaData() t = Table('sometable', m,", "Column('z', Integer)) idx = Index(\"foo\", tbl.c.x, mssql_include=[tbl.c.y]) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX", "behavior that converted \"x==subquery\" to use IN. \"\"\" t =", "WHERE ' '[banana split].paj.test.id IN (' 'SELECT [banana split].paj.test.id FROM", "mytable.name = ' ':name_1') u = update(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(u,", ") def test_schema_autosplit_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table( 'test',", "sometable \" \"ORDER BY sometable.somecolumn COLLATE \" \"Latin1_General_CS_AS_KS_WS_CI ASC\" )", "test (id INTEGER NOT NULL IDENTITY(1,1)\" \")\" ) def test_identity_separate_from_primary_key(self):", "Integer, primary_key=True), schema=\"foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT foo.dbo.test.id FROM foo.dbo.test\"", "\"\"\"test the 'strict' compiler binds.\"\"\" from sqlalchemy.dialects.mssql.base import MSSQLStrictCompiler mxodbc_dialect", "asserting this is what # the two autoincrements will do", "TABLE test (id INTEGER NOT NULL IDENTITY(0,1), \" \"PRIMARY KEY", ") c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 4) result_map = c._create_result_map() for", "NULL\", self._column_spec()) def test_that_mssql_specified_not_nullable_emits_not_null(self): self.column.nullable = False eq_(\"test_column VARCHAR(max) NOT", "select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM banana.paj.test WHERE ' 'banana.paj.test.id", "t1.join(t2, t1.c.a == t2.c.a).\\ select().with_hint(t1, 'WITH (NOLOCK)') self.assert_compile( join, 'SELECT", "select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0) self.assert_compile( s, \"SELECT TOP 0 t.x, t.y", ") def test_table_pkc_explicit_nonclustered(self): metadata = MetaData() tbl = Table('test', metadata,", "schema=\"[Foo.dbo]\" ) self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" ) def", "self.assert_compile( s, \"SELECT anon_1.x, anon_1.q, anon_1.p, anon_1.y \" \"FROM (SELECT", "'DELETE FROM paj.test WHERE paj.test.id = ' ':id_1') s =", "'t2.col4 AS col4 FROM t2 WHERE t2.col2 IN ' '(:col2_3,", "= Table('test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\",", "String), column('c', String), ) t2 = table('t2', column(\"a\", Integer), column(\"b\",", "column('a', Integer), column('b', String), column('c', String), ) t2 = table('t2',", "AS col4 FROM t2 WHERE t2.col2 IN ' '(:col2_3, :col2_4)", "= :id_1)\" ) def test_union(self): t1 = table( 't1', column('col1'),", "test_join_with_hint(self): t1 = table('t1', column('a', Integer), column('b', String), column('c', String),", "== other.c.sym).as_scalar()) self.assert_compile( stmt, \"UPDATE [schema].sometable SET val=\" \"(SELECT [#other].newval", "PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER", "MetaData() tbl = Table('test', metadata, Column('id', Integer, autoincrement=True)) self.assert_compile( schema.CreateTable(tbl),", "\" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_delete_exclude_hint(self): t =", "split].[paj with a space].test \" \"WHERE [banana split].[paj with a", "Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\"), UniqueConstraint(\"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl),", "m, Column('somecolumn', String)) self.assert_compile( select([t]). order_by( t.c.somecolumn.collate(\"Latin1_General_CS_AS_KS_WS_CI\").asc()), \"SELECT sometable.somecolumn FROM", "AS col4 FROM t1 ' 'WHERE t1.col2 IN (:col2_1, :col2_2)", "m = MetaData() t = Table('sometable', m, Column('somecolumn', String)) self.assert_compile(", "val=\" \"(SELECT [#other].newval FROM [#other] \" \"WHERE [schema].sometable.sym = [#other].sym)\",", "INTO mytable (name) OUTPUT ' 'inserted.myid, inserted.name VALUES ' '(:name)')", "JOIN t2 ON t1.a = t2.a' ) def test_insert(self): t", "10 t.x, t.y FROM t WHERE t.x = :x_1 ORDER", "checkparams={'x_1': 5} ) def test_primary_key_no_identity(self): metadata = MetaData() tbl =", "t1.c1 = t2.c1\" ) def test_delete_extra_froms_alias(self): a1 = table('t1', column('c1')).alias('a1')", "'inserted.myid, inserted.name') u = update(table1, values=dict(name='foo')).returning(table1) self.assert_compile(u, 'UPDATE mytable SET", "table('sometable', column('somecolumn')) # t2 = table('othertable', column('somecolumn')) # for darg", "FROM ' 'sometable)') self.assert_compile(t.select().where(t.c.somecolumn != t.select()), 'SELECT sometable.somecolumn FROM '", "' 'FROM test_schema.sometable WITH (NOLOCK)') def test_select_w_order_by_collate(self): m = MetaData()", "t = table('t', column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x", "' 'banana.paj.test.id = :id_1)') def test_delete_schema_multipart_needs_quoting(self): metadata = MetaData() tbl", "INCLUDE (y)\" ) def test_index_extra_include_2(self): metadata = MetaData() tbl =", "'t2col2r3'])) u = union(s1, s2, order_by=['col3', 'col4']) self.assert_compile(u, 'SELECT t1.col3", "(PAGLOCK) \" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_delete_exclude_hint(self): t", "[foo.dbo].test.id FROM [foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_insensitive(self): metadata = MetaData() tbl", "\") AS mssql_rn \" \"FROM t1 \" \"WHERE t1.x =", "selectable=t2, # dialect_name=darg), # \"\" # ) def test_strict_binds(self): \"\"\"test", "autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x", "' '(:col2_3, :col2_4) ORDER BY col3, col4') self.assert_compile(u.alias('bar').select(), 'SELECT bar.col3,", "metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer, mssql_identity_start=0,", "def test_delete_schema_multipart_needs_quoting(self): metadata = MetaData() tbl = Table( 'test', metadata,", "\"SELECT anon_1.x, anon_1.y FROM (SELECT t.x AS x, t.y \"", "insert(table1, values=dict(name='foo')).returning(table1) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT ' 'inserted.myid,", "'WHERE paj.test.id = :id_1)') def test_delete_schema_multipart(self): metadata = MetaData() tbl", "self.assert_compile( select([extract(field, t.c.col1)]), 'SELECT DATEPART(%s, t.col1) AS anon_1 FROM t'", "eq_, is_ from sqlalchemy import schema from sqlalchemy.sql import table,", "othertable.somecolumn\" ) def test_update_to_select_schema(self): meta = MetaData() table = Table(", ") def test_table_uc_clustering(self): metadata = MetaData() tbl = Table('test', metadata,", "not supported yet. # def test_delete_from_hint(self): # t = table('sometable',", ") self.assert_compile(sql.delete(a1), \"DELETE FROM t1 AS a1\") def test_update_from_hint(self): t", "table('t', column('col1')) for field in 'day', 'month', 'year': self.assert_compile( select([extract(field,", "[ ( select([literal(\"x\"), literal(\"y\")]), \"SELECT 'x' AS anon_1, 'y' AS", "self.assert_compile( schema.CreateIndex(Index(\"bar\", t1.c.x > 5)), \"CREATE INDEX bar ON foo", "INTO sometable (somecolumn) VALUES ' '(:somecolumn)') def test_update(self): t =", "INTO mytable (name) OUTPUT ' 'LEN(inserted.name) AS length_1 VALUES '", ")).returning(func.length(table1.c.name)) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT ' 'LEN(inserted.name) AS", "Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0) self.assert_compile( s, \"SELECT TOP", "Column('id', Integer, primary_key=True), schema=quoted_name(\"Foo.dbo\", True) ) self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id", ") def test_primary_key_no_identity(self): metadata = MetaData() tbl = Table('test', metadata,", "delete, insert, extract, union, func, PrimaryKeyConstraint, \\ UniqueConstraint, Index, Sequence,", "== 1), 'DELETE FROM [banana split].[paj with a ' 'space].test", "test_identity_separate_from_primary_key(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "order_by( t.c.somecolumn.collate(\"Latin1_General_CS_AS_KS_WS_CI\").asc()), \"SELECT sometable.somecolumn FROM sometable \" \"ORDER BY sometable.somecolumn", "dialect_name=darg), \"UPDATE sometable SET somecolumn=:somecolumn \" \"FROM sometable, othertable WITH", "= select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM paj.test WHERE paj.test.id", "a1.c1 = t2.c1\" ) self.assert_compile(sql.delete(a1), \"DELETE FROM t1 AS a1\")", "test (x INTEGER NOT NULL, y INTEGER NOT NULL, \"", "\"SELECT anon_1.x FROM (SELECT foo(t.x) AS x, \" \"ROW_NUMBER() OVER", "(name) OUTPUT ' 'inserted.myid, inserted.name VALUES ' '(:name)') i =", ") def test_update_hint(self): t = table('sometable', column('somecolumn')) for targ in", "darg in (\"*\", \"mssql\"): self.assert_compile( t.insert(). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ,", "Table('test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\"), UniqueConstraint(\"y\",", "IN (' 'SELECT [banana split].paj.test.id FROM ' '[banana split].paj.test WHERE", "Table('test', metadata, Column('id', Integer, Sequence('', start=5), primary_key=False)) with testing.expect_deprecated( \"Use", "schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(0,1), \"", "'inserted.description VALUES (:name)') i = insert(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(i, 'INSERT", ") def test_identity_illegal_two_autoincrements(self): metadata = MetaData() tbl = Table('test', metadata,", "BY t.y\", checkparams={'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2)", "'UPDATE mytable SET name=:name OUTPUT ' 'inserted.myid, inserted.name') u =", "\" \"PRIMARY KEY CLUSTERED (x, y))\" ) def test_table_pkc_explicit_nonclustered(self): metadata", "FROM [banana split].[paj with a space].test \" \"WHERE [banana split].[paj", "binds.\"\"\" from sqlalchemy.dialects.mssql.base import MSSQLStrictCompiler mxodbc_dialect = mxodbc.dialect() mxodbc_dialect.statement_compiler =", "AS x, \" \"ROW_NUMBER() OVER (ORDER BY foo(t.x) DESC) AS", "= ' ':somecolumn_1', dict(somecolumn=10)) def test_insert_hint(self): t = table('sometable', column('somecolumn'))", "Integer, Sequence('', 0), primary_key=True)) with testing.expect_deprecated( \"Use of Sequence with", "Column('test_column', String) ) self.column = t.c.test_column dialect = mssql.dialect() self.ddl_compiler", "# of zero, so produces TOP 0 self.assert_compile( s, \"SELECT", "tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"Foo.dbo\" )", "s, \"SELECT TOP 0 t.x, t.y FROM t \" \"WHERE", "\"CREATE TABLE test (id INTEGER NOT NULL, \" \"x INTEGER", "= table('sometable', column('somecolumn')) self.assert_compile(t.select().where(t.c.somecolumn == t.select()), 'SELECT sometable.somecolumn FROM '", "mxodbc from sqlalchemy.testing import fixtures, AssertsCompiledSQL from sqlalchemy import sql", "IDENTITY(1,1), \" \"id2 INTEGER NOT NULL IDENTITY(1,1))\" ) def test_identity_start_0(self):", "select().with_hint(t1, 'WITH (NOLOCK)') self.assert_compile( join, 'SELECT t1.a, t1.b, t1.c, t2.a,", "self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM paj.test WHERE paj.test.id IN ' '(SELECT paj.test.id", "(None, t): for darg in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn ==", "t1.c.x > 5)), \"CREATE INDEX bar ON foo (x >", "test_delete_schema_multipart(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('id',", "WITH (NOLOCK) JOIN t2 ON t1.a = t2.a' ) def", "utf-8 from sqlalchemy.testing import eq_, is_ from sqlalchemy import schema", "schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL, \" \"PRIMARY", "table, column, quoted_name from sqlalchemy.dialects import mssql from sqlalchemy.dialects.mssql import", "NULL IDENTITY(1,1), \" \"id2 INTEGER NOT NULL IDENTITY(1,1))\" ) def", "mssql_clustered=False) self.assert_compile( schema.CreateIndex(idx), \"CREATE NONCLUSTERED INDEX myidx ON test (x,", "t.x AS x, t.x AS q, t.x AS p, t.y", "select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0).offset(0) # render the LIMIT of zero, but", "column('description', String(128))) i = insert( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(i, 'INSERT", "of zero, so produces TOP 0 self.assert_compile( s, \"SELECT TOP", "'sometable)') @testing.uses_deprecated def test_count(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.count(), 'SELECT", "2) assert t.c.x in set(c._create_result_map()['x'][1]) def test_offset_using_window(self): t = table('t',", "' 'inserted.description VALUES (:name)') i = insert(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(i,", "sqlalchemy.testing import eq_, is_ from sqlalchemy import schema from sqlalchemy.sql", "t = table('sometable', column('somecolumn')) self.assert_compile(t.select().where(t.c.somecolumn == t.select()), 'SELECT sometable.somecolumn FROM", ":somecolumn_1\" ) def test_update_exclude_hint(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.update().where(t.c.somecolumn", "= [t.c.x, t.c.x.label('q'), t.c.x.label('p'), t.c.y] s = select(cols).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20)", "\" \"PRIMARY KEY (id))\" ) def test_sequence_non_primary_key(self): metadata = MetaData()", "\"q\"). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"UPDATE sometable WITH (PAGLOCK)", "metadata = MetaData() tbl = Table('test', metadata, Column('x', Integer, autoincrement=False),", "FROM t2 WHERE t2.col2 IN ' '(:col2_3, :col2_4) ORDER BY", "foo ON test (x DESC, y)\" ) def test_create_index_expr(self): m", "ON test (x) INCLUDE (y)\" ) def test_index_extra_include_2(self): metadata =", ":x_1) AS \" \"anon_1 WHERE mssql_rn > :param_1\", checkparams={'param_1': 20,", "= insert( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(i, 'INSERT INTO mytable (name)", "self.assert_compile( schema.CreateIndex(idx), \"CREATE NONCLUSTERED INDEX myidx ON test (x, y)\"", "= Table( \"#other\", meta, Column(\"sym\", String), Column(\"newval\", Integer) ) stmt", "test_force_schema_quoted_name_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('id',", "idx = Index(\"foo\", tbl.c.x.desc(), \"y\") self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON", "test_count(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.count(), 'SELECT count(sometable.somecolumn) AS '", "mytable OUTPUT deleted.myid, ' 'deleted.name') d = delete(table1).where(table1.c.name == 'bar'", "column('name', String(128)), column('description', String(128))) d = delete(table1).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE", "'(SELECT paj.test.id FROM paj.test ' 'WHERE paj.test.id = :id_1)') def", "assert t.c.y in set(c._create_result_map()['y'][1]) def test_limit_offset_w_ambiguous_cols(self): t = table('t', column('x',", "' '(:somecolumn)') def test_update(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.update(t.c.somecolumn ==", "MSSQLStrictCompiler t = table('sometable', column('foo')) for expr, compile in [", "(NOLOCK) JOIN t2 ON t1.a = t2.a' ) def test_insert(self):", "'sometable WHERE sometable.somecolumn != ' '(SELECT sometable.somecolumn FROM ' 'sometable)')", "def test_identity_no_primary_key(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "\" \"AS anon_1 WHERE mssql_rn > :param_1\" ) def test_limit_zero_offset_using_window(self):", "( select([t]).where(t.c.foo.in_(['x', 'y', 'z'])), \"SELECT sometable.foo FROM sometable WHERE sometable.foo", "mssql_rn > :param_1\", checkparams={'param_1': 20, 'x_1': 5} ) c =", "def test_insert_returning(self): table1 = table( 'mytable', column('myid', Integer), column('name', String(128)),", "INTEGER NOT NULL IDENTITY(1,1), \" \"PRIMARY KEY (id))\" ) def", ") def test_index_clustering(self): metadata = MetaData() tbl = Table('test', metadata,", "sqlalchemy.dialects.mssql.base import MSSQLStrictCompiler mxodbc_dialect = mxodbc.dialect() mxodbc_dialect.statement_compiler = MSSQLStrictCompiler t", "'SELECT max(sometable.col1) AS max_1 FROM ' 'sometable') def test_function_overrides(self): self.assert_compile(func.current_date(),", "import mxodbc from sqlalchemy.testing import fixtures, AssertsCompiledSQL from sqlalchemy import", "= union(s1, s2, order_by=['col3', 'col4']) self.assert_compile(u, 'SELECT t1.col3 AS col3,", "t) \" \"AS anon_1 WHERE mssql_rn > :param_1\" ) self.assert_compile(", "self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(1,5),", "OUTPUT deleted.myid, ' 'deleted.name WHERE mytable.name = :name_1') def test_insert_returning(self):", "WHERE t1.x = t2.x)\" \") AS mssql_rn \" \"FROM t1", "\"PRIMARY KEY (id))\" ) def test_sequence_non_primary_key(self): metadata = MetaData() tbl", "Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_sensitive(self): metadata =", "= select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM [banana split].paj.test WHERE", "d = delete(table1).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM mytable OUTPUT deleted.myid,", "WHERE sometable.somecolumn != ' '(SELECT sometable.somecolumn FROM ' 'sometable)') @testing.uses_deprecated", "\"(SELECT t2.y FROM t2 WHERE t1.x = t2.x)\" \") AS", "to affect \"): self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER", "split].[paj ' 'with a space].test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id", "[schema].sometable SET val=\" \"(SELECT [#other].newval FROM [#other] \" \"WHERE [schema].sometable.sym", "othertable WITH (PAGLOCK) \" \"WHERE sometable.somecolumn = othertable.somecolumn\" ) def", "metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"foo.dbo\", True) ) self.assert_compile( select([tbl]), \"SELECT", "t2.col2 IN ' '(:col2_3, :col2_4) ORDER BY col3, col4') self.assert_compile(u.alias('bar').select(),", "NOT NULL, \" \"x INTEGER NOT NULL IDENTITY(1,1), \" \"PRIMARY", "def test_select(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.select(), 'SELECT sometable.somecolumn FROM", "WITH (NOLOCK)') def test_select_with_nolock_schema(self): m = MetaData() t = Table('sometable',", "Integer)) order_by = select([t2.c.y]).where(t1.c.x == t2.c.x).as_scalar() s = select([t1]).where(t1.c.x ==", "'test', metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"Foo.dbo\", True) ) self.assert_compile( select([tbl]),", "self.assert_compile( select([t]). order_by( t.c.somecolumn.collate(\"Latin1_General_CS_AS_KS_WS_CI\").asc()), \"SELECT sometable.somecolumn FROM sometable \" \"ORDER", "= Table('test', metadata, Column('id', Integer, primary_key=True), schema='banana split.paj with a", "Column(\"newval\", Integer) ) stmt = table.update().values( val=select([other.c.newval]). where(table.c.sym == other.c.sym).as_scalar())", "\"PRIMARY KEY (x), UNIQUE CLUSTERED (y))\" ) def test_index_clustering(self): metadata", "self.ddl_compiler.get_column_specification(self.column) def test_that_mssql_default_nullability_emits_null(self): eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_none_nullability_does_not_emit_nullability(self): self.column.nullable", "import schema from sqlalchemy.sql import table, column, quoted_name from sqlalchemy.dialects", "s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1]) def test_limit_offset_using_window(self): t", "1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM banana.paj.test WHERE ' 'banana.paj.test.id IN (SELECT", "WHERE t2.col2 IN (:col2_3, ' ':col2_4)) AS bar') def test_function(self):", "metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer, autoincrement=False,", "t.select()), 'SELECT sometable.somecolumn FROM ' 'sometable WHERE sometable.somecolumn != '", "y, \" \"ROW_NUMBER() OVER (ORDER BY t.y) AS mssql_rn \"", "setup(self): t = Table('sometable', MetaData(), Column('pk_column', Integer), Column('test_column', String) )", "= MetaData() t1 = Table('foo', m, Column('x', Integer), schema='bar' )", "IN ' '(:col2_3, :col2_4) ORDER BY col3, col4') self.assert_compile(u.alias('bar').select(), 'SELECT", "WHERE [banana split].[paj ' 'with a space].test.id = :id_1') s", "dialect = mssql.dialect() self.ddl_compiler = dialect.ddl_compiler(dialect, schema.CreateTable(t)) def _column_spec(self): return", "MetaData() tbl = Table('test', metadata, Column('id', Integer, primary_key=True), schema='banana split.paj", ":foo_2)') self.assert_compile(func.current_time(), 'CURRENT_TIME') self.assert_compile(func.foo(), 'foo()') m = MetaData() t =", "mssql_include=[tbl.c.y]) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test (x) INCLUDE (y)\"", "Column('id', Integer, Sequence('', start=5), primary_key=False)) with testing.expect_deprecated( \"Use of Sequence", "def test_update_from_hint(self): t = table('sometable', column('somecolumn')) t2 = table('othertable', column('somecolumn'))", "primary_key=True), Column('x', Integer, autoincrement=True) ) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "\"UPDATE sometable SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn = :somecolumn_1\" )", "' 'inserted.myid, inserted.name, ' 'inserted.description WHERE mytable.name = ' ':name_1')", "[#other].sym\", ) # TODO: not supported yet. # def test_delete_from_hint(self):", "table('t', column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0).offset(0)", "\" \"PRIMARY KEY (id))\" ) def test_identity_increment_5(self): metadata = MetaData()", "sqlalchemy.sql import table, column, quoted_name from sqlalchemy.dialects import mssql from", "NOT NULL IDENTITY(5,1))\" ) def test_table_pkc_clustering(self): metadata = MetaData() tbl", "def test_function(self): self.assert_compile(func.foo(1, 2), 'foo(:foo_1, :foo_2)') self.assert_compile(func.current_time(), 'CURRENT_TIME') self.assert_compile(func.foo(), 'foo()')", "s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM paj.test WHERE", "assert t1.c.x in set(c._create_result_map()['x'][1]) assert t1.c.y in set(c._create_result_map()['y'][1]) def test_offset_dont_misapply_labelreference(self):", "Index(\"myidx\", tbl.c.x, tbl.c.y, mssql_clustered=False) self.assert_compile( schema.CreateIndex(idx), \"CREATE NONCLUSTERED INDEX myidx", "y INTEGER NOT NULL, \" \"PRIMARY KEY CLUSTERED (x, y))\"", "= Table( 'test', metadata, Column('id', Integer, primary_key=True), schema='banana split.paj') self.assert_compile(tbl.delete(tbl.c.id", "self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER NOT NULL, y", "= :id_1)') def test_delete_schema_multipart(self): metadata = MetaData() tbl = Table(", "\"GETDATE()\") self.assert_compile(func.length(3), \"LEN(:length_1)\") def test_extract(self): t = table('t', column('col1')) for", "func.foo(t.c.x).label('x') expr2 = func.foo(t.c.x).label('y') stmt1 = select([expr1]).order_by(expr1.desc()).offset(1) stmt2 = select([expr2]).order_by(expr2.desc()).offset(1)", "'UPDATE mytable SET name=:name OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description", "OVER (ORDER BY \" \"(SELECT t2.y FROM t2 WHERE t1.x", ") def test_select(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.select(), 'SELECT sometable.somecolumn", "tbl = Table( 'test', metadata, Column('x', Integer), Column('y', Integer), Column('z',", "stmt2 = select([expr2]).order_by(expr2.desc()).offset(1) self.assert_compile( stmt1, \"SELECT anon_1.x FROM (SELECT foo(t.x)", "self._column_spec()) def test_that_mssql_none_nullability_does_not_emit_nullability(self): self.column.nullable = None eq_(\"test_column VARCHAR(max)\", self._column_spec()) def", "= MetaData() t = Table('sometable', m, Column('somecolumn', String)) self.assert_compile( select([t]).", "'SELECT sometable.somecolumn FROM ' 'sometable WHERE sometable.somecolumn = ' '(SELECT", "with_hint(\"XYZ\", dialect_name=\"mysql\"), \"DELETE FROM sometable WHERE \" \"sometable.somecolumn = :somecolumn_1\"", "s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0) self.assert_compile( s, \"SELECT TOP 0", "MetaData() t1 = Table('foo', m, Column('x', Integer), schema='bar' ) self.assert_compile(", "mytable (name) OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description VALUES (:name)')", "metadata, Column('id', Integer, primary_key=True), schema=\"foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT foo.dbo.test.id", "\" \"WHERE [banana split].[paj with a space].test.id IN \" \"(SELECT", "def test_update_hint(self): t = table('sometable', column('somecolumn')) for targ in (None,", "with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"UPDATE sometable WITH (PAGLOCK) \" \"SET", "SET name=:name OUTPUT ' 'LEN(inserted.name) AS length_1') def test_delete_returning(self): table1", "FROM mytable OUTPUT deleted.myid, ' 'deleted.name') d = delete(table1).where(table1.c.name ==", "(ORDER BY t.y) AS \" \"mssql_rn FROM t WHERE t.x", "\"1\" ) def test_select(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.select(), 'SELECT", "bar ON foo (x > 5)\" ) def test_drop_index_w_schema(self): m", ") class SchemaTest(fixtures.TestBase): def setup(self): t = Table('sometable', MetaData(), Column('pk_column',", "mytable WHERE \" \"foo.myid = mytable.myid\") def test_force_schema_quoted_name_w_dot_case_insensitive(self): metadata =", ") self.assert_compile( sql.true(), \"1\" ) def test_select(self): t = table('sometable',", "INDEX idx_foo ON bar.foo\" ) def test_index_extra_include_1(self): metadata = MetaData()", "= dialect.ddl_compiler(dialect, schema.CreateTable(t)) def _column_spec(self): return self.ddl_compiler.get_column_specification(self.column) def test_that_mssql_default_nullability_emits_null(self): eq_(\"test_column", "table.update().values( val=select([other.c.newval]). where(table.c.sym == other.c.sym).as_scalar()) self.assert_compile( stmt, \"UPDATE [schema].sometable SET", "def test_offset_dont_misapply_labelreference(self): m = MetaData() t = Table('t', m, Column('x',", "def test_sequence_ignore_nullability(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "\" \"FROM (SELECT t.x AS x, t.x AS q, t.x", "self.assert_compile(t.count(), 'SELECT count(sometable.somecolumn) AS ' 'tbl_row_count FROM sometable') def test_noorderby_insubquery(self):", "NULL IDENTITY(1,1)\" \")\" ) def test_identity_separate_from_primary_key(self): metadata = MetaData() tbl", "test_delete_exclude_hint(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.delete(). where(t.c.somecolumn == \"q\").", "20, 'param_2': 10, 'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns),", "table( 'mytable', column('myid', Integer), column('name', String(128)), column('description', String(128))) i =", "AS col3, ' 't2.col4 AS col4 FROM t2 WHERE t2.col2", "import testing from sqlalchemy.dialects.mssql import base class CompileTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__", "t1.y AS y, \" \"ROW_NUMBER() OVER (ORDER BY \" \"(SELECT", "'z')\", ), ( t.c.foo.in_([None]), \"sometable.foo IN (NULL)\" ) ]: self.assert_compile(expr,", "FROM ' '[banana split].paj.test WHERE ' '[banana split].paj.test.id = :id_1)')", "[banana split].[paj with a ' 'space].test WHERE [banana split].[paj '", "t1.x = :x_1) AS anon_1 \" \"WHERE mssql_rn > :param_1", "Column('id', Integer, autoincrement=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER", "\" \"Latin1_General_CS_AS_KS_WS_CI ASC\" ) def test_join_with_hint(self): t1 = table('t1', column('a',", "(NOLOCK)'), 'SELECT sometable.somecolumn FROM sometable WITH (NOLOCK)') def test_select_with_nolock_schema(self): m", "self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM banana.paj.test WHERE ' 'banana.paj.test.id =", "def test_that_mssql_none_nullability_does_not_emit_nullability(self): self.column.nullable = None eq_(\"test_column VARCHAR(max)\", self._column_spec()) def test_that_mssql_specified_nullable_emits_null(self):", "Column('id2', Integer, autoincrement=True), ) # this will be rejected by", "\"myid FROM mytable) AS foo, mytable WHERE \" \"foo.myid =", "t1 WHERE t1.col2 IN (:col2_1, ' ':col2_2) UNION SELECT t2.col3", "\")\" ) def test_identity_separate_from_primary_key(self): metadata = MetaData() tbl = Table('test',", "\"PRIMARY KEY CLUSTERED (x, y))\" ) def test_table_pkc_explicit_nonclustered(self): metadata =", "t1, t2 WHERE t1.c1 = t2.c1\" ) def test_delete_extra_froms_alias(self): a1", "(id INTEGER NOT NULL IDENTITY(1,1), \" \"PRIMARY KEY (id))\" )", "table('sometable', column('somecolumn')) self.assert_compile(t.select(), 'SELECT sometable.somecolumn FROM sometable') def test_select_with_nolock(self): t", "mssql_rn > :param_1\" ) self.assert_compile( stmt2, \"SELECT anon_1.y FROM (SELECT", "right now self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT", "schema=quoted_name(\"foo.dbo\", True) ) self.assert_compile( select([tbl]), \"SELECT [foo.dbo].test.id FROM [foo.dbo].test\" )", "), ( select([t]).where(t.c.foo.in_(['x', 'y', 'z'])), \"SELECT sometable.foo FROM sometable WHERE", "'UPDATE mytable SET name=:name OUTPUT ' 'LEN(inserted.name) AS length_1') def", "INTEGER NOT NULL IDENTITY(1,1))\" ) def test_identity_start_0(self): metadata = MetaData()", "sqlalchemy.dialects import mssql from sqlalchemy.dialects.mssql import mxodbc from sqlalchemy.testing import", "name=:name OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description') u = update(", "autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE", "NULL, \" \"x INTEGER NOT NULL IDENTITY(1,1), \" \"PRIMARY KEY", "= table('mytable', column('myid', Integer), column('name', String), column('description', String), ) q", "FROM paj.test ' 'WHERE paj.test.id = :id_1)') def test_delete_schema_multipart(self): metadata", "column('c1')).alias('a1') t2 = table('t2', column('c1')) q = sql.delete(a1).where(a1.c.c1 == t2.c.c1)", "Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0) self.assert_compile( s,", "= Index(\"myidx\", tbl.c.x, tbl.c.y, mssql_clustered=False) self.assert_compile( schema.CreateIndex(idx), \"CREATE NONCLUSTERED INDEX", "= update(table1, values=dict(name='foo')).returning(table1) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT '", "test (x INTEGER NOT NULL, y INTEGER NULL, \" \"PRIMARY", "'day', 'month', 'year': self.assert_compile( select([extract(field, t.c.col1)]), 'SELECT DATEPART(%s, t.col1) AS", "NULL\", self._column_spec()) def test_that_mssql_none_nullability_does_not_emit_nullability(self): self.column.nullable = None eq_(\"test_column VARCHAR(max)\", self._column_spec())", "Table('test', metadata, Column('id', Integer, Sequence('', 0), primary_key=True)) with testing.expect_deprecated( \"Use", "IN (:col2_1, :col2_2) UNION ' 'SELECT t2.col3 AS col3, t2.col4", "= MetaData() t = Table('t', m, Column('x', Integer)) expr1 =", "t.c.test_column dialect = mssql.dialect() self.ddl_compiler = dialect.ddl_compiler(dialect, schema.CreateTable(t)) def _column_spec(self):", "Column('z', Integer)) idx = Index(\"foo\", tbl.c.x.desc(), \"y\") self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX", "self.assert_compile(sql.delete(a1), \"DELETE FROM t1 AS a1\") def test_update_from_hint(self): t =", "= t.c.test_column dialect = mssql.dialect() self.ddl_compiler = dialect.ddl_compiler(dialect, schema.CreateTable(t)) def", "table('t', column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).offset(20)", "IDENTITY(1,1)\" \")\" ) def test_identity_separate_from_primary_key(self): metadata = MetaData() tbl =", "with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"DELETE FROM sometable WITH (PAGLOCK) \"", "deleted.myid, ' 'deleted.name WHERE mytable.name = :name_1') def test_insert_returning(self): table1", "class CompileTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = mssql.dialect() def test_true_false(self): self.assert_compile( sql.false(),", "FROM [banana split].paj.test WHERE ' '[banana split].paj.test.id = :id_1') s", "(\"[Foo.Bar].[bat]\", \"Foo.Bar\", \"bat\"), ]: schema, owner = base._owner_plus_db(dialect, identifier) eq_(owner,", "test_delete_schema_multipart_both_need_quoting(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "select([tbl]), \"SELECT [foo.dbo].test.id FROM [foo.dbo].test\" ) def test_force_schema_quoted_name_w_dot_case_sensitive(self): metadata =", "SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_delete_hint(self):", "\"(SELECT [banana split].[paj with a space].test.id \" \"FROM [banana split].[paj", "(:somecolumn)\" ) def test_update_hint(self): t = table('sometable', column('somecolumn')) for targ", "'sometable') def test_function_overrides(self): self.assert_compile(func.current_date(), \"GETDATE()\") self.assert_compile(func.length(3), \"LEN(:length_1)\") def test_extract(self): t", ") other = Table( \"#other\", meta, Column(\"sym\", String), Column(\"newval\", Integer)", "= select(cols).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.q, anon_1.p,", "t.c.x.label('q'), t.c.x.label('p'), t.c.y] s = select(cols).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s,", "def test_update_to_select_schema(self): meta = MetaData() table = Table( \"sometable\", meta,", "= func.foo(t.c.x).label('y') stmt1 = select([expr1]).order_by(expr1.desc()).offset(1) stmt2 = select([expr2]).order_by(expr2.desc()).offset(1) self.assert_compile( stmt1,", "t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT sometable.somecolumn FROM sometable WITH (NOLOCK)') def", "self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT ' 'inserted.myid, inserted.name, '", ") c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1])", "self.assert_compile(t.update(t.c.somecolumn == 7), 'UPDATE sometable SET somecolumn=:somecolum' 'n WHERE sometable.somecolumn", "= Table('sometable', m, Column('somecolumn', Integer), schema='test_schema') self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'),", "10, 'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 4) result_map", "(id INTEGER NOT NULL IDENTITY(1,1), \" \"id2 INTEGER NOT NULL", ") def test_sequence_non_primary_key(self): metadata = MetaData() tbl = Table('test', metadata,", "(NULL)\" ) ]: self.assert_compile(expr, compile, dialect=mxodbc_dialect) def test_in_with_subqueries(self): \"\"\"Test removal", "'sometable', m, Column('col1', Integer), Column('col2', Integer)) self.assert_compile(select([func.max(t.c.col1)]), 'SELECT max(sometable.col1) AS", "\"0\" ) self.assert_compile( sql.true(), \"1\" ) def test_select(self): t =", "sqlalchemy import testing from sqlalchemy.dialects.mssql import base class CompileTest(fixtures.TestBase, AssertsCompiledSQL):", "== 1), 'DELETE FROM paj.test WHERE paj.test.id = ' ':id_1')", "FROM t WHERE t.x = :x_1 ORDER BY t.y\", checkparams={'x_1':", "\"CREATE TABLE test (x INTEGER NULL, y INTEGER NULL, \"", "import table, column, quoted_name from sqlalchemy.dialects import mssql from sqlalchemy.dialects.mssql", "supported yet. # def test_delete_from_hint(self): # t = table('sometable', column('somecolumn'))", ") idx = Index(\"myidx\", tbl.c.x, tbl.c.y, mssql_clustered=False) self.assert_compile( schema.CreateIndex(idx), \"CREATE", "where(table.c.sym == other.c.sym) self.assert_compile( stmt, \"UPDATE [schema].sometable SET val=\" \"[#other].newval", "Column('x', Integer) ) self.assert_compile( schema.CreateIndex(Index(\"bar\", t1.c.x > 5)), \"CREATE INDEX", ":col2_2) UNION ' 'SELECT t2.col3 AS col3, t2.col4 AS col4", "order_by = select([t2.c.y]).where(t1.c.x == t2.c.x).as_scalar() s = select([t1]).where(t1.c.x == 5).order_by(order_by)", "other.c.sym) self.assert_compile( stmt, \"UPDATE [schema].sometable SET val=\" \"[#other].newval FROM [schema].sometable,", "s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM banana.paj.test WHERE", "AS bar') def test_function(self): self.assert_compile(func.foo(1, 2), 'foo(:foo_1, :foo_2)') self.assert_compile(func.current_time(), 'CURRENT_TIME')", "INTEGER NOT NULL IDENTITY(1,1)\" \")\" ) def test_identity_separate_from_primary_key(self): metadata =", "t2.x)\" \") AS mssql_rn \" \"FROM t1 \" \"WHERE t1.x", "m, Column('x', Integer) ) self.assert_compile( schema.CreateIndex(Index(\"bar\", t1.c.x > 5)), \"CREATE", "from sqlalchemy import testing from sqlalchemy.dialects.mssql import base class CompileTest(fixtures.TestBase,", "mxodbc_dialect.statement_compiler = MSSQLStrictCompiler t = table('sometable', column('foo')) for expr, compile", "test_limit_offset_w_ambiguous_cols(self): t = table('t', column('x', Integer), column('y', Integer)) cols =", "= s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1]) def test_limit_offset_using_window(self):", "self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"UPDATE", "\"WHERE t.x = :x_1) AS anon_1 \" \"WHERE mssql_rn >", "self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT test_schema.sometable.somecolumn ' 'FROM test_schema.sometable WITH", "AS \" \"myid FROM mytable) AS foo, mytable WHERE \"", "(' 'SELECT [banana split].paj.test.id FROM ' '[banana split].paj.test WHERE '", "crit = q.c.myid == table1.c.myid self.assert_compile(select(['*'], crit), \"SELECT * FROM", "\"Bar\"), (\"[Foo.Bar]\", None, \"Foo.Bar\"), (\"[Foo.Bar].[bat]\", \"Foo.Bar\", \"bat\"), ]: schema, owner", "t2.col4 AS col4 ' 'FROM t2 WHERE t2.col2 IN (:col2_3,", "test_that_mssql_default_nullability_emits_null(self): eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_none_nullability_does_not_emit_nullability(self): self.column.nullable = None", "self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" ) def test_schema_autosplit_w_dot_case_insensitive(self): metadata", "= Table('test', metadata, Column('id', Integer, Sequence('', 0), primary_key=True)) with testing.expect_deprecated(", "4) result_map = c._create_result_map() for col in cols: is_(result_map[col.key][1][0], col)", "eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_none_nullability_does_not_emit_nullability(self): self.column.nullable = None eq_(\"test_column", "t1.col4 AS col4 ' 'FROM t1 WHERE t1.col2 IN (:col2_1,", "'t2', column('col1'), column('col2'), column('col3'), column('col4')) s1, s2 = select( [t1.c.col3.label('col3'),", "u = update(table1, values=dict(name='foo')).returning(table1) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT", "= Table('test', metadata, Column('id', Integer, Sequence('', start=5), primary_key=False)) with testing.expect_deprecated(", "\"FROM (SELECT t.x AS x, t.x AS q, t.x AS", "Column('id', Integer, primary_key=True), schema='banana split.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM", "y))\" ) def test_table_uc_clustering(self): metadata = MetaData() tbl = Table('test',", "a1 = table('t1', column('c1')).alias('a1') t2 = table('t2', column('c1')) q =", "\"UPDATE [schema].sometable SET val=\" \"[#other].newval FROM [schema].sometable, \" \"[#other] WHERE", "NOT NULL IDENTITY(1,1))\" ) def test_identity_start_0(self): metadata = MetaData() tbl", "primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL,", "' ':col2_2) UNION SELECT t2.col3 AS col3, ' 't2.col4 AS", "\" \"anon_1 WHERE mssql_rn > :param_1\", checkparams={'param_1': 20, 'x_1': 5}", "x, t.x AS q, t.x AS p, t.y AS y,", "MetaData() t = Table( 'sometable', m, Column('col1', Integer), Column('col2', Integer))", "ORDER BY clauses from subqueries\"\"\" table1 = table('mytable', column('myid', Integer),", ") def test_owner_database_pairs(self): dialect = mssql.dialect() for identifier, expected_schema, expected_owner", "Table('test', metadata, Column('id', Integer, autoincrement=False, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "TODO: not supported yet. # def test_delete_from_hint(self): # t =", "MetaData() t = Table('sometable', m, Column('somecolumn', Integer), schema='test_schema') self.assert_compile( t.select().with_hint(t,", "Column('id', Integer, primary_key=True), schema=\"[Foo.dbo]\" ) self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM", "= None eq_(\"test_column VARCHAR(max)\", self._column_spec()) def test_that_mssql_specified_nullable_emits_null(self): self.column.nullable = True", "\" \"SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def", "'WITH (NOLOCK)'), 'SELECT sometable.somecolumn FROM sometable WITH (NOLOCK)') def test_select_with_nolock_schema(self):", "Integer), column(\"c\", Integer), ) join = t1.join(t2, t1.c.a == t2.c.a).\\", "WHERE sometable.foo \" \"IN ('x', 'y', 'z')\", ), ( t.c.foo.in_([None]),", "two autoincrements will do right now self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "t.delete(). where(t.c.somecolumn == \"q\"). with_hint(\"XYZ\", dialect_name=\"mysql\"), \"DELETE FROM sometable WHERE", "somecolumn=:somecolumn \" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_delete_hint(self): t", "\"SELECT anon_1.x, anon_1.y \" \"FROM (SELECT t1.x AS x, t1.y", "schema='paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM paj.test WHERE paj.test.id =", "mssql_rn > :param_1\" ) def test_limit_zero_offset_using_window(self): t = table('t', column('x',", "String(128))) d = delete(table1).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM mytable OUTPUT", "tbl = Table('test', metadata, Column('id', Integer, Sequence('', start=5), primary_key=False)) with", "produces TOP 0 self.assert_compile( s, \"SELECT TOP 0 t.x, t.y", "mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER NOT NULL,", "BY t.y) AS mssql_rn \" \"FROM t \" \"WHERE t.x", "select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile( tbl.delete().where(tbl.c.id.in_(s)), \"DELETE FROM [banana split].[paj with", "= t2.c1\" ) self.assert_compile(sql.delete(a1), \"DELETE FROM t1 AS a1\") def", "= MetaData() tbl = Table('test', metadata, Column('id', Integer, primary_key=True), schema='banana", "in [ ( select([literal(\"x\"), literal(\"y\")]), \"SELECT 'x' AS anon_1, 'y'", "Integer, primary_key=True), schema='paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM paj.test WHERE", "= q.c.myid == table1.c.myid self.assert_compile(select(['*'], crit), \"SELECT * FROM (SELECT", "self.assert_compile( join, 'SELECT t1.a, t1.b, t1.c, t2.a, t2.b, t2.c '", "= select([t]).where(t.c.x == 5).order_by(t.c.y).offset(20) # test that the select is", "idx = Index(\"foo\", tbl.c.id, mssql_clustered=True) self.assert_compile(schema.CreateIndex(idx), \"CREATE CLUSTERED INDEX foo", "split].paj.test WHERE ' '[banana split].paj.test.id = :id_1)') def test_delete_schema_multipart_both_need_quoting(self): metadata", "split].paj.test.id = :id_1)') def test_delete_schema_multipart_both_need_quoting(self): metadata = MetaData() tbl =", "(:col2_3, ' ':col2_4)) AS bar') def test_function(self): self.assert_compile(func.foo(1, 2), 'foo(:foo_1,", "MetaData() tbl = Table('test', metadata, Column('id', Integer, mssql_identity_increment=5, primary_key=True)) self.assert_compile(", "'inserted.myid, inserted.name, ' 'inserted.description') u = update( table1, values=dict( name='foo')).returning(table1).where(table1.c.name", "q = select([table1.c.myid], order_by=[table1.c.myid]).alias('foo') crit = q.c.myid == table1.c.myid self.assert_compile(select(['*'],", "Integer) ) stmt = table.update().values( val=select([other.c.newval]). where(table.c.sym == other.c.sym).as_scalar()) self.assert_compile(", "anon_1, 'y' AS anon_2\", ), ( select([t]).where(t.c.foo.in_(['x', 'y', 'z'])), \"SELECT", "(PAGLOCK)\", # selectable=t2, # dialect_name=darg), # \"\" # ) def", "Column('id', Integer, primary_key=True), schema=quoted_name(\"foo.dbo\", True) ) self.assert_compile( select([tbl]), \"SELECT [foo.dbo].test.id", "'sometable)') self.assert_compile(t.select().where(t.c.somecolumn != t.select()), 'SELECT sometable.somecolumn FROM ' 'sometable WHERE", "ORDER BY t.y\", checkparams={'x_1': 5} ) def test_limit_zero_using_top(self): t =", "test_delete_extra_froms_alias(self): a1 = table('t1', column('c1')).alias('a1') t2 = table('t2', column('c1')) q", "AssertsCompiledSQL): __dialect__ = mssql.dialect() def test_true_false(self): self.assert_compile( sql.false(), \"0\" )", "= Table( 'test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False)", "Integer, autoincrement=False), UniqueConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM paj.test WHERE paj.test.id IN ' '(SELECT", "t1 AS a1\") def test_update_from_hint(self): t = table('sometable', column('somecolumn')) t2", "KEY (id))\" ) def test_identity_increment_5(self): metadata = MetaData() tbl =", "Integer), column(\"b\", Integer), column(\"c\", Integer), ) join = t1.join(t2, t1.c.a", "== 1), 'DELETE FROM [banana split].paj.test WHERE ' '[banana split].paj.test.id", "KEY (id))\" ) def test_primary_key_defaults_to_identity(self): metadata = MetaData() tbl =", "= table('sometable', column('somecolumn')) self.assert_compile(t.update(t.c.somecolumn == 7), 'UPDATE sometable SET somecolumn=:somecolum'", "IDENTITY(1,1), \" \"PRIMARY KEY (id))\" ) def test_identity_illegal_two_autoincrements(self): metadata =", "NOT NULL IDENTITY(0,1), \" \"PRIMARY KEY (id))\" ) def test_identity_increment_5(self):", "Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=True)) self.assert_compile(", "import Integer, String, Table, Column, select, MetaData,\\ update, delete, insert,", "> :param_1\", checkparams={'param_1': 20, 'x_1': 5} ) c = s.compile(dialect=mssql.dialect())", "Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"Foo.dbo\", True) ) self.assert_compile(", "table('t1', column('x', Integer), column('y', Integer)) t2 = table('t2', column('x', Integer),", "with a space].test.id IN \" \"(SELECT [banana split].[paj with a", "select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10) self.assert_compile( s, \"SELECT TOP 10 t.x, t.y", "5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.q, anon_1.p, anon_1.y \" \"FROM", "from sqlalchemy.testing import fixtures, AssertsCompiledSQL from sqlalchemy import sql from", ") def test_drop_index_w_schema(self): m = MetaData() t1 = Table('foo', m,", "\" \"ROW_NUMBER() OVER (ORDER BY t.y) AS mssql_rn \" \"FROM", "String), ) t2 = table('t2', column(\"a\", Integer), column(\"b\", Integer), column(\"c\",", "is_(result_map[col.key][1][0], col) def test_limit_offset_with_correlated_order_by(self): t1 = table('t1', column('x', Integer), column('y',", "'[banana split].paj.test WHERE ' '[banana split].paj.test.id = :id_1)') def test_delete_schema_multipart_both_need_quoting(self):", "AS ' 'tbl_row_count FROM sometable') def test_noorderby_insubquery(self): \"\"\"test that the", "\"\" # ) def test_strict_binds(self): \"\"\"test the 'strict' compiler binds.\"\"\"", "'z'])), \"SELECT sometable.foo FROM sometable WHERE sometable.foo \" \"IN ('x',", "t' % field) def test_update_returning(self): table1 = table( 'mytable', column('myid',", "TOP 0 self.assert_compile( s, \"SELECT TOP 0 t.x, t.y FROM", "' 'WHERE t1.col2 IN (:col2_1, :col2_2) UNION ' 'SELECT t2.col3", "def test_force_schema_quoted_name_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table( 'test', metadata,", "select([t2.c.y]).where(t1.c.x == t2.c.x).as_scalar() s = select([t1]).where(t1.c.x == 5).order_by(order_by) \\ .limit(10).offset(20)", "'deleted.name WHERE mytable.name = :name_1') def test_insert_returning(self): table1 = table(", "values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT ' 'LEN(inserted.name)", "column('c1')) t2 = table('t2', column('c1')) q = sql.delete(t1).where(t1.c.c1 == t2.c.c1)", "t2.c1\" ) def test_delete_extra_froms_alias(self): a1 = table('t1', column('c1')).alias('a1') t2 =", "expr2 = func.foo(t.c.x).label('y') stmt1 = select([expr1]).order_by(expr1.desc()).offset(1) stmt2 = select([expr2]).order_by(expr2.desc()).offset(1) self.assert_compile(", "cols = [t.c.x, t.c.x.label('q'), t.c.x.label('p'), t.c.y] s = select(cols).where(t.c.x ==", "tbl = Table('test', metadata, Column('id', Integer, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE", "t2 WHERE t2.col2 IN ' '(:col2_3, :col2_4) ORDER BY col3,", "= MetaData() tbl = Table('test', metadata, Column('id', Integer)) idx =", ") def test_index_ordering(self): metadata = MetaData() tbl = Table( 'test',", "mssql_rn FROM t) \" \"AS anon_1 WHERE mssql_rn > :param_1\"", "zero, so produces TOP 0 self.assert_compile( s, \"SELECT TOP 0", "\" \"PRIMARY KEY (id))\" ) def test_primary_key_defaults_to_identity(self): metadata = MetaData()", "\"UNIQUE NONCLUSTERED (x, y))\" ) def test_table_uc_clustering(self): metadata = MetaData()", "self.column.nullable = True eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_specified_not_nullable_emits_not_null(self): self.column.nullable", "autoincrements will do right now self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "update(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT '", "mytable (name) OUTPUT ' 'inserted.myid, inserted.name VALUES ' '(:name)') i", "\"mssql\"): # self.assert_compile( # t.delete().where(t.c.somecolumn==t2.c.somecolumn). # with_hint(\"WITH (PAGLOCK)\", # selectable=t2,", "def test_force_schema_quoted_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table( 'test', metadata,", "expr1 = func.foo(t.c.x).label('x') expr2 = func.foo(t.c.x).label('y') stmt1 = select([expr1]).order_by(expr1.desc()).offset(1) stmt2", "'SELECT t2.col3 AS col3, t2.col4 AS col4 ' 'FROM t2", "Table('test', metadata, Column('id', Integer, primary_key=True), schema='banana split.paj with a space')", "(id))\" ) def test_sequence_non_primary_key(self): metadata = MetaData() tbl = Table('test',", "2) assert t1.c.x in set(c._create_result_map()['x'][1]) assert t1.c.y in set(c._create_result_map()['y'][1]) def", "(PAGLOCK)\", selectable=targ, dialect_name=darg), \"UPDATE sometable WITH (PAGLOCK) \" \"SET somecolumn=:somecolumn", "== 5).order_by(t.c.y).limit(0).offset(0) # render the LIMIT of zero, but not", "select([literal(\"x\"), literal(\"y\")]), \"SELECT 'x' AS anon_1, 'y' AS anon_2\", ),", "col3, ' 't2.col4 AS col4 FROM t2 WHERE t2.col2 IN", "def test_that_mssql_specified_not_nullable_emits_not_null(self): self.column.nullable = False eq_(\"test_column VARCHAR(max) NOT NULL\", self._column_spec())", "NULL, y INTEGER NOT NULL, \" \"PRIMARY KEY CLUSTERED (x,", "'[banana split].paj.test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)),", ":id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM banana.paj.test", "\" \"mssql_rn FROM t WHERE t.x = :x_1) AS \"", "'FROM banana.paj.test WHERE ' 'banana.paj.test.id = :id_1)') def test_delete_schema_multipart_needs_quoting(self): metadata", "NULL, \" \"PRIMARY KEY NONCLUSTERED (x, y))\" ) def test_table_idx_explicit_nonclustered(self):", "test_update_to_select_schema(self): meta = MetaData() table = Table( \"sometable\", meta, Column(\"sym\",", "'[banana split].paj.test.id IN (' 'SELECT [banana split].paj.test.id FROM ' '[banana", "'y' AS anon_2\", ), ( select([t]).where(t.c.foo.in_(['x', 'y', 'z'])), \"SELECT sometable.foo", "u = update(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(u, 'UPDATE mytable SET name=:name", "s, \"SELECT TOP 10 t.x, t.y FROM t WHERE t.x", "\" \"PRIMARY KEY (id))\" ) def test_identity_illegal_two_autoincrements(self): metadata = MetaData()", "IN ' '(SELECT paj.test.id FROM paj.test ' 'WHERE paj.test.id =", "schema.CreateIndex(Index(\"bar\", t1.c.x > 5)), \"CREATE INDEX bar ON foo (x", "selectable=targ, dialect_name=darg), \"UPDATE sometable WITH (PAGLOCK) \" \"SET somecolumn=:somecolumn \"", "d = delete(table1).where(table1.c.name == 'bar' ).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM", "the 'strict' compiler binds.\"\"\" from sqlalchemy.dialects.mssql.base import MSSQLStrictCompiler mxodbc_dialect =", "sqlalchemy.dialects.mssql import base class CompileTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = mssql.dialect() def", "def test_index_extra_include_1(self): metadata = MetaData() tbl = Table( 'test', metadata,", "in (\"*\", \"mssql\"): self.assert_compile( t.delete().where(t.c.somecolumn == \"q\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ,", "test_select(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.select(), 'SELECT sometable.somecolumn FROM sometable')", "(x, y))\" ) def test_table_pkc_explicit_nonclustered(self): metadata = MetaData() tbl =", "t1.col2 IN (:col2_1, :col2_2) UNION ' 'SELECT t2.col3 AS col3,", "[Foo.dbo].test\" ) def test_schema_autosplit_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table(", "'SELECT test_schema.sometable.somecolumn ' 'FROM test_schema.sometable WITH (NOLOCK)') def test_select_w_order_by_collate(self): m", "self.assert_compile(u, 'SELECT t1.col3 AS col3, t1.col4 AS col4 ' 'FROM", "MetaData() tbl = Table('test', metadata, Column('id', Integer, Sequence('', start=5), primary_key=False))", "AssertsCompiledSQL from sqlalchemy import sql from sqlalchemy import Integer, String,", "self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(1,1)\"", "(\"*\", \"mssql\"): self.assert_compile( t.delete().where(t.c.somecolumn == \"q\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg),", "Table( \"#other\", meta, Column(\"sym\", String), Column(\"newval\", Integer) ) stmt =", "foo ON test (x) INCLUDE (y)\" ) class SchemaTest(fixtures.TestBase): def", "expr, compile in [ ( select([literal(\"x\"), literal(\"y\")]), \"SELECT 'x' AS", "selectable=targ, dialect_name=darg), \"DELETE FROM sometable WITH (PAGLOCK) \" \"WHERE sometable.somecolumn", "paj.test ' 'WHERE paj.test.id = :id_1)') def test_delete_schema_multipart(self): metadata =", "column('name', String(128)), column('description', String(128))) u = update( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name)", "' ':somecolumn_1', dict(somecolumn=10)) def test_insert_hint(self): t = table('sometable', column('somecolumn')) for", "'t1col2r2'])), \\ select([t2.c.col3.label('col3'), t2.c.col4.label('col4')], t2.c.col2.in_(['t2col2r2', 't2col2r3'])) u = union(s1, s2,", "table('t1', column('a', Integer), column('b', String), column('c', String), ) t2 =", "def test_schema_autosplit_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table( 'test', metadata,", "SET name=:name OUTPUT ' 'inserted.myid, inserted.name') u = update(table1, values=dict(name='foo')).returning(table1)", "ON test (id)\" ) def test_index_ordering(self): metadata = MetaData() tbl", "primary_key=True), schema=\"foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT foo.dbo.test.id FROM foo.dbo.test\" )", "sometable.foo FROM sometable WHERE sometable.foo \" \"IN ('x', 'y', 'z')\",", "= :id_1)') def test_delete_schema_multipart_needs_quoting(self): metadata = MetaData() tbl = Table(", "test_noorderby_insubquery(self): \"\"\"test that the ms-sql dialect removes ORDER BY clauses", "column('col4')) t2 = table( 't2', column('col1'), column('col2'), column('col3'), column('col4')) s1,", "Integer, autoincrement=True), ) # this will be rejected by the", "= othertable.somecolumn\" ) def test_update_to_select_schema(self): meta = MetaData() table =", "KEY CLUSTERED (x, y))\" ) def test_table_pkc_explicit_nonclustered(self): metadata = MetaData()", "ORDER BY t.y\", checkparams={'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns),", "Integer)) idx = Index(\"foo\", tbl.c.x, mssql_include=[tbl.c.y]) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo", "field in 'day', 'month', 'year': self.assert_compile( select([extract(field, t.c.col1)]), 'SELECT DATEPART(%s,", "\" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_delete_hint(self): t =", "t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"UPDATE sometable", "table('sometable', column('somecolumn')) for targ in (None, t): for darg in", "c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 4) result_map = c._create_result_map() for col", "AS y, \" \"ROW_NUMBER() OVER (ORDER BY \" \"(SELECT t2.y", "space].test.id = :id_1)\" ) def test_union(self): t1 = table( 't1',", "NULL IDENTITY(5,1))\" ) def test_sequence_ignore_nullability(self): metadata = MetaData() tbl =", "\" \"AS y, ROW_NUMBER() OVER (ORDER BY t.y) AS \"", "\"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(1,1), \" \"PRIMARY", "# render the LIMIT of zero, but not the OFFSET", "m = MetaData() t1 = Table('foo', m, Column('x', Integer), schema='bar'", "= Index(\"foo\", tbl.c.id, mssql_clustered=True) self.assert_compile(schema.CreateIndex(idx), \"CREATE CLUSTERED INDEX foo ON", "primary_key=True), schema=\"Foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT [Foo].dbo.test.id FROM [Foo].dbo.test\" )", "def test_primary_key_no_identity(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "AS \" \"anon_1 WHERE mssql_rn > :param_1\", checkparams={'param_1': 20, 'x_1':", "def setup(self): t = Table('sometable', MetaData(), Column('pk_column', Integer), Column('test_column', String)", "\"): self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL", "INDEX myidx ON test (x, y)\" ) def test_table_uc_explicit_nonclustered(self): metadata", "= Table('test', metadata, Column('id', Integer, mssql_identity_start=0, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE", "sometable.somecolumn = :somecolumn_1\" ) def test_update_exclude_hint(self): t = table('sometable', column('somecolumn'))", "\" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_update_exclude_hint(self): t =", "select( [t1.c.col3.label('col3'), t1.c.col4.label('col4')], t1.c.col2.in_(['t1col2r1', 't1col2r2'])), \\ select([t2.c.col3.label('col3'), t2.c.col4.label('col4')], t2.c.col2.in_(['t2col2r2', 't2col2r3']))", "== 7), 'UPDATE sometable SET somecolumn=:somecolum' 'n WHERE sometable.somecolumn =", "Column('y', Integer), Column('z', Integer)) idx = Index(\"foo\", tbl.c.x.desc(), \"y\") self.assert_compile(schema.CreateIndex(idx),", "test that the select is not altered with subsequent compile", "(SELECT foo(t.x) AS y, \" \"ROW_NUMBER() OVER (ORDER BY foo(t.x)", "tbl.c.x, mssql_include=[tbl.c.y]) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test (x) INCLUDE", ":param_2 + :param_1\", checkparams={'param_1': 20, 'param_2': 10, 'x_1': 5} )", "dialect.ddl_compiler(dialect, schema.CreateTable(t)) def _column_spec(self): return self.ddl_compiler.get_column_specification(self.column) def test_that_mssql_default_nullability_emits_null(self): eq_(\"test_column VARCHAR(max)", "func.foo(t.c.x).label('y') stmt1 = select([expr1]).order_by(expr1.desc()).offset(1) stmt2 = select([expr2]).order_by(expr2.desc()).offset(1) self.assert_compile( stmt1, \"SELECT", "BY t.y\", checkparams={'x_1': 5} ) def test_limit_zero_using_top(self): t = table('t',", "NULL IDENTITY(0,1), \" \"PRIMARY KEY (id))\" ) def test_sequence_non_primary_key(self): metadata", "UniqueConstraint(\"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER NOT", "t.delete().where(t.c.somecolumn == \"q\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"DELETE FROM sometable", "test_force_schema_quoted_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('id',", "FROM (SELECT t.x AS x, t.y \" \"AS y, ROW_NUMBER()", "Column('id', Integer)) idx = Index(\"foo\", tbl.c.id, mssql_clustered=True) self.assert_compile(schema.CreateIndex(idx), \"CREATE CLUSTERED", "% field) def test_update_returning(self): table1 = table( 'mytable', column('myid', Integer),", "table( 't2', column('col1'), column('col2'), column('col3'), column('col4')) s1, s2 = select(", "== t2.c.c1) self.assert_compile( q, \"DELETE FROM t1 FROM t1, t2", "Integer, primary_key=True), schema=quoted_name(\"Foo.dbo\", True) ) self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM", "' ':name_1') u = update(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(u, 'UPDATE mytable", "IDENTITY(5,1))\" ) def test_table_pkc_clustering(self): metadata = MetaData() tbl = Table('test',", "Integer), column('name', String), column('description', String), ) q = select([table1.c.myid], order_by=[table1.c.myid]).alias('foo')", "':col2_2) UNION SELECT t2.col3 AS col3, ' 't2.col4 AS col4", "t1.col4 AS col4 FROM t1 ' 'WHERE t1.col2 IN (:col2_1,", "so produces TOP 0 self.assert_compile( s, \"SELECT TOP 0 t.x,", "= :id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile( tbl.delete().where(tbl.c.id.in_(s)), \"DELETE", "self.assert_compile(func.length(3), \"LEN(:length_1)\") def test_extract(self): t = table('t', column('col1')) for field", "def test_that_mssql_default_nullability_emits_null(self): eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_none_nullability_does_not_emit_nullability(self): self.column.nullable =", "test_union(self): t1 = table( 't1', column('col1'), column('col2'), column('col3'), column('col4')) t2", "AS \" \"mssql_rn FROM t WHERE t.x = :x_1) AS", "metadata, Column('id', Integer, primary_key=True), schema='banana split.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE", "name=:name OUTPUT ' 'inserted.myid, inserted.name') u = update(table1, values=dict(name='foo')).returning(table1) self.assert_compile(u,", "def test_drop_index_w_schema(self): m = MetaData() t1 = Table('foo', m, Column('x',", "t.x AS p, t.y AS y, \" \"ROW_NUMBER() OVER (ORDER", "anon_1 WHERE mssql_rn > :param_1\" ) def test_limit_zero_offset_using_window(self): t =", "NOT NULL IDENTITY(1,1)\" \")\" ) def test_identity_separate_from_primary_key(self): metadata = MetaData()", "UNION SELECT t2.col3 AS col3, ' 't2.col4 AS col4 FROM", "sql.false(), \"0\" ) self.assert_compile( sql.true(), \"1\" ) def test_select(self): t", "self.assert_compile(schema.CreateIndex(idx), \"CREATE CLUSTERED INDEX foo ON test (id)\" ) def", "0), primary_key=True)) with testing.expect_deprecated( \"Use of Sequence with SQL Server", "t1.a = t2.a' ) def test_insert(self): t = table('sometable', column('somecolumn'))", "Integer, mssql_identity_increment=5, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER", "in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\",", "insert(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT '", "VALUES ' '(:name)') i = insert(table1, values=dict(name='foo')).returning(table1) self.assert_compile(i, 'INSERT INTO", "> 5)), \"CREATE INDEX bar ON foo (x > 5)\"", "tbl = Table('test', metadata, Column('id', Integer, Sequence('', 0), primary_key=True)) with", "FROM paj.test WHERE paj.test.id IN ' '(SELECT paj.test.id FROM paj.test", "def test_delete_schema(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "dialect_name=\"mysql\"), \"DELETE FROM sometable WHERE \" \"sometable.somecolumn = :somecolumn_1\" )", "\"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == t2.c.somecolumn). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=t2, dialect_name=darg),", "checkparams={'x_1': 5} ) def test_limit_zero_using_top(self): t = table('t', column('x', Integer),", "myidx ON test (x, y)\" ) def test_table_uc_explicit_nonclustered(self): metadata =", "'test', metadata, Column('id', Integer, primary_key=True), schema='banana.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE", "Sequence with SQL Server in order to affect \"): self.assert_compile(", "test_table_uc_explicit_nonclustered(self): metadata = MetaData() tbl = Table('test', metadata, Column('x', Integer,", "test_schema.sometable.somecolumn ' 'FROM test_schema.sometable WITH (NOLOCK)') def test_select_w_order_by_collate(self): m =", "(x) INCLUDE (y)\" ) class SchemaTest(fixtures.TestBase): def setup(self): t =", "t.y AS y, \" \"ROW_NUMBER() OVER (ORDER BY t.y) AS", "with a space].test.id = :id_1)\" ) def test_union(self): t1 =", "= select([expr2]).order_by(expr2.desc()).offset(1) self.assert_compile( stmt1, \"SELECT anon_1.x FROM (SELECT foo(t.x) AS", "where(table.c.sym == other.c.sym).as_scalar()) self.assert_compile( stmt, \"UPDATE [schema].sometable SET val=\" \"(SELECT", "schema.CreateTable(t)) def _column_spec(self): return self.ddl_compiler.get_column_specification(self.column) def test_that_mssql_default_nullability_emits_null(self): eq_(\"test_column VARCHAR(max) NULL\",", "AS x, t.y AS y, \" \"ROW_NUMBER() OVER (ORDER BY", "sometable WITH (PAGLOCK) \" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def", "= :somecolumn_1\" ) def test_delete_extra_froms(self): t1 = table('t1', column('c1')) t2", "\"LEN(:length_1)\") def test_extract(self): t = table('t', column('col1')) for field in", "metadata, Column('id', Integer, autoincrement=False, primary_key=True), Column('x', Integer, autoincrement=True) ) self.assert_compile(", "that the select is not altered with subsequent compile #", "# the two autoincrements will do right now self.assert_compile( schema.CreateTable(tbl),", "\"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(1,1)\" \")\" )", "space].test \" \"WHERE [banana split].[paj with a space].test.id IN \"", "self.assert_compile( t.update().where(t.c.somecolumn == t2.c.somecolumn). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=t2, dialect_name=darg), \"UPDATE", "'bar' ).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM mytable OUTPUT deleted.myid, '", "table('t2', column(\"a\", Integer), column(\"b\", Integer), column(\"c\", Integer), ) join =", "column('b', String), column('c', String), ) t2 = table('t2', column(\"a\", Integer),", "'test', metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"foo.dbo\", True) ) self.assert_compile( select([tbl]),", "column('c1')) q = sql.delete(a1).where(a1.c.c1 == t2.c.c1) self.assert_compile( q, \"DELETE FROM", "self.assert_compile(u.alias('bar').select(), 'SELECT bar.col3, bar.col4 FROM (SELECT ' 't1.col3 AS col3,", "FROM ' 'sometable WHERE sometable.somecolumn != ' '(SELECT sometable.somecolumn FROM", "self._column_spec()) def test_that_mssql_specified_not_nullable_emits_not_null(self): self.column.nullable = False eq_(\"test_column VARCHAR(max) NOT NULL\",", "sometable SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def", "' 'deleted.name') d = delete(table1).where(table1.c.name == 'bar' ).returning(table1.c.myid, table1.c.name) self.assert_compile(d,", "table('t1', column('c1')).alias('a1') t2 = table('t2', column('c1')) q = sql.delete(a1).where(a1.c.c1 ==", "== 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM [banana split].paj.test WHERE ' '[banana", "test (id INTEGER NOT NULL IDENTITY(0,1), \" \"PRIMARY KEY (id))\"", "'FROM t2 WHERE t2.col2 IN (:col2_3, ' ':col2_4)) AS bar')", "Column('id', Integer, Sequence('', 0), primary_key=True)) with testing.expect_deprecated( \"Use of Sequence", "OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description') u = update( table1,", "\"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_sensitive(self): metadata = MetaData()", "'SELECT DATEPART(%s, t.col1) AS anon_1 FROM t' % field) def", "tbl.c.y, mssql_clustered=False) self.assert_compile( schema.CreateIndex(idx), \"CREATE NONCLUSTERED INDEX myidx ON test", "= MetaData() tbl = Table( 'test', metadata, Column('x', Integer, autoincrement=False),", "a space].test \" \"WHERE [banana split].[paj with a space].test.id IN", "[banana split].[paj with a space].test.id = :id_1)\" ) def test_union(self):", "(ORDER BY \" \"(SELECT t2.y FROM t2 WHERE t1.x =", "\" \"ROW_NUMBER() OVER (ORDER BY foo(t.x) DESC) AS mssql_rn FROM", ")).returning(func.length(table1.c.name)) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT ' 'LEN(inserted.name) AS", "foo ON test (id)\" ) def test_index_ordering(self): metadata = MetaData()", "\"anon_1 WHERE mssql_rn > :param_1\", checkparams={'param_1': 20, 'x_1': 5} )", "stmt, \"UPDATE [schema].sometable SET val=\" \"(SELECT [#other].newval FROM [#other] \"", "t1 = table('t1', column('a', Integer), column('b', String), column('c', String), )", "autoincrement=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL", "\"CREATE INDEX foo ON test (x) INCLUDE (y)\" ) def", "' '[banana split].paj.test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id == 1)", "' 'inserted.myid, inserted.name VALUES ' '(:name)') i = insert(table1, values=dict(name='foo')).returning(table1)", "MetaData() tbl = Table('test', metadata, Column('id', Integer, primary_key=True)) self.assert_compile( schema.CreateTable(tbl),", "test_index_clustering(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer))", "Integer), Column('y', Integer), Column('z', Integer)) idx = Index(\"foo\", tbl.c.x.desc(), \"y\")", "def test_update_returning(self): table1 = table( 'mytable', column('myid', Integer), column('name', String(128)),", "test_offset_dont_misapply_labelreference(self): m = MetaData() t = Table('t', m, Column('x', Integer))", "metadata, Column('id', Integer, Sequence('', start=5), nullable=True)) with testing.expect_deprecated( \"Use of", "anon_1.y \" \"FROM (SELECT t.x AS x, t.y AS y,", "somecolumn=:somecolum' 'n WHERE sometable.somecolumn = ' ':somecolumn_1', dict(somecolumn=10)) def test_insert_hint(self):", "tbl.delete().where(tbl.c.id.in_(s)), \"DELETE FROM [banana split].[paj with a space].test \" \"WHERE", "= func.foo(t.c.x).label('x') expr2 = func.foo(t.c.x).label('y') stmt1 = select([expr1]).order_by(expr1.desc()).offset(1) stmt2 =", "test_select_w_order_by_collate(self): m = MetaData() t = Table('sometable', m, Column('somecolumn', String))", "test_force_schema_quoted_name_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('id',", ") def test_update_exclude_hint(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.update().where(t.c.somecolumn ==", "s, \"SELECT anon_1.x, anon_1.y \" \"FROM (SELECT t1.x AS x,", "' '[banana split].paj.test.id = :id_1)') def test_delete_schema_multipart_both_need_quoting(self): metadata = MetaData()", "FROM sometable') def test_noorderby_insubquery(self): \"\"\"test that the ms-sql dialect removes", "FROM [banana split].paj.test WHERE ' '[banana split].paj.test.id IN (' 'SELECT", "NOT NULL, \" \"PRIMARY KEY CLUSTERED (x, y))\" ) def", "checkparams={'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x", "\" \"WHERE sometable.somecolumn = othertable.somecolumn\" ) def test_update_to_select_schema(self): meta =", "t = table('t', column('x', Integer), column('y', Integer)) cols = [t.c.x,", "def test_update(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.update(t.c.somecolumn == 7), 'UPDATE", "= MetaData() t = Table('sometable', m, Column('somecolumn', Integer), schema='test_schema') self.assert_compile(", "table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT '", "True eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_specified_not_nullable_emits_not_null(self): self.column.nullable = False", "values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=t2, dialect_name=darg), \"UPDATE sometable SET somecolumn=:somecolumn \"", "# dialect_name=darg), # \"\" # ) def test_strict_binds(self): \"\"\"test the", ") join = t1.join(t2, t1.c.a == t2.c.a).\\ select().with_hint(t1, 'WITH (NOLOCK)')", "t.y\", checkparams={'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert", "MetaData() tbl = Table( 'test', metadata, Column('x', Integer, autoincrement=False), Column('y',", "select([tbl]), \"SELECT foo.dbo.test.id FROM foo.dbo.test\" ) def test_schema_autosplit_w_dot_case_sensitive(self): metadata =", "t1.c.col2.in_(['t1col2r1', 't1col2r2'])), \\ select([t2.c.col3.label('col3'), t2.c.col4.label('col4')], t2.c.col2.in_(['t2col2r2', 't2col2r3'])) u = union(s1,", "for darg in (\"*\", \"mssql\"): # self.assert_compile( # t.delete().where(t.c.somecolumn==t2.c.somecolumn). #", "t1 = Table('foo', m, Column('x', Integer), schema='bar' ) self.assert_compile( schema.DropIndex(Index(\"idx_foo\",", "t2.c.a).\\ select().with_hint(t1, 'WITH (NOLOCK)') self.assert_compile( join, 'SELECT t1.a, t1.b, t1.c,", "AS mssql_rn FROM t) \" \"AS anon_1 WHERE mssql_rn >", "self.assert_compile( t.insert(). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"INSERT INTO sometable", "darg in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"WITH", "column('somecolumn')) self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT sometable.somecolumn FROM sometable WITH", "= mxodbc.dialect() mxodbc_dialect.statement_compiler = MSSQLStrictCompiler t = table('sometable', column('foo')) for", "TABLE test (id INTEGER NOT NULL, \" \"x INTEGER NOT", "order_by=[table1.c.myid]).alias('foo') crit = q.c.myid == table1.c.myid self.assert_compile(select(['*'], crit), \"SELECT *", ":somecolumn_1\" ) def test_delete_exclude_hint(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.delete().", "\"DELETE FROM sometable WHERE \" \"sometable.somecolumn = :somecolumn_1\" ) def", "select([tbl]), \"SELECT [foo.dbo].test.id FROM [foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_insensitive(self): metadata =", "Integer, primary_key=True), schema='banana split.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM [banana", "Column('x', Integer)) expr1 = func.foo(t.c.x).label('x') expr2 = func.foo(t.c.x).label('y') stmt1 =", "sql.delete(a1).where(a1.c.c1 == t2.c.c1) self.assert_compile( q, \"DELETE FROM a1 FROM t1", ") stmt = table.update().values(val=other.c.newval).\\ where(table.c.sym == other.c.sym) self.assert_compile( stmt, \"UPDATE", "sometable.somecolumn FROM sometable WITH (NOLOCK)') def test_select_with_nolock_schema(self): m = MetaData()", "def test_limit_offset_using_window(self): t = table('t', column('x', Integer), column('y', Integer)) s", "identifier) eq_(owner, expected_owner) eq_(schema, expected_schema) def test_delete_schema(self): metadata = MetaData()", "NOT NULL IDENTITY(5,1))\" ) def test_sequence_ignore_nullability(self): metadata = MetaData() tbl", "Column(\"sym\", String), Column(\"newval\", Integer) ) stmt = table.update().values( val=select([other.c.newval]). where(table.c.sym", "String), Column(\"newval\", Integer) ) stmt = table.update().values( val=select([other.c.newval]). where(table.c.sym ==", "mssql.dialect() self.ddl_compiler = dialect.ddl_compiler(dialect, schema.CreateTable(t)) def _column_spec(self): return self.ddl_compiler.get_column_specification(self.column) def", "KEY (x), UNIQUE CLUSTERED (y))\" ) def test_index_clustering(self): metadata =", "test (id INTEGER NOT NULL, \" \"x INTEGER NOT NULL", "t2 = table('t2', column('c1')) q = sql.delete(a1).where(a1.c.c1 == t2.c.c1) self.assert_compile(", "column('somecolumn')) self.assert_compile( t.delete(). where(t.c.somecolumn == \"q\"). with_hint(\"XYZ\", dialect_name=\"mysql\"), \"DELETE FROM", "AS x, t1.y AS y, \" \"ROW_NUMBER() OVER (ORDER BY", "= MetaData() tbl = Table('test', metadata, Column('id', Integer, mssql_identity_increment=5, primary_key=True))", "':name_1') u = update(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(u, 'UPDATE mytable SET", "self.assert_compile( t.delete(). where(t.c.somecolumn == \"q\"). with_hint(\"XYZ\", dialect_name=\"mysql\"), \"DELETE FROM sometable", "\" \"(somecolumn) VALUES (:somecolumn)\" ) def test_update_hint(self): t = table('sometable',", "FROM [banana split].[paj with a ' 'space].test WHERE [banana split].[paj", "for field in 'day', 'month', 'year': self.assert_compile( select([extract(field, t.c.col1)]), 'SELECT", "= table('t2', column('x', Integer), column('y', Integer)) order_by = select([t2.c.y]).where(t1.c.x ==", "sql from sqlalchemy import Integer, String, Table, Column, select, MetaData,\\", "= s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1]) def test_offset_using_window(self):", "FROM ' 'sometable WHERE sometable.somecolumn = ' '(SELECT sometable.somecolumn FROM", "OVER (ORDER BY t.y) AS mssql_rn \" \"FROM t \"", "TABLE test (id INTEGER NOT NULL IDENTITY(1,5), \" \"PRIMARY KEY", "column('somecolumn')) self.assert_compile(t.count(), 'SELECT count(sometable.somecolumn) AS ' 'tbl_row_count FROM sometable') def", "expected_schema, expected_owner in [ (\"foo\", None, \"foo\"), (\"foo.bar\", \"foo\", \"bar\"),", "OFFSET # of zero, so produces TOP 0 self.assert_compile( s,", "use IN. \"\"\" t = table('sometable', column('somecolumn')) self.assert_compile(t.select().where(t.c.somecolumn == t.select()),", "targ in (None, t): for darg in (\"*\", \"mssql\"): self.assert_compile(", "-*- encoding: utf-8 from sqlalchemy.testing import eq_, is_ from sqlalchemy", "t2.c.somecolumn). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=t2, dialect_name=darg), \"UPDATE sometable SET somecolumn=:somecolumn", "= Table('test', metadata, Column('id', Integer, Sequence('', start=5), nullable=True)) with testing.expect_deprecated(", "' '[banana split].paj.test.id IN (' 'SELECT [banana split].paj.test.id FROM '", "of legacy behavior that converted \"x==subquery\" to use IN. \"\"\"", "INTEGER NOT NULL, y INTEGER NULL, \" \"PRIMARY KEY (x),", "column('y', Integer)) t2 = table('t2', column('x', Integer), column('y', Integer)) order_by", ") def test_identity_increment_5(self): metadata = MetaData() tbl = Table('test', metadata,", "compiler binds.\"\"\" from sqlalchemy.dialects.mssql.base import MSSQLStrictCompiler mxodbc_dialect = mxodbc.dialect() mxodbc_dialect.statement_compiler", "= Table('test', metadata, Column('id', Integer)) idx = Index(\"foo\", tbl.c.id, mssql_clustered=True)", "metadata, Column('id', Integer)) idx = Index(\"foo\", tbl.c.id, mssql_clustered=True) self.assert_compile(schema.CreateIndex(idx), \"CREATE", "FROM t1 FROM t1, t2 WHERE t1.c1 = t2.c1\" )", "set(c._create_result_map()['x'][1]) assert t1.c.y in set(c._create_result_map()['y'][1]) def test_offset_dont_misapply_labelreference(self): m = MetaData()", "eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1]) def test_limit_offset_using_window(self): t =", "\" \"myid FROM mytable) AS foo, mytable WHERE \" \"foo.myid", "t1 WITH (NOLOCK) JOIN t2 ON t1.a = t2.a' )", "removal of legacy behavior that converted \"x==subquery\" to use IN.", "altered with subsequent compile # calls for i in range(2):", "metadata, Column('id', Integer, mssql_identity_start=0, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "expected_owner) eq_(schema, expected_schema) def test_delete_schema(self): metadata = MetaData() tbl =", "<= :param_2 + :param_1\", checkparams={'param_1': 20, 'param_2': 10, 'x_1': 5}", "sometable.somecolumn != ' '(SELECT sometable.somecolumn FROM ' 'sometable)') @testing.uses_deprecated def", "= :somecolumn_1\" ) def test_delete_hint(self): t = table('sometable', column('somecolumn')) for", "= Table('test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), UniqueConstraint(\"x\",", "import mssql from sqlalchemy.dialects.mssql import mxodbc from sqlalchemy.testing import fixtures,", "COLLATE \" \"Latin1_General_CS_AS_KS_WS_CI ASC\" ) def test_join_with_hint(self): t1 = table('t1',", "' 'LEN(inserted.name) AS length_1') def test_delete_returning(self): table1 = table( 'mytable',", "AS q, t.x AS p, t.y AS y, \" \"ROW_NUMBER()", "by the database, just asserting this is what # the", "self.assert_compile( q, \"DELETE FROM a1 FROM t1 AS a1, t2", "y, ROW_NUMBER() OVER (ORDER BY t.y) AS \" \"mssql_rn FROM", "OUTPUT ' 'inserted.myid, inserted.name VALUES ' '(:name)') i = insert(table1,", "column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0).offset(0) #", "INTEGER NOT NULL IDENTITY(0,1), \" \"PRIMARY KEY (id))\" ) def", "table('sometable', column('foo')) for expr, compile in [ ( select([literal(\"x\"), literal(\"y\")]),", "'FROM t1 WITH (NOLOCK) JOIN t2 ON t1.a = t2.a'", "FROM mytable OUTPUT deleted.myid, ' 'deleted.name WHERE mytable.name = :name_1')", "MetaData() tbl = Table('test', metadata, Column('id', Integer, Sequence('', 0), primary_key=True))", "def test_limit_offset_w_ambiguous_cols(self): t = table('t', column('x', Integer), column('y', Integer)) cols", "self.assert_compile(func.foo(), 'foo()') m = MetaData() t = Table( 'sometable', m,", "= MetaData() tbl = Table( 'test', metadata, Column('x', Integer), Column('y',", "from sqlalchemy.sql import table, column, quoted_name from sqlalchemy.dialects import mssql", "split].paj.test WHERE ' '[banana split].paj.test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id", "WHERE ' 'banana.paj.test.id = :id_1)') def test_delete_schema_multipart_needs_quoting(self): metadata = MetaData()", "WHERE ' '[banana split].paj.test.id = :id_1)') def test_delete_schema_multipart_both_need_quoting(self): metadata =", "where(t.c.somecolumn == \"q\"). with_hint(\"XYZ\", dialect_name=\"mysql\"), \"DELETE FROM sometable WHERE \"", "\" \"PRIMARY KEY NONCLUSTERED (x, y))\" ) def test_table_idx_explicit_nonclustered(self): metadata", "(id INTEGER NOT NULL, \" \"PRIMARY KEY (id))\" ) def", "'y', 'z')\", ), ( t.c.foo.in_([None]), \"sometable.foo IN (NULL)\" ) ]:", "UniqueConstraint, Index, Sequence, literal from sqlalchemy import testing from sqlalchemy.dialects.mssql", ":param_1 AND mssql_rn <= :param_2 + :param_1\", checkparams={'param_1': 20, 'param_2':", "\"SELECT sometable.somecolumn FROM sometable \" \"ORDER BY sometable.somecolumn COLLATE \"", "'col4']) self.assert_compile(u, 'SELECT t1.col3 AS col3, t1.col4 AS col4 '", "t.update().where(t.c.somecolumn == t2.c.somecolumn). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=t2, dialect_name=darg), \"UPDATE sometable", "inserted.name, ' 'inserted.description') u = update( table1, values=dict( name='foo')).returning(table1).where(table1.c.name ==", "length_1') def test_delete_returning(self): table1 = table( 'mytable', column('myid', Integer), column('name',", ":id_1)\" ) def test_union(self): t1 = table( 't1', column('col1'), column('col2'),", "= [#other].sym)\", ) stmt = table.update().values(val=other.c.newval).\\ where(table.c.sym == other.c.sym) self.assert_compile(", "OUTPUT ' 'inserted.myid, inserted.name') u = update(table1, values=dict(name='foo')).returning(table1) self.assert_compile(u, 'UPDATE", "select(cols).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.q, anon_1.p, anon_1.y", "somecolumn=:somecolumn \" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_update_exclude_hint(self): t", "' 't1.col3 AS col3, t1.col4 AS col4 FROM t1 '", "in (None, t): for darg in (\"*\", \"mssql\"): self.assert_compile( t.insert().", "self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT ' 'inserted.myid, inserted.name, '", "\"SELECT TOP 0 t.x, t.y FROM t \" \"WHERE t.x", "(x > 5)\" ) def test_drop_index_w_schema(self): m = MetaData() t1", "test_table_uc_clustering(self): metadata = MetaData() tbl = Table('test', metadata, Column('x', Integer,", "other = Table( \"#other\", meta, Column(\"sym\", String), Column(\"newval\", Integer) )", "[Foo.dbo].test.id FROM [Foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_sensitive(self): metadata = MetaData() tbl", "self.assert_compile( s, \"SELECT anon_1.x, anon_1.y FROM (SELECT t.x AS x,", "BY clauses from subqueries\"\"\" table1 = table('mytable', column('myid', Integer), column('name',", "AS anon_1 FROM t' % field) def test_update_returning(self): table1 =", "\"INSERT INTO sometable WITH (PAGLOCK) \" \"(somecolumn) VALUES (:somecolumn)\" )", "calls for i in range(2): self.assert_compile( s, \"SELECT anon_1.x, anon_1.y", "foo(t.x) AS y, \" \"ROW_NUMBER() OVER (ORDER BY foo(t.x) DESC)", "test_insert_returning(self): table1 = table( 'mytable', column('myid', Integer), column('name', String(128)), column('description',", "test_index_ordering(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('x',", "\"CREATE TABLE test (x INTEGER NOT NULL, y INTEGER NULL,", "anon_1.y \" \"FROM (SELECT t.x AS x, t.x AS q,", "space].test.id IN \" \"(SELECT [banana split].[paj with a space].test.id \"", "]: schema, owner = base._owner_plus_db(dialect, identifier) eq_(owner, expected_owner) eq_(schema, expected_schema)", "split].paj.test.id IN (' 'SELECT [banana split].paj.test.id FROM ' '[banana split].paj.test", "[ (\"foo\", None, \"foo\"), (\"foo.bar\", \"foo\", \"bar\"), (\"Foo.Bar\", \"Foo\", \"Bar\"),", "' 'inserted.description') u = update( table1, values=dict( name='foo')).returning(table1).where(table1.c.name == 'bar')", "TABLE test (id INTEGER NOT NULL IDENTITY(1,1), \" \"PRIMARY KEY", "in range(2): self.assert_compile( s, \"SELECT anon_1.x, anon_1.y FROM (SELECT t.x", "20, 'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert", "t.c.somecolumn.collate(\"Latin1_General_CS_AS_KS_WS_CI\").asc()), \"SELECT sometable.somecolumn FROM sometable \" \"ORDER BY sometable.somecolumn COLLATE", "OVER (ORDER BY t.y) AS \" \"mssql_rn FROM t WHERE", "test (id INTEGER NOT NULL, \" \"PRIMARY KEY (id))\" )", "with testing.expect_deprecated( \"Use of Sequence with SQL Server in order", "Column('x', Integer), Column('y', Integer), Column('z', Integer)) idx = Index(\"foo\", tbl.c.x,", "tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema='banana.paj') self.assert_compile(tbl.delete(tbl.c.id", "test_select_with_nolock(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT", "do right now self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER", "'(:name)') def test_limit_using_top(self): t = table('t', column('x', Integer), column('y', Integer))", "anon_1.p, anon_1.y \" \"FROM (SELECT t.x AS x, t.x AS", "KEY (id))\" ) def test_sequence_non_primary_key(self): metadata = MetaData() tbl =", "= Table('test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\"),", "INTEGER NULL, \" \"PRIMARY KEY (x), UNIQUE CLUSTERED (y))\" )", "= Table('test', metadata, Column('id', Integer, autoincrement=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "Table('test', metadata, Column('id', Integer, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "autoincrement=False), Column('y', Integer, autoincrement=False) ) idx = Index(\"myidx\", tbl.c.x, tbl.c.y,", "max_1 FROM ' 'sometable') def test_function_overrides(self): self.assert_compile(func.current_date(), \"GETDATE()\") self.assert_compile(func.length(3), \"LEN(:length_1)\")", "1), 'DELETE FROM [banana split].[paj with a ' 'space].test WHERE", "of Sequence with SQL Server in order to affect \"):", "= select([t2.c.y]).where(t1.c.x == t2.c.x).as_scalar() s = select([t1]).where(t1.c.x == 5).order_by(order_by) \\", "what # the two autoincrements will do right now self.assert_compile(", "None, \"foo\"), (\"foo.bar\", \"foo\", \"bar\"), (\"Foo.Bar\", \"Foo\", \"Bar\"), (\"[Foo.Bar]\", None,", "= Table('sometable', m, Column('somecolumn', String)) self.assert_compile( select([t]). order_by( t.c.somecolumn.collate(\"Latin1_General_CS_AS_KS_WS_CI\").asc()), \"SELECT", ":id_1)') def test_delete_schema_multipart(self): metadata = MetaData() tbl = Table( 'test',", "test (id INTEGER NOT NULL IDENTITY(1,1), \" \"PRIMARY KEY (id))\"", "' '(SELECT sometable.somecolumn FROM ' 'sometable)') @testing.uses_deprecated def test_count(self): t", "sometable (somecolumn) VALUES ' '(:somecolumn)') def test_update(self): t = table('sometable',", "= table('sometable', column('somecolumn')) # t2 = table('othertable', column('somecolumn')) # for", "darg in (\"*\", \"mssql\"): self.assert_compile( t.delete().where(t.c.somecolumn == \"q\"). with_hint(\"WITH (PAGLOCK)\",", "CLUSTERED (x, y))\" ) def test_table_pkc_explicit_nonclustered(self): metadata = MetaData() tbl", "' 'tbl_row_count FROM sometable') def test_noorderby_insubquery(self): \"\"\"test that the ms-sql", "t.c.x.label('p'), t.c.y] s = select(cols).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT", "table('othertable', column('somecolumn')) for darg in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn ==", "WHERE paj.test.id IN ' '(SELECT paj.test.id FROM paj.test ' 'WHERE", "anon_1 WHERE mssql_rn > :param_1\" ) self.assert_compile( stmt2, \"SELECT anon_1.y", "= True eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_specified_not_nullable_emits_not_null(self): self.column.nullable =", "\"mysql\"), \"UPDATE sometable SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn = :somecolumn_1\"", "is what # the two autoincrements will do right now", "t1.c.x)), \"DROP INDEX idx_foo ON bar.foo\" ) def test_index_extra_include_1(self): metadata", "'(:name)') i = insert(table1, values=dict(name='foo')).returning(table1) self.assert_compile(i, 'INSERT INTO mytable (name)", "'DELETE FROM banana.paj.test WHERE ' 'banana.paj.test.id = :id_1') s =", "metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer, primary_key=True),", "Index(\"foo\", tbl.c.id, mssql_clustered=True) self.assert_compile(schema.CreateIndex(idx), \"CREATE CLUSTERED INDEX foo ON test", "Integer)) idx = Index(\"foo\", tbl.c.x, mssql_include=['y']) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo", "5)), \"CREATE INDEX bar ON foo (x > 5)\" )", "NULL, \" \"PRIMARY KEY (x), UNIQUE CLUSTERED (y))\" ) def", "':id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM paj.test", "column('description', String(128))) d = delete(table1).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM mytable", "IDENTITY(0,1), \" \"PRIMARY KEY (id))\" ) def test_identity_increment_5(self): metadata =", "dialect removes ORDER BY clauses from subqueries\"\"\" table1 = table('mytable',", "select([expr2]).order_by(expr2.desc()).offset(1) self.assert_compile( stmt1, \"SELECT anon_1.x FROM (SELECT foo(t.x) AS x,", "' 'sometable WHERE sometable.somecolumn = ' '(SELECT sometable.somecolumn FROM '", "values(somecolumn=\"x\"). with_hint(\"XYZ\", \"mysql\"), \"UPDATE sometable SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn", "test_schema_autosplit_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('id',", "1), 'DELETE FROM [banana split].paj.test WHERE ' '[banana split].paj.test.id =", "y)\" ) def test_table_uc_explicit_nonclustered(self): metadata = MetaData() tbl = Table('test',", "max(sometable.col1) AS max_1 FROM ' 'sometable') def test_function_overrides(self): self.assert_compile(func.current_date(), \"GETDATE()\")", "'sometable WHERE sometable.somecolumn = ' '(SELECT sometable.somecolumn FROM ' 'sometable)')", "'year': self.assert_compile( select([extract(field, t.c.col1)]), 'SELECT DATEPART(%s, t.col1) AS anon_1 FROM", "column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0) self.assert_compile(", "= Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"foo.dbo\" ) self.assert_compile(", "MetaData() tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"Foo.dbo\"", "t.col1) AS anon_1 FROM t' % field) def test_update_returning(self): table1", ") def test_delete_hint(self): t = table('sometable', column('somecolumn')) for targ in", "5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.y \" \"FROM (SELECT t.x", "= Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"foo.dbo\", True) )", "Integer), column('y', Integer)) order_by = select([t2.c.y]).where(t1.c.x == t2.c.x).as_scalar() s =", "NULL IDENTITY(0,1), \" \"PRIMARY KEY (id))\" ) def test_identity_increment_5(self): metadata", "BY \" \"(SELECT t2.y FROM t2 WHERE t1.x = t2.x)\"", "p, t.y AS y, \" \"ROW_NUMBER() OVER (ORDER BY t.y)", "FROM sometable WHERE sometable.foo \" \"IN ('x', 'y', 'z')\", ),", "(id INTEGER NOT NULL, \" \"x INTEGER NOT NULL IDENTITY(1,1),", "NONCLUSTERED (x, y))\" ) def test_table_idx_explicit_nonclustered(self): metadata = MetaData() tbl", "\"UPDATE sometable WITH (PAGLOCK) \" \"SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn", "(\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == t2.c.somecolumn). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=t2,", ") def test_force_schema_quoted_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table( 'test',", "MetaData() tbl = Table('test', metadata, Column('id', Integer, primary_key=True), schema='paj') self.assert_compile(tbl.delete(tbl.c.id", "autoincrement=False), PrimaryKeyConstraint(\"x\"), UniqueConstraint(\"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x", "column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).offset(20) #", "\"SET somecolumn=:somecolumn \" \"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_update_exclude_hint(self):", "t2.col2 IN (:col2_3, ' ':col2_4)) AS bar') def test_function(self): self.assert_compile(func.foo(1,", "t.y \" \"AS y, ROW_NUMBER() OVER (ORDER BY t.y) AS", "self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_sensitive(self): metadata", "t.x, t.y FROM t \" \"WHERE t.x = :x_1 ORDER", "tbl = Table('test', metadata, Column('id', Integer, autoincrement=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE", "IN (NULL)\" ) ]: self.assert_compile(expr, compile, dialect=mxodbc_dialect) def test_in_with_subqueries(self): \"\"\"Test", "t2 ON t1.a = t2.a' ) def test_insert(self): t =", "sometable') def test_select_with_nolock(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.select().with_hint(t, 'WITH", "Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), UniqueConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile(", "MetaData() tbl = Table('test', metadata, Column('id', Integer, autoincrement=False, primary_key=True)) self.assert_compile(", "= table( 't1', column('col1'), column('col2'), column('col3'), column('col4')) t2 = table(", "t2.a' ) def test_insert(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.insert(), 'INSERT", "> :param_1 AND mssql_rn <= :param_2 + :param_1\", checkparams={'param_1': 20,", "column('somecolumn')) # t2 = table('othertable', column('somecolumn')) # for darg in", "def test_update_exclude_hint(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.update().where(t.c.somecolumn == \"q\").", "converted \"x==subquery\" to use IN. \"\"\" t = table('sometable', column('somecolumn'))", "'UPDATE mytable SET name=:name OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description')", "(x, y))\" ) def test_table_uc_clustering(self): metadata = MetaData() tbl =", "= :x_1 ORDER BY t.y\", checkparams={'x_1': 5} ) c =", "test (id INTEGER NOT NULL IDENTITY(5,1))\" ) def test_sequence_ignore_nullability(self): metadata", "func, PrimaryKeyConstraint, \\ UniqueConstraint, Index, Sequence, literal from sqlalchemy import", "encoding: utf-8 from sqlalchemy.testing import eq_, is_ from sqlalchemy import", "the select is not altered with subsequent compile # calls", "WHERE mytable.name = :name_1') def test_insert_returning(self): table1 = table( 'mytable',", "self.assert_compile( s, \"SELECT TOP 0 t.x, t.y FROM t \"", "(:col2_1, :col2_2) UNION ' 'SELECT t2.col3 AS col3, t2.col4 AS", "t.x, t.y FROM t WHERE t.x = :x_1 ORDER BY", "metadata, Column('id', Integer, primary_key=True), schema='paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM", "(id INTEGER NOT NULL IDENTITY(1,5), \" \"PRIMARY KEY (id))\" )", "5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t1.c.x in", "be rejected by the database, just asserting this is what", "\"WHERE [banana split].[paj with a space].test.id IN \" \"(SELECT [banana", "for col in cols: is_(result_map[col.key][1][0], col) def test_limit_offset_with_correlated_order_by(self): t1 =", "def test_strict_binds(self): \"\"\"test the 'strict' compiler binds.\"\"\" from sqlalchemy.dialects.mssql.base import", "[Foo].dbo.test.id FROM [Foo].dbo.test\" ) def test_owner_database_pairs(self): dialect = mssql.dialect() for", "def test_index_clustering(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1]) def test_offset_using_window(self): t", "tbl = Table('test', metadata, Column('id', Integer, primary_key=True), schema='banana split.paj with", "\"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER NOT", "cols: is_(result_map[col.key][1][0], col) def test_limit_offset_with_correlated_order_by(self): t1 = table('t1', column('x', Integer),", ") def test_delete_extra_froms(self): t1 = table('t1', column('c1')) t2 = table('t2',", "def test_true_false(self): self.assert_compile( sql.false(), \"0\" ) self.assert_compile( sql.true(), \"1\" )", "'SELECT count(sometable.somecolumn) AS ' 'tbl_row_count FROM sometable') def test_noorderby_insubquery(self): \"\"\"test", "sometable SET somecolumn=:somecolumn \" \"FROM sometable, othertable WITH (PAGLOCK) \"", ") def test_limit_zero_offset_using_window(self): t = table('t', column('x', Integer), column('y', Integer))", "PrimaryKeyConstraint(\"x\"), UniqueConstraint(\"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER", "DESC, y)\" ) def test_create_index_expr(self): m = MetaData() t1 =", "Server in order to affect \"): self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "column('col1'), column('col2'), column('col3'), column('col4')) t2 = table( 't2', column('col1'), column('col2'),", "t2 WHERE t2.col2 IN (:col2_3, ' ':col2_4)) AS bar') def", "t WHERE t.x = :x_1) AS \" \"anon_1 WHERE mssql_rn", "'with a space].test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id == 1)", "u = update( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(u, 'UPDATE mytable SET", "FROM t \" \"WHERE t.x = :x_1 ORDER BY t.y\",", "'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x", "= table('t', column('col1')) for field in 'day', 'month', 'year': self.assert_compile(", "'inserted.description') u = update( table1, values=dict( name='foo')).returning(table1).where(table1.c.name == 'bar') self.assert_compile(u,", "= delete(table1).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM mytable OUTPUT deleted.myid, '", "range(2): self.assert_compile( s, \"SELECT anon_1.x, anon_1.y FROM (SELECT t.x AS", ") def test_limit_zero_using_top(self): t = table('t', column('x', Integer), column('y', Integer))", "Column('y', Integer, autoincrement=False) ) idx = Index(\"myidx\", tbl.c.x, tbl.c.y, mssql_clustered=False)", "sometable.somecolumn = othertable.somecolumn\" ) def test_update_to_select_schema(self): meta = MetaData() table", "table1.c.name) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT ' 'inserted.myid, inserted.name')", "\"WHERE t.x = :x_1 ORDER BY t.y\", checkparams={'x_1': 5} )", "INDEX bar ON foo (x > 5)\" ) def test_drop_index_w_schema(self):", "FROM sometable WITH (NOLOCK)') def test_select_with_nolock_schema(self): m = MetaData() t", "foo, mytable WHERE \" \"foo.myid = mytable.myid\") def test_force_schema_quoted_name_w_dot_case_insensitive(self): metadata", "= [#other].sym\", ) # TODO: not supported yet. # def", ") self.assert_compile( schema.CreateIndex(Index(\"bar\", t1.c.x > 5)), \"CREATE INDEX bar ON", "col3, t1.col4 AS col4 FROM t1 ' 'WHERE t1.col2 IN", "sometable.somecolumn = ' '(SELECT sometable.somecolumn FROM ' 'sometable)') self.assert_compile(t.select().where(t.c.somecolumn !=", "t.c.x in set(c._create_result_map()['x'][1]) def test_offset_using_window(self): t = table('t', column('x', Integer),", "= table('sometable', column('somecolumn')) self.assert_compile( t.delete(). where(t.c.somecolumn == \"q\"). with_hint(\"XYZ\", dialect_name=\"mysql\"),", "(name) OUTPUT ' 'LEN(inserted.name) AS length_1 VALUES ' '(:name)') def", "\"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER NULL,", "for identifier, expected_schema, expected_owner in [ (\"foo\", None, \"foo\"), (\"foo.bar\",", "self.assert_compile( stmt1, \"SELECT anon_1.x FROM (SELECT foo(t.x) AS x, \"", "= Table('test', metadata, Column('id', Integer, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "\"CREATE INDEX foo ON test (x) INCLUDE (y)\" ) class", "metadata = MetaData() tbl = Table( 'test', metadata, Column('x', Integer),", "Sequence, literal from sqlalchemy import testing from sqlalchemy.dialects.mssql import base", "Table('foo', m, Column('x', Integer) ) self.assert_compile( schema.CreateIndex(Index(\"bar\", t1.c.x > 5)),", "\" \"FROM [banana split].[paj with a space].test \" \"WHERE [banana", "table('t2', column('x', Integer), column('y', Integer)) order_by = select([t2.c.y]).where(t1.c.x == t2.c.x).as_scalar()", "with SQL Server in order to affect \"): self.assert_compile( schema.CreateTable(tbl),", "order to affect \"): self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id", "# for darg in (\"*\", \"mssql\"): # self.assert_compile( # t.delete().where(t.c.somecolumn==t2.c.somecolumn).", "Table('test', metadata, Column('id', Integer, mssql_identity_increment=5, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "\" \"FROM sometable, othertable WITH (PAGLOCK) \" \"WHERE sometable.somecolumn =", "WHERE paj.test.id = ' ':id_1') s = select([tbl.c.id]).where(tbl.c.id == 1)", "(id))\" ) def test_sequence_start_0(self): metadata = MetaData() tbl = Table('test',", "metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer, mssql_identity_increment=5,", "' 'banana.paj.test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)),", ") self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_sensitive(self):", "\"WHERE [schema].sometable.sym = [#other].sym)\", ) stmt = table.update().values(val=other.c.newval).\\ where(table.c.sym ==", "\"bar\"), (\"Foo.Bar\", \"Foo\", \"Bar\"), (\"[Foo.Bar]\", None, \"Foo.Bar\"), (\"[Foo.Bar].[bat]\", \"Foo.Bar\", \"bat\"),", "test (x, y)\" ) def test_table_uc_explicit_nonclustered(self): metadata = MetaData() tbl", "WHERE ' 'banana.paj.test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id == 1)", "table1.c.name) self.assert_compile(d, 'DELETE FROM mytable OUTPUT deleted.myid, ' 'deleted.name') d", "= table('t1', column('a', Integer), column('b', String), column('c', String), ) t2", "tbl.c.id, mssql_clustered=True) self.assert_compile(schema.CreateIndex(idx), \"CREATE CLUSTERED INDEX foo ON test (id)\"", "AS col3, t2.col4 AS col4 ' 'FROM t2 WHERE t2.col2", "(NOLOCK)') def test_select_w_order_by_collate(self): m = MetaData() t = Table('sometable', m,", "table('t', column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10)", "test_limit_using_top(self): t = table('t', column('x', Integer), column('y', Integer)) s =", "(x) INCLUDE (y)\" ) def test_index_extra_include_2(self): metadata = MetaData() tbl", "= MetaData() tbl = Table('test', metadata, Column('id', Integer, autoincrement=True), Column('id2',", "column('name', String(128)), column('description', String(128))) i = insert( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name)", "stmt1 = select([expr1]).order_by(expr1.desc()).offset(1) stmt2 = select([expr2]).order_by(expr2.desc()).offset(1) self.assert_compile( stmt1, \"SELECT anon_1.x", "'y', 'z'])), \"SELECT sometable.foo FROM sometable WHERE sometable.foo \" \"IN", "import eq_, is_ from sqlalchemy import schema from sqlalchemy.sql import", "(name) OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description VALUES (:name)') i", "ON test (x) INCLUDE (y)\" ) class SchemaTest(fixtures.TestBase): def setup(self):", "testing from sqlalchemy.dialects.mssql import base class CompileTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ =", "\"ORDER BY sometable.somecolumn COLLATE \" \"Latin1_General_CS_AS_KS_WS_CI ASC\" ) def test_join_with_hint(self):", "s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 4) result_map = c._create_result_map() for col in cols:", "m, Column('col1', Integer), Column('col2', Integer)) self.assert_compile(select([func.max(t.c.col1)]), 'SELECT max(sometable.col1) AS max_1", "s = select(cols).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.q,", "Integer, autoincrement=True), Column('id2', Integer, autoincrement=True), ) # this will be", "UniqueConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER", "tbl = Table('test', metadata, Column('id', Integer)) idx = Index(\"foo\", tbl.c.id,", "space') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM [banana split].[paj with a", "def test_index_ordering(self): metadata = MetaData() tbl = Table( 'test', metadata,", "select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM [banana split].paj.test WHERE '", "Integer, primary_key=True), schema='banana split.paj with a space') self.assert_compile(tbl.delete(tbl.c.id == 1),", "(y)\" ) class SchemaTest(fixtures.TestBase): def setup(self): t = Table('sometable', MetaData(),", "space].test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile( tbl.delete().where(tbl.c.id.in_(s)),", "AS length_1') def test_delete_returning(self): table1 = table( 'mytable', column('myid', Integer),", "(id))\" ) def test_identity_no_primary_key(self): metadata = MetaData() tbl = Table('test',", "(\"foo\", None, \"foo\"), (\"foo.bar\", \"foo\", \"bar\"), (\"Foo.Bar\", \"Foo\", \"Bar\"), (\"[Foo.Bar]\",", "sometable WHERE sometable.foo \" \"IN ('x', 'y', 'z')\", ), (", "in [ (\"foo\", None, \"foo\"), (\"foo.bar\", \"foo\", \"bar\"), (\"Foo.Bar\", \"Foo\",", "Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"Foo.dbo\" ) self.assert_compile( select([tbl]),", "AS a1, t2 WHERE a1.c1 = t2.c1\" ) self.assert_compile(sql.delete(a1), \"DELETE", "' 'WHERE paj.test.id = :id_1)') def test_delete_schema_multipart(self): metadata = MetaData()", "mytable.myid AS \" \"myid FROM mytable) AS foo, mytable WHERE", "FROM [Foo.dbo].test\" ) def test_force_schema_quoted_w_dot_case_sensitive(self): metadata = MetaData() tbl =", "test_limit_zero_using_top(self): t = table('t', column('x', Integer), column('y', Integer)) s =", "= Table('sometable', MetaData(), Column('pk_column', Integer), Column('test_column', String) ) self.column =", "self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(0,1),", "base._owner_plus_db(dialect, identifier) eq_(owner, expected_owner) eq_(schema, expected_schema) def test_delete_schema(self): metadata =", "metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer, Sequence('',", "5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert t.c.x in", "t1.c.y in set(c._create_result_map()['y'][1]) def test_offset_dont_misapply_labelreference(self): m = MetaData() t =", "mytable (name) OUTPUT ' 'LEN(inserted.name) AS length_1 VALUES ' '(:name)')", "schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER NOT NULL, y INTEGER", "for i in range(2): self.assert_compile( s, \"SELECT anon_1.x, anon_1.y FROM", "== 1) self.assert_compile( tbl.delete().where(tbl.c.id.in_(s)), \"DELETE FROM [banana split].[paj with a", "NULL, y INTEGER NULL, \" \"PRIMARY KEY (x), UNIQUE CLUSTERED", "= Index(\"foo\", tbl.c.x, mssql_include=['y']) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test", "anon_1.x, anon_1.q, anon_1.p, anon_1.y \" \"FROM (SELECT t.x AS x,", "col in cols: is_(result_map[col.key][1][0], col) def test_limit_offset_with_correlated_order_by(self): t1 = table('t1',", "t = table('sometable', column('somecolumn')) # t2 = table('othertable', column('somecolumn')) #", "BY col3, col4') self.assert_compile(u.alias('bar').select(), 'SELECT bar.col3, bar.col4 FROM (SELECT '", "t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"XYZ\", \"mysql\"), \"UPDATE sometable SET somecolumn=:somecolumn", "test_sequence_non_primary_key(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "test_insert_hint(self): t = table('sometable', column('somecolumn')) for targ in (None, t):", "def test_delete_returning(self): table1 = table( 'mytable', column('myid', Integer), column('name', String(128)),", "IDENTITY(5,1))\" ) def test_sequence_ignore_nullability(self): metadata = MetaData() tbl = Table('test',", "column('somecolumn')) for targ in (None, t): for darg in (\"*\",", "update, delete, insert, extract, union, func, PrimaryKeyConstraint, \\ UniqueConstraint, Index,", "t.x = :x_1) AS \" \"anon_1 WHERE mssql_rn > :param_1\",", "test_select_with_nolock_schema(self): m = MetaData() t = Table('sometable', m, Column('somecolumn', Integer),", "t = table('sometable', column('somecolumn')) self.assert_compile( t.delete(). where(t.c.somecolumn == \"q\"). with_hint(\"XYZ\",", "def test_primary_key_defaults_to_identity(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT", "\" \"PRIMARY KEY (x), UNIQUE CLUSTERED (y))\" ) def test_index_clustering(self):", "mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER NULL, y", "Column(\"sym\", String), Column(\"val\", Integer), schema=\"schema\" ) other = Table( \"#other\",", "WITH (PAGLOCK) \" \"WHERE sometable.somecolumn = othertable.somecolumn\" ) def test_update_to_select_schema(self):", "table('sometable', column('somecolumn')) self.assert_compile(t.insert(), 'INSERT INTO sometable (somecolumn) VALUES ' '(:somecolumn)')", "== \"q\"). values(somecolumn=\"x\"). with_hint(\"XYZ\", \"mysql\"), \"UPDATE sometable SET somecolumn=:somecolumn \"", "self.assert_compile( s, \"SELECT anon_1.x, anon_1.y \" \"FROM (SELECT t.x AS", "FROM t) \" \"AS anon_1 WHERE mssql_rn > :param_1\" )", "mytable SET name=:name OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description WHERE", "(PAGLOCK) \" \"WHERE sometable.somecolumn = othertable.somecolumn\" ) def test_update_to_select_schema(self): meta", "metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), UniqueConstraint(\"x\", \"y\", mssql_clustered=False))", "def test_limit_zero_using_top(self): t = table('t', column('x', Integer), column('y', Integer)) s", "the LIMIT of zero, but not the OFFSET # of", "autoincrement=False), UniqueConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x", "= :name_1') def test_insert_returning(self): table1 = table( 'mytable', column('myid', Integer),", "SET val=\" \"[#other].newval FROM [schema].sometable, \" \"[#other] WHERE [schema].sometable.sym =", "column('description', String), ) q = select([table1.c.myid], order_by=[table1.c.myid]).alias('foo') crit = q.c.myid", "val=select([other.c.newval]). where(table.c.sym == other.c.sym).as_scalar()) self.assert_compile( stmt, \"UPDATE [schema].sometable SET val=\"", "primary_key=True), schema=quoted_name(\"Foo.dbo\", True) ) self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\"", "= select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM banana.paj.test WHERE '", "WHERE ' 'banana.paj.test.id IN (SELECT banana.paj.test.id ' 'FROM banana.paj.test WHERE", ") def test_union(self): t1 = table( 't1', column('col1'), column('col2'), column('col3'),", "MetaData() tbl = Table('test', metadata, Column('id', Integer, mssql_identity_start=0, primary_key=True)) self.assert_compile(", "2) assert t.c.x in set(c._create_result_map()['x'][1]) def test_limit_offset_using_window(self): t = table('t',", "t = Table('sometable', m, Column('somecolumn', String)) self.assert_compile( select([t]). order_by( t.c.somecolumn.collate(\"Latin1_General_CS_AS_KS_WS_CI\").asc()),", "in (None, t): for darg in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn", "t = table('sometable', column('somecolumn')) self.assert_compile(t.update(t.c.somecolumn == 7), 'UPDATE sometable SET", "5).order_by(t.c.y).limit(10) self.assert_compile( s, \"SELECT TOP 10 t.x, t.y FROM t", "column('x', Integer), column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile(", "table('othertable', column('somecolumn')) # for darg in (\"*\", \"mssql\"): # self.assert_compile(", "(SELECT t.x AS x, t.y AS y, \" \"ROW_NUMBER() OVER", "\"sometable.foo IN (NULL)\" ) ]: self.assert_compile(expr, compile, dialect=mxodbc_dialect) def test_in_with_subqueries(self):", "FROM sometable') def test_select_with_nolock(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.select().with_hint(t,", "t2 WHERE t1.c1 = t2.c1\" ) def test_delete_extra_froms_alias(self): a1 =", "from sqlalchemy.testing import eq_, is_ from sqlalchemy import schema from", "test_index_extra_include_2(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('x',", "Table( 'test', metadata, Column('id', Integer, primary_key=True), schema='banana.paj') self.assert_compile(tbl.delete(tbl.c.id == 1),", "# \"\" # ) def test_strict_binds(self): \"\"\"test the 'strict' compiler", "MetaData() tbl = Table('test', metadata, Column('id', Integer, Sequence('', start=5), nullable=True))", "ORDER BY col3, col4') self.assert_compile(u.alias('bar').select(), 'SELECT bar.col3, bar.col4 FROM (SELECT", "Integer)) idx = Index(\"foo\", tbl.c.x.desc(), \"y\") self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo", "sometable.somecolumn = :somecolumn_1\" ) def test_delete_hint(self): t = table('sometable', column('somecolumn'))", "t2.col3 AS col3, ' 't2.col4 AS col4 FROM t2 WHERE", "TABLE test (id INTEGER NOT NULL IDENTITY(1,1), \" \"id2 INTEGER", "'SELECT sometable.somecolumn FROM ' 'sometable WHERE sometable.somecolumn != ' '(SELECT", "t1.col3 AS col3, t1.col4 AS col4 ' 'FROM t1 WHERE", "update( table1, values=dict( name='foo')).returning(table1).where(table1.c.name == 'bar') self.assert_compile(u, 'UPDATE mytable SET", "NONCLUSTERED INDEX myidx ON test (x, y)\" ) def test_table_uc_explicit_nonclustered(self):", "INTO sometable WITH (PAGLOCK) \" \"(somecolumn) VALUES (:somecolumn)\" ) def", "INTEGER NULL, y INTEGER NULL, \" \"UNIQUE NONCLUSTERED (x, y))\"", "t.x AS x, t.y AS y, \" \"ROW_NUMBER() OVER (ORDER", "NULL IDENTITY(1,1), \" \"PRIMARY KEY (id))\" ) def test_identity_no_primary_key(self): metadata", "start=5), nullable=True)) with testing.expect_deprecated( \"Use of Sequence with SQL Server", "= Table('test', metadata, Column('id', Integer, mssql_identity_increment=5, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE", "MetaData() t1 = Table('foo', m, Column('x', Integer) ) self.assert_compile( schema.CreateIndex(Index(\"bar\",", "= table('sometable', column('somecolumn')) self.assert_compile(t.count(), 'SELECT count(sometable.somecolumn) AS ' 'tbl_row_count FROM", "OUTPUT ' 'LEN(inserted.name) AS length_1') def test_delete_returning(self): table1 = table(", "test_force_schema_quoted_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('id',", "'DELETE FROM mytable OUTPUT deleted.myid, ' 'deleted.name') d = delete(table1).where(table1.c.name", "\"SELECT * FROM (SELECT mytable.myid AS \" \"myid FROM mytable)", "with a space') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM [banana split].[paj", "a space].test.id IN \" \"(SELECT [banana split].[paj with a space].test.id", "# -*- encoding: utf-8 from sqlalchemy.testing import eq_, is_ from", "column('somecolumn')) # for darg in (\"*\", \"mssql\"): # self.assert_compile( #", "name=:name OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description WHERE mytable.name =", "metadata = MetaData() tbl = Table( 'test', metadata, Column('id', Integer,", "(y))\" ) def test_index_clustering(self): metadata = MetaData() tbl = Table('test',", "'DELETE FROM mytable OUTPUT deleted.myid, ' 'deleted.name WHERE mytable.name =", "== t2.c.a).\\ select().with_hint(t1, 'WITH (NOLOCK)') self.assert_compile( join, 'SELECT t1.a, t1.b,", "name=:name OUTPUT ' 'LEN(inserted.name) AS length_1') def test_delete_returning(self): table1 =", "= :somecolumn_1\" ) def test_delete_exclude_hint(self): t = table('sometable', column('somecolumn')) self.assert_compile(", "self.assert_compile( s, \"SELECT TOP 0 t.x, t.y FROM t WHERE", "of zero, but not the OFFSET # of zero, so", "Integer), column('name', String(128)), column('description', String(128))) i = insert( table1, values=dict(name='foo')).returning(table1.c.myid,", "AS mssql_rn \" \"FROM t1 \" \"WHERE t1.x = :x_1)", "table1.c.name) self.assert_compile(d, 'DELETE FROM mytable OUTPUT deleted.myid, ' 'deleted.name WHERE", "1), 'DELETE FROM banana.paj.test WHERE ' 'banana.paj.test.id = :id_1') s", "INCLUDE (y)\" ) class SchemaTest(fixtures.TestBase): def setup(self): t = Table('sometable',", "= Table('foo', m, Column('x', Integer), schema='bar' ) self.assert_compile( schema.DropIndex(Index(\"idx_foo\", t1.c.x)),", ") q = select([table1.c.myid], order_by=[table1.c.myid]).alias('foo') crit = q.c.myid == table1.c.myid", "test_delete_extra_froms(self): t1 = table('t1', column('c1')) t2 = table('t2', column('c1')) q", "t = Table( 'sometable', m, Column('col1', Integer), Column('col2', Integer)) self.assert_compile(select([func.max(t.c.col1)]),", "t.c.x in set(c._create_result_map()['x'][1]) assert t.c.y in set(c._create_result_map()['y'][1]) def test_limit_offset_w_ambiguous_cols(self): t", "IDENTITY(1,1), \" \"PRIMARY KEY (id))\" ) def test_identity_no_primary_key(self): metadata =", "t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT test_schema.sometable.somecolumn ' 'FROM test_schema.sometable WITH (NOLOCK)')", "\"\"\" t = table('sometable', column('somecolumn')) self.assert_compile(t.select().where(t.c.somecolumn == t.select()), 'SELECT sometable.somecolumn", "values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT ' 'inserted.myid,", "delete(table1).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM mytable OUTPUT deleted.myid, ' 'deleted.name')", "\"sometable\", meta, Column(\"sym\", String), Column(\"val\", Integer), schema=\"schema\" ) other =", "def test_table_uc_clustering(self): metadata = MetaData() tbl = Table('test', metadata, Column('x',", "t2 = table('othertable', column('somecolumn')) for darg in (\"*\", \"mssql\"): self.assert_compile(", "'inserted.myid, inserted.name, ' 'inserted.description WHERE mytable.name = ' ':name_1') u", "import sql from sqlalchemy import Integer, String, Table, Column, select,", "\"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" ) def test_schema_autosplit_w_dot_case_insensitive(self): metadata = MetaData()", "def test_schema_autosplit_w_dot_case_insensitive(self): metadata = MetaData() tbl = Table( 'test', metadata,", ") def test_identity_no_primary_key(self): metadata = MetaData() tbl = Table('test', metadata,", "column('somecolumn')) self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"XYZ\", \"mysql\"), \"UPDATE sometable", "\"DELETE FROM a1 FROM t1 AS a1, t2 WHERE a1.c1", "5).order_by(order_by) \\ .limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.y \" \"FROM", "removes ORDER BY clauses from subqueries\"\"\" table1 = table('mytable', column('myid',", "paj.test WHERE paj.test.id IN ' '(SELECT paj.test.id FROM paj.test '", "Column('x', Integer), schema='bar' ) self.assert_compile( schema.DropIndex(Index(\"idx_foo\", t1.c.x)), \"DROP INDEX idx_foo", "'param_2': 10, 'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 4)", "compile in [ ( select([literal(\"x\"), literal(\"y\")]), \"SELECT 'x' AS anon_1,", "SELECT t2.col3 AS col3, ' 't2.col4 AS col4 FROM t2", "column('x', Integer), column('y', Integer)) t2 = table('t2', column('x', Integer), column('y',", "column('somecolumn')) for darg in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == t2.c.somecolumn).", "crit), \"SELECT * FROM (SELECT mytable.myid AS \" \"myid FROM", "anon_1.y FROM (SELECT foo(t.x) AS y, \" \"ROW_NUMBER() OVER (ORDER", "tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"[Foo.dbo]\" )", "test_table_pkc_explicit_nonclustered(self): metadata = MetaData() tbl = Table('test', metadata, Column('x', Integer,", "'banana.paj.test.id IN (SELECT banana.paj.test.id ' 'FROM banana.paj.test WHERE ' 'banana.paj.test.id", "= :x_1) AS \" \"anon_1 WHERE mssql_rn > :param_1\", checkparams={'param_1':", "for darg in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\").", "= table('t1', column('c1')).alias('a1') t2 = table('t2', column('c1')) q = sql.delete(a1).where(a1.c.c1", "'(:somecolumn)') def test_update(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.update(t.c.somecolumn == 7),", "'UPDATE sometable SET somecolumn=:somecolum' 'n WHERE sometable.somecolumn = ' ':somecolumn_1',", "AS x, t.y \" \"AS y, ROW_NUMBER() OVER (ORDER BY", "autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE", "Index, Sequence, literal from sqlalchemy import testing from sqlalchemy.dialects.mssql import", "q, \"DELETE FROM t1 FROM t1, t2 WHERE t1.c1 =", "Integer, primary_key=True), schema=\"[Foo.dbo]\" ) self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\"", "metadata, Column('id', Integer, autoincrement=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id", "the two autoincrements will do right now self.assert_compile( schema.CreateTable(tbl), \"CREATE", "\"SELECT foo.dbo.test.id FROM foo.dbo.test\" ) def test_schema_autosplit_w_dot_case_sensitive(self): metadata = MetaData()", "column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0).offset(0) # render the", "def test_identity_separate_from_primary_key(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "(id INTEGER NOT NULL IDENTITY(5,1))\" ) def test_sequence_ignore_nullability(self): metadata =", "INDEX foo ON test (x) INCLUDE (y)\" ) class SchemaTest(fixtures.TestBase):", "def test_identity_illegal_two_autoincrements(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "split].[paj with a space].test.id IN \" \"(SELECT [banana split].[paj with", "table1.c.myid self.assert_compile(select(['*'], crit), \"SELECT * FROM (SELECT mytable.myid AS \"", "t2 = table('t2', column('c1')) q = sql.delete(t1).where(t1.c.c1 == t2.c.c1) self.assert_compile(", "== \"q\"). with_hint(\"XYZ\", dialect_name=\"mysql\"), \"DELETE FROM sometable WHERE \" \"sometable.somecolumn", "\"SELECT anon_1.x, anon_1.q, anon_1.p, anon_1.y \" \"FROM (SELECT t.x AS", "def test_that_mssql_specified_nullable_emits_null(self): self.column.nullable = True eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def", "SET val=\" \"(SELECT [#other].newval FROM [#other] \" \"WHERE [schema].sometable.sym =", "sometable') def test_noorderby_insubquery(self): \"\"\"test that the ms-sql dialect removes ORDER", "def test_force_schema_quoted_name_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table( 'test', metadata,", "foo.dbo.test.id FROM foo.dbo.test\" ) def test_schema_autosplit_w_dot_case_sensitive(self): metadata = MetaData() tbl", "column('myid', Integer), column('name', String(128)), column('description', String(128))) d = delete(table1).returning(table1.c.myid, table1.c.name)", "t.x AS x, t.y \" \"AS y, ROW_NUMBER() OVER (ORDER", "> :param_1\" ) def test_limit_zero_offset_using_window(self): t = table('t', column('x', Integer),", "True) ) self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id FROM [Foo.dbo].test\" ) def", "mssql_rn \" \"FROM t1 \" \"WHERE t1.x = :x_1) AS", "'inserted.myid, inserted.name, ' 'inserted.description VALUES (:name)') i = insert(table1, values=dict(name='foo'", "metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"Foo.dbo\", True) ) self.assert_compile( select([tbl]), \"SELECT", "select([extract(field, t.c.col1)]), 'SELECT DATEPART(%s, t.col1) AS anon_1 FROM t' %", "\" \"PRIMARY KEY (id))\" ) def test_identity_no_primary_key(self): metadata = MetaData()", "t2.c.c1) self.assert_compile( q, \"DELETE FROM t1 FROM t1, t2 WHERE", "'SELECT sometable.somecolumn FROM sometable WITH (NOLOCK)') def test_select_with_nolock_schema(self): m =", "values=dict(name='foo')).returning(table1) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT ' 'inserted.myid, inserted.name,", "test_delete_from_hint(self): # t = table('sometable', column('somecolumn')) # t2 = table('othertable',", "5} ) def test_primary_key_no_identity(self): metadata = MetaData() tbl = Table('test',", "\"AS y, ROW_NUMBER() OVER (ORDER BY t.y) AS \" \"mssql_rn", "the ms-sql dialect removes ORDER BY clauses from subqueries\"\"\" table1", "def test_identity_increment_5(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "foo (x > 5)\" ) def test_drop_index_w_schema(self): m = MetaData()", "Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0).offset(0) # render the LIMIT", "table('t', column('x', Integer), column('y', Integer)) cols = [t.c.x, t.c.x.label('q'), t.c.x.label('p'),", "Integer, autoincrement=False), PrimaryKeyConstraint(\"x\"), UniqueConstraint(\"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "sometable.somecolumn FROM ' 'sometable)') self.assert_compile(t.select().where(t.c.somecolumn != t.select()), 'SELECT sometable.somecolumn FROM", "\" \"WHERE t1.x = :x_1) AS anon_1 \" \"WHERE mssql_rn", "[Foo].dbo.test\" ) def test_owner_database_pairs(self): dialect = mssql.dialect() for identifier, expected_schema,", "\"y\") self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test (x DESC, y)\"", "test_extract(self): t = table('t', column('col1')) for field in 'day', 'month',", "Table('test', metadata, Column('id', Integer, autoincrement=True), Column('id2', Integer, autoincrement=True), ) #", "NOT NULL IDENTITY(1,1), \" \"id2 INTEGER NOT NULL IDENTITY(1,1))\" )", "self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM [banana split].paj.test WHERE ' '[banana split].paj.test.id IN", "NOT NULL IDENTITY(0,1), \" \"PRIMARY KEY (id))\" ) def test_sequence_non_primary_key(self):", "select([expr1]).order_by(expr1.desc()).offset(1) stmt2 = select([expr2]).order_by(expr2.desc()).offset(1) self.assert_compile( stmt1, \"SELECT anon_1.x FROM (SELECT", "(:col2_1, ' ':col2_2) UNION SELECT t2.col3 AS col3, ' 't2.col4", "split].[paj with a ' 'space].test WHERE [banana split].[paj ' 'with", "t = table('sometable', column('somecolumn')) self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"XYZ\",", "TABLE test (id INTEGER NOT NULL, \" \"PRIMARY KEY (id))\"", "split.paj with a space') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM [banana", "eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1]) def test_offset_using_window(self): t =", "dict(somecolumn=10)) def test_insert_hint(self): t = table('sometable', column('somecolumn')) for targ in", "AS col3, t1.col4 AS col4 FROM t1 ' 'WHERE t1.col2", "'LEN(inserted.name) AS length_1') def test_delete_returning(self): table1 = table( 'mytable', column('myid',", "Integer), ) join = t1.join(t2, t1.c.a == t2.c.a).\\ select().with_hint(t1, 'WITH", "column('col2'), column('col3'), column('col4')) t2 = table( 't2', column('col1'), column('col2'), column('col3'),", "\"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(5,1))\" ) def", "\"[#other] WHERE [schema].sometable.sym = [#other].sym\", ) # TODO: not supported", "in set(c._create_result_map()['x'][1]) def test_offset_using_window(self): t = table('t', column('x', Integer), column('y',", "eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_specified_not_nullable_emits_not_null(self): self.column.nullable = False eq_(\"test_column", "t2.c.col4.label('col4')], t2.c.col2.in_(['t2col2r2', 't2col2r3'])) u = union(s1, s2, order_by=['col3', 'col4']) self.assert_compile(u,", "self.assert_compile( stmt, \"UPDATE [schema].sometable SET val=\" \"(SELECT [#other].newval FROM [#other]", "MetaData() tbl = Table( 'test', metadata, Column('x', Integer), Column('y', Integer),", "paj.test.id FROM paj.test ' 'WHERE paj.test.id = :id_1)') def test_delete_schema_multipart(self):", "' 'with a space].test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id ==", "idx = Index(\"foo\", tbl.c.x, mssql_include=['y']) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON", ") def test_table_idx_explicit_nonclustered(self): metadata = MetaData() tbl = Table( 'test',", "t = Table('t', m, Column('x', Integer)) expr1 = func.foo(t.c.x).label('x') expr2", "subsequent compile # calls for i in range(2): self.assert_compile( s,", "[foo.dbo].test.id FROM [foo.dbo].test\" ) def test_force_schema_quoted_name_w_dot_case_sensitive(self): metadata = MetaData() tbl", "s, \"SELECT anon_1.x, anon_1.y \" \"FROM (SELECT t.x AS x,", "(SELECT foo(t.x) AS x, \" \"ROW_NUMBER() OVER (ORDER BY foo(t.x)", "def _column_spec(self): return self.ddl_compiler.get_column_specification(self.column) def test_that_mssql_default_nullability_emits_null(self): eq_(\"test_column VARCHAR(max) NULL\", self._column_spec())", ") self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL,", "t = table('sometable', column('somecolumn')) for targ in (None, t): for", "t = table('sometable', column('somecolumn')) self.assert_compile(t.count(), 'SELECT count(sometable.somecolumn) AS ' 'tbl_row_count", "sqlalchemy.testing import fixtures, AssertsCompiledSQL from sqlalchemy import sql from sqlalchemy", "\"CREATE INDEX foo ON test (x DESC, y)\" ) def", "= MetaData() tbl = Table('test', metadata, Column('id', Integer, primary_key=True)) self.assert_compile(", "TOP 10 t.x, t.y FROM t WHERE t.x = :x_1", "'FROM test_schema.sometable WITH (NOLOCK)') def test_select_w_order_by_collate(self): m = MetaData() t", "\"AS anon_1 WHERE mssql_rn > :param_1\" ) self.assert_compile( stmt2, \"SELECT", "autoincrement=False) ) idx = Index(\"myidx\", tbl.c.x, tbl.c.y, mssql_clustered=False) self.assert_compile( schema.CreateIndex(idx),", "Integer), column('name', String(128)), column('description', String(128))) u = update( table1, values=dict(name='foo')).returning(table1.c.myid,", "'(SELECT sometable.somecolumn FROM ' 'sometable)') @testing.uses_deprecated def test_count(self): t =", "self.assert_compile( s, \"SELECT anon_1.x, anon_1.y \" \"FROM (SELECT t1.x AS", "(ORDER BY t.y) AS mssql_rn \" \"FROM t \" \"WHERE", "column, quoted_name from sqlalchemy.dialects import mssql from sqlalchemy.dialects.mssql import mxodbc", "table1 = table('mytable', column('myid', Integer), column('name', String), column('description', String), )", "t \" \"WHERE t.x = :x_1 ORDER BY t.y\", checkparams={'x_1':", "banana.paj.test.id ' 'FROM banana.paj.test WHERE ' 'banana.paj.test.id = :id_1)') def", "mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER NOT NULL,", "SET name=:name OUTPUT ' 'inserted.myid, inserted.name, ' 'inserted.description WHERE mytable.name", "'INSERT INTO mytable (name) OUTPUT ' 'LEN(inserted.name) AS length_1 VALUES", "INTEGER NULL, \" \"UNIQUE NONCLUSTERED (x, y))\" ) def test_table_uc_clustering(self):", "self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM [banana split].[paj with a '", "VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_specified_not_nullable_emits_not_null(self): self.column.nullable = False eq_(\"test_column VARCHAR(max)", "u = update( table1, values=dict( name='foo')).returning(table1).where(table1.c.name == 'bar') self.assert_compile(u, 'UPDATE", "def test_union(self): t1 = table( 't1', column('col1'), column('col2'), column('col3'), column('col4'))", "i = insert(table1, values=dict(name='foo')).returning(table1) self.assert_compile(i, 'INSERT INTO mytable (name) OUTPUT", "DESC) AS mssql_rn FROM t) \" \"AS anon_1 WHERE mssql_rn", ") # this will be rejected by the database, just", "= select([table1.c.myid], order_by=[table1.c.myid]).alias('foo') crit = q.c.myid == table1.c.myid self.assert_compile(select(['*'], crit),", "mssql from sqlalchemy.dialects.mssql import mxodbc from sqlalchemy.testing import fixtures, AssertsCompiledSQL", "mssql_rn <= :param_2 + :param_1\", checkparams={'param_1': 20, 'param_2': 10, 'x_1':", ":param_1\" ) self.assert_compile( stmt2, \"SELECT anon_1.y FROM (SELECT foo(t.x) AS", "FROM ' 'sometable') def test_function_overrides(self): self.assert_compile(func.current_date(), \"GETDATE()\") self.assert_compile(func.length(3), \"LEN(:length_1)\") def", "(NOLOCK)'), 'SELECT test_schema.sometable.somecolumn ' 'FROM test_schema.sometable WITH (NOLOCK)') def test_select_w_order_by_collate(self):", "t1 FROM t1, t2 WHERE t1.c1 = t2.c1\" ) def", "'t1.col3 AS col3, t1.col4 AS col4 FROM t1 ' 'WHERE", "Integer, mssql_identity_start=0, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER", "= Table('test', metadata, Column('id', Integer, autoincrement=False, primary_key=True), Column('x', Integer, autoincrement=True)", "= table('t1', column('c1')) t2 = table('t2', column('c1')) q = sql.delete(t1).where(t1.c.c1", "values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(u, 'UPDATE mytable SET name=:name OUTPUT ' 'LEN(inserted.name)", "somecolumn=:somecolumn \" \"FROM sometable, othertable WITH (PAGLOCK) \" \"WHERE sometable.somecolumn", "FROM (SELECT foo(t.x) AS y, \" \"ROW_NUMBER() OVER (ORDER BY", ") def test_sequence_start_0(self): metadata = MetaData() tbl = Table('test', metadata,", "NONCLUSTERED (x, y))\" ) def test_table_uc_clustering(self): metadata = MetaData() tbl", "autoincrement=True) ) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT", "primary_key=True), schema='banana split.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM [banana split].paj.test", "def test_table_pkc_explicit_nonclustered(self): metadata = MetaData() tbl = Table('test', metadata, Column('x',", "# def test_delete_from_hint(self): # t = table('sometable', column('somecolumn')) # t2", "= table('sometable', column('somecolumn')) self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"XYZ\", \"mysql\"),", "inserted.name, ' 'inserted.description VALUES (:name)') i = insert(table1, values=dict(name='foo' )).returning(func.length(table1.c.name))", "self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM [banana split].paj.test WHERE ' '[banana", ":id_1') s = select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)), 'DELETE FROM [banana", "t.insert(). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"INSERT INTO sometable WITH", ") def test_force_schema_quoted_name_w_dot_case_sensitive(self): metadata = MetaData() tbl = Table( 'test',", "AS x, t.x AS q, t.x AS p, t.y AS", "(id)\" ) def test_index_ordering(self): metadata = MetaData() tbl = Table(", "(x INTEGER NOT NULL, y INTEGER NOT NULL, \" \"PRIMARY", "]: self.assert_compile(expr, compile, dialect=mxodbc_dialect) def test_in_with_subqueries(self): \"\"\"Test removal of legacy", "test_index_extra_include_1(self): metadata = MetaData() tbl = Table( 'test', metadata, Column('x',", "sqlalchemy import sql from sqlalchemy import Integer, String, Table, Column,", ") def test_primary_key_defaults_to_identity(self): metadata = MetaData() tbl = Table('test', metadata,", "with a space].test \" \"WHERE [banana split].[paj with a space].test.id", "\"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(1,5), \" \"PRIMARY", "FROM [foo.dbo].test\" ) def test_force_schema_quoted_name_w_dot_case_sensitive(self): metadata = MetaData() tbl =", ") ]: self.assert_compile(expr, compile, dialect=mxodbc_dialect) def test_in_with_subqueries(self): \"\"\"Test removal of", "test_schema.sometable WITH (NOLOCK)') def test_select_w_order_by_collate(self): m = MetaData() t =", "table('t1', column('c1')) t2 = table('t2', column('c1')) q = sql.delete(t1).where(t1.c.c1 ==", "split].paj.test.id FROM ' '[banana split].paj.test WHERE ' '[banana split].paj.test.id =", "y INTEGER NULL, \" \"UNIQUE NONCLUSTERED (x, y))\" ) def", "select([t1]).where(t1.c.x == 5).order_by(order_by) \\ .limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.y", "self.assert_compile( sql.true(), \"1\" ) def test_select(self): t = table('sometable', column('somecolumn'))", "1), 'DELETE FROM paj.test WHERE paj.test.id = ' ':id_1') s", "union(s1, s2, order_by=['col3', 'col4']) self.assert_compile(u, 'SELECT t1.col3 AS col3, t1.col4", "sometable SET somecolumn=:somecolum' 'n WHERE sometable.somecolumn = ' ':somecolumn_1', dict(somecolumn=10))", "Table( \"sometable\", meta, Column(\"sym\", String), Column(\"val\", Integer), schema=\"schema\" ) other", "FROM (SELECT ' 't1.col3 AS col3, t1.col4 AS col4 FROM", "metadata = MetaData() tbl = Table( 'test', metadata, Column('x', Integer,", "self.column.nullable = None eq_(\"test_column VARCHAR(max)\", self._column_spec()) def test_that_mssql_specified_nullable_emits_null(self): self.column.nullable =", "primary_key=True), schema='banana.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM banana.paj.test WHERE '", "database, just asserting this is what # the two autoincrements", "== 5).order_by(t.c.y).offset(20) # test that the select is not altered", "\"[#other].newval FROM [schema].sometable, \" \"[#other] WHERE [schema].sometable.sym = [#other].sym\", )", "TABLE test (id INTEGER NOT NULL IDENTITY(5,1))\" ) def test_sequence_ignore_nullability(self):", "NULL, \" \"UNIQUE NONCLUSTERED (x, y))\" ) def test_table_uc_clustering(self): metadata", "\" \"(SELECT [banana split].[paj with a space].test.id \" \"FROM [banana", "mssql_rn \" \"FROM t \" \"WHERE t.x = :x_1) AS", "\"q\"). values(somecolumn=\"x\"). with_hint(\"XYZ\", \"mysql\"), \"UPDATE sometable SET somecolumn=:somecolumn \" \"WHERE", "self.assert_compile(d, 'DELETE FROM mytable OUTPUT deleted.myid, ' 'deleted.name WHERE mytable.name", "== t2.c.x).as_scalar() s = select([t1]).where(t1.c.x == 5).order_by(order_by) \\ .limit(10).offset(20) self.assert_compile(", "7), 'UPDATE sometable SET somecolumn=:somecolum' 'n WHERE sometable.somecolumn = '", "from sqlalchemy.dialects.mssql import mxodbc from sqlalchemy.testing import fixtures, AssertsCompiledSQL from", "test (x INTEGER NULL, y INTEGER NULL, \" \"UNIQUE NONCLUSTERED", "t = Table('sometable', MetaData(), Column('pk_column', Integer), Column('test_column', String) ) self.column", "test (x) INCLUDE (y)\" ) def test_index_extra_include_2(self): metadata = MetaData()", "t1.c.a == t2.c.a).\\ select().with_hint(t1, 'WITH (NOLOCK)') self.assert_compile( join, 'SELECT t1.a,", "Table( 'test', metadata, Column('id', Integer, primary_key=True), schema='banana split.paj') self.assert_compile(tbl.delete(tbl.c.id ==", "column('somecolumn')) self.assert_compile(t.insert(), 'INSERT INTO sometable (somecolumn) VALUES ' '(:somecolumn)') def", "t.x = :x_1 ORDER BY t.y\", checkparams={'x_1': 5} ) def", "ON t1.a = t2.a' ) def test_insert(self): t = table('sometable',", "def test_limit_offset_with_correlated_order_by(self): t1 = table('t1', column('x', Integer), column('y', Integer)) t2", "idx = Index(\"foo\", tbl.c.x, mssql_include=[tbl.c.y]) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON", "from sqlalchemy.dialects.mssql.base import MSSQLStrictCompiler mxodbc_dialect = mxodbc.dialect() mxodbc_dialect.statement_compiler = MSSQLStrictCompiler", "eq_(len(c._result_columns), 2) assert t.c.x in set(c._create_result_map()['x'][1]) assert t.c.y in set(c._create_result_map()['y'][1])", "\" \"ROW_NUMBER() OVER (ORDER BY \" \"(SELECT t2.y FROM t2", "'SELECT t1.a, t1.b, t1.c, t2.a, t2.b, t2.c ' 'FROM t1", "Integer)) self.assert_compile(select([func.max(t.c.col1)]), 'SELECT max(sometable.col1) AS max_1 FROM ' 'sometable') def", "table.update().values(val=other.c.newval).\\ where(table.c.sym == other.c.sym) self.assert_compile( stmt, \"UPDATE [schema].sometable SET val=\"", "' 'FROM t1 WITH (NOLOCK) JOIN t2 ON t1.a =", "banana.paj.test WHERE ' 'banana.paj.test.id IN (SELECT banana.paj.test.id ' 'FROM banana.paj.test", "t1.b, t1.c, t2.a, t2.b, t2.c ' 'FROM t1 WITH (NOLOCK)", "space].test.id \" \"FROM [banana split].[paj with a space].test \" \"WHERE", "= table.update().values( val=select([other.c.newval]). where(table.c.sym == other.c.sym).as_scalar()) self.assert_compile( stmt, \"UPDATE [schema].sometable", "AS col3, t1.col4 AS col4 ' 'FROM t1 WHERE t1.col2", "table1, values=dict( name='foo')).returning(table1).where(table1.c.name == 'bar') self.assert_compile(u, 'UPDATE mytable SET name=:name", "column('y', Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10) self.assert_compile( s, \"SELECT", "in set(c._create_result_map()['y'][1]) def test_offset_dont_misapply_labelreference(self): m = MetaData() t = Table('t',", "WITH (PAGLOCK) \" \"(somecolumn) VALUES (:somecolumn)\" ) def test_update_hint(self): t", "= Index(\"foo\", tbl.c.x.desc(), \"y\") self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test", "select([t]).where(t.c.x == 5).order_by(t.c.y).offset(20) # test that the select is not", "column('somecolumn')) t2 = table('othertable', column('somecolumn')) for darg in (\"*\", \"mssql\"):", "with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"INSERT INTO sometable WITH (PAGLOCK) \"", "5)\" ) def test_drop_index_w_schema(self): m = MetaData() t1 = Table('foo',", "sqlalchemy import schema from sqlalchemy.sql import table, column, quoted_name from", "\"CREATE TABLE test (id INTEGER NOT NULL, \" \"PRIMARY KEY", "t2.b, t2.c ' 'FROM t1 WITH (NOLOCK) JOIN t2 ON", "FROM paj.test WHERE paj.test.id = ' ':id_1') s = select([tbl.c.id]).where(tbl.c.id", "literal from sqlalchemy import testing from sqlalchemy.dialects.mssql import base class", "\"ROW_NUMBER() OVER (ORDER BY \" \"(SELECT t2.y FROM t2 WHERE", "\"IN ('x', 'y', 'z')\", ), ( t.c.foo.in_([None]), \"sometable.foo IN (NULL)\"", "\" \"foo.myid = mytable.myid\") def test_force_schema_quoted_name_w_dot_case_insensitive(self): metadata = MetaData() tbl", "NOT NULL, y INTEGER NOT NULL, \" \"PRIMARY KEY NONCLUSTERED", "test_insert(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.insert(), 'INSERT INTO sometable (somecolumn)", "col3, col4') self.assert_compile(u.alias('bar').select(), 'SELECT bar.col3, bar.col4 FROM (SELECT ' 't1.col3", "MetaData() tbl = Table('test', metadata, Column('id', Integer, autoincrement=False, primary_key=True), Column('x',", "\"DROP INDEX idx_foo ON bar.foo\" ) def test_index_extra_include_1(self): metadata =", "t2.c.c1) self.assert_compile( q, \"DELETE FROM a1 FROM t1 AS a1,", "s = select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0).offset(0) # render the LIMIT of", "schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(1,1)\" \")\"", ".limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.y \" \"FROM (SELECT t1.x", "\"foo\", \"bar\"), (\"Foo.Bar\", \"Foo\", \"Bar\"), (\"[Foo.Bar]\", None, \"Foo.Bar\"), (\"[Foo.Bar].[bat]\", \"Foo.Bar\",", "MetaData() t = Table('sometable', m, Column('somecolumn', String)) self.assert_compile( select([t]). order_by(", "# calls for i in range(2): self.assert_compile( s, \"SELECT anon_1.x,", "self.assert_compile(select([func.max(t.c.col1)]), 'SELECT max(sometable.col1) AS max_1 FROM ' 'sometable') def test_function_overrides(self):", "def test_limit_zero_offset_using_window(self): t = table('t', column('x', Integer), column('y', Integer)) s", "the OFFSET # of zero, so produces TOP 0 self.assert_compile(", "t2.c1\" ) self.assert_compile(sql.delete(a1), \"DELETE FROM t1 AS a1\") def test_update_from_hint(self):", "[banana split].[paj ' 'with a space].test.id = :id_1') s =", "self.assert_compile( stmt2, \"SELECT anon_1.y FROM (SELECT foo(t.x) AS y, \"", "self.assert_compile( tbl.delete().where(tbl.c.id.in_(s)), \"DELETE FROM [banana split].[paj with a space].test \"", "\"Foo.Bar\", \"bat\"), ]: schema, owner = base._owner_plus_db(dialect, identifier) eq_(owner, expected_owner)", ").returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM mytable OUTPUT deleted.myid, ' 'deleted.name", "table1 = table( 'mytable', column('myid', Integer), column('name', String(128)), column('description', String(128)))", "\"y\", mssql_clustered=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (x INTEGER NOT", "WHERE mssql_rn > :param_1\" ) self.assert_compile( stmt2, \"SELECT anon_1.y FROM", "WHERE t.x = :x_1 ORDER BY t.y\", checkparams={'x_1': 5} )", "ON bar.foo\" ) def test_index_extra_include_1(self): metadata = MetaData() tbl =", "Column('id', Integer, primary_key=True), schema='banana split.paj with a space') self.assert_compile(tbl.delete(tbl.c.id ==", "FROM banana.paj.test WHERE ' 'banana.paj.test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id", "OVER (ORDER BY foo(t.x) DESC) AS mssql_rn FROM t) \"", "\"PRIMARY KEY NONCLUSTERED (x, y))\" ) def test_table_idx_explicit_nonclustered(self): metadata =", "y, \" \"ROW_NUMBER() OVER (ORDER BY foo(t.x) DESC) AS mssql_rn", "autoincrement=True), ) # this will be rejected by the database,", "FROM [#other] \" \"WHERE [schema].sometable.sym = [#other].sym)\", ) stmt =", "= select( [t1.c.col3.label('col3'), t1.c.col4.label('col4')], t1.c.col2.in_(['t1col2r1', 't1col2r2'])), \\ select([t2.c.col3.label('col3'), t2.c.col4.label('col4')], t2.c.col2.in_(['t2col2r2',", "metadata, Column('id', Integer, Sequence('', start=5), primary_key=False)) with testing.expect_deprecated( \"Use of", "import MSSQLStrictCompiler mxodbc_dialect = mxodbc.dialect() mxodbc_dialect.statement_compiler = MSSQLStrictCompiler t =", "schema.CreateIndex(idx), \"CREATE NONCLUSTERED INDEX myidx ON test (x, y)\" )", "Integer, primary_key=True), schema=\"Foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT [Foo].dbo.test.id FROM [Foo].dbo.test\"", "(y)\" ) def test_index_extra_include_2(self): metadata = MetaData() tbl = Table(", "= :somecolumn_1\" ) def test_update_exclude_hint(self): t = table('sometable', column('somecolumn')) self.assert_compile(", "\"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == \"q\"). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg),", ") def test_insert(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.insert(), 'INSERT INTO", "_column_spec(self): return self.ddl_compiler.get_column_specification(self.column) def test_that_mssql_default_nullability_emits_null(self): eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def", "t2.col3 AS col3, t2.col4 AS col4 ' 'FROM t2 WHERE", "AS y, \" \"ROW_NUMBER() OVER (ORDER BY foo(t.x) DESC) AS", "test_sequence_ignore_nullability(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "\"mssql_rn FROM t WHERE t.x = :x_1) AS \" \"anon_1", "sqlalchemy.dialects.mssql import mxodbc from sqlalchemy.testing import fixtures, AssertsCompiledSQL from sqlalchemy", "base class CompileTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = mssql.dialect() def test_true_false(self): self.assert_compile(", "'DELETE FROM [banana split].paj.test WHERE ' '[banana split].paj.test.id = :id_1')", ":x_1) AS anon_1 \" \"WHERE mssql_rn > :param_1 AND mssql_rn", "dialect_name=darg), # \"\" # ) def test_strict_binds(self): \"\"\"test the 'strict'", "FROM foo.dbo.test\" ) def test_schema_autosplit_w_dot_case_sensitive(self): metadata = MetaData() tbl =", "to use IN. \"\"\" t = table('sometable', column('somecolumn')) self.assert_compile(t.select().where(t.c.somecolumn ==", "== t2.c.c1) self.assert_compile( q, \"DELETE FROM a1 FROM t1 AS", "= Table('foo', m, Column('x', Integer) ) self.assert_compile( schema.CreateIndex(Index(\"bar\", t1.c.x >", "Integer, primary_key=True), schema=quoted_name(\"foo.dbo\", True) ) self.assert_compile( select([tbl]), \"SELECT [foo.dbo].test.id FROM", "FROM (SELECT foo(t.x) AS x, \" \"ROW_NUMBER() OVER (ORDER BY", "def test_sequence_start_0(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "s2 = select( [t1.c.col3.label('col3'), t1.c.col4.label('col4')], t1.c.col2.in_(['t1col2r1', 't1col2r2'])), \\ select([t2.c.col3.label('col3'), t2.c.col4.label('col4')],", "# t2 = table('othertable', column('somecolumn')) # for darg in (\"*\",", ") # TODO: not supported yet. # def test_delete_from_hint(self): #", "(:name)') i = insert(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(i, 'INSERT INTO mytable", "Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=False)) self.assert_compile(", "Integer, String, Table, Column, select, MetaData,\\ update, delete, insert, extract,", "= Table( 'sometable', m, Column('col1', Integer), Column('col2', Integer)) self.assert_compile(select([func.max(t.c.col1)]), 'SELECT", "in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == t2.c.somecolumn). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\",", "\"SELECT anon_1.y FROM (SELECT foo(t.x) AS y, \" \"ROW_NUMBER() OVER", "\" \"UNIQUE NONCLUSTERED (x, y))\" ) def test_table_uc_clustering(self): metadata =", "ON test (x DESC, y)\" ) def test_create_index_expr(self): m =", "def test_sequence_non_primary_key(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "\"x==subquery\" to use IN. \"\"\" t = table('sometable', column('somecolumn')) self.assert_compile(t.select().where(t.c.somecolumn", "split].[paj with a space].test.id = :id_1)\" ) def test_union(self): t1", "UNIQUE CLUSTERED (y))\" ) def test_index_clustering(self): metadata = MetaData() tbl", "'INSERT INTO sometable (somecolumn) VALUES ' '(:somecolumn)') def test_update(self): t", "FROM t1, t2 WHERE t1.c1 = t2.c1\" ) def test_delete_extra_froms_alias(self):", "(PAGLOCK)\", selectable=targ, dialect_name=darg), \"INSERT INTO sometable WITH (PAGLOCK) \" \"(somecolumn)", "), ( t.c.foo.in_([None]), \"sometable.foo IN (NULL)\" ) ]: self.assert_compile(expr, compile,", "INTEGER NOT NULL IDENTITY(1,5), \" \"PRIMARY KEY (id))\" ) def", "s1, s2 = select( [t1.c.col3.label('col3'), t1.c.col4.label('col4')], t1.c.col2.in_(['t1col2r1', 't1col2r2'])), \\ select([t2.c.col3.label('col3'),", "bar.col4 FROM (SELECT ' 't1.col3 AS col3, t1.col4 AS col4", "t1.a, t1.b, t1.c, t2.a, t2.b, t2.c ' 'FROM t1 WITH", "m, Column('somecolumn', Integer), schema='test_schema') self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT test_schema.sometable.somecolumn", "= table('t2', column('c1')) q = sql.delete(a1).where(a1.c.c1 == t2.c.c1) self.assert_compile( q,", "Table( 'sometable', m, Column('col1', Integer), Column('col2', Integer)) self.assert_compile(select([func.max(t.c.col1)]), 'SELECT max(sometable.col1)", "INTEGER NOT NULL, y INTEGER NOT NULL, \" \"PRIMARY KEY", "(PAGLOCK)\", selectable=t2, dialect_name=darg), \"UPDATE sometable SET somecolumn=:somecolumn \" \"FROM sometable,", "(PAGLOCK)\", selectable=targ, dialect_name=darg), \"DELETE FROM sometable WITH (PAGLOCK) \" \"WHERE", "MetaData() tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema='banana", "for expr, compile in [ ( select([literal(\"x\"), literal(\"y\")]), \"SELECT 'x'", "\"FROM t1 \" \"WHERE t1.x = :x_1) AS anon_1 \"", "t1 \" \"WHERE t1.x = :x_1) AS anon_1 \" \"WHERE", "metadata, Column('id', Integer, autoincrement=False, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test", "def test_select_with_nolock(self): t = table('sometable', column('somecolumn')) self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'),", "WHERE \" \"foo.myid = mytable.myid\") def test_force_schema_quoted_name_w_dot_case_insensitive(self): metadata = MetaData()", "\" \"WHERE t.x = :x_1 ORDER BY t.y\", checkparams={'x_1': 5}", "BY sometable.somecolumn COLLATE \" \"Latin1_General_CS_AS_KS_WS_CI ASC\" ) def test_join_with_hint(self): t1", "WHERE mytable.name = ' ':name_1') u = update(table1, values=dict(name='foo' )).returning(func.length(table1.c.name))", "sometable.foo \" \"IN ('x', 'y', 'z')\", ), ( t.c.foo.in_([None]), \"sometable.foo", "' 't2.col4 AS col4 FROM t2 WHERE t2.col2 IN '", "'test', metadata, Column('id', Integer, primary_key=True), schema=\"[Foo.dbo]\" ) self.assert_compile( select([tbl]), \"SELECT", "Column('somecolumn', Integer), schema='test_schema') self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT test_schema.sometable.somecolumn '", "Integer)) cols = [t.c.x, t.c.x.label('q'), t.c.x.label('p'), t.c.y] s = select(cols).where(t.c.x", "i = insert( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(i, 'INSERT INTO mytable", "self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX foo ON test (x DESC, y)\" )", "dialect_name=darg), \"DELETE FROM sometable WITH (PAGLOCK) \" \"WHERE sometable.somecolumn =", "FROM a1 FROM t1 AS a1, t2 WHERE a1.c1 =", "(NOLOCK)') self.assert_compile( join, 'SELECT t1.a, t1.b, t1.c, t2.a, t2.b, t2.c", "t.select()), 'SELECT sometable.somecolumn FROM ' 'sometable WHERE sometable.somecolumn = '", "= select([tbl.c.id]).where(tbl.c.id == 1) self.assert_compile( tbl.delete().where(tbl.c.id.in_(s)), \"DELETE FROM [banana split].[paj", "primary_key=True), schema='banana split.paj with a space') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE", "t2 = table('t2', column('x', Integer), column('y', Integer)) order_by = select([t2.c.y]).where(t1.c.x", "stmt1, \"SELECT anon_1.x FROM (SELECT foo(t.x) AS x, \" \"ROW_NUMBER()", "metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=False))", "10, 'x_1': 5} ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 2) assert", "mxodbc.dialect() mxodbc_dialect.statement_compiler = MSSQLStrictCompiler t = table('sometable', column('foo')) for expr,", "autoincrement=False, primary_key=True), Column('x', Integer, autoincrement=True) ) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE", "metadata, Column('id', Integer, primary_key=True), schema=\"[Foo.dbo]\" ) self.assert_compile( select([tbl]), \"SELECT [Foo.dbo].test.id", "schema='banana split.paj') self.assert_compile(tbl.delete(tbl.c.id == 1), 'DELETE FROM [banana split].paj.test WHERE", "self.assert_compile( select([tbl]), \"SELECT [foo.dbo].test.id FROM [foo.dbo].test\" ) def test_force_schema_quoted_name_w_dot_case_sensitive(self): metadata", "order_by=['col3', 'col4']) self.assert_compile(u, 'SELECT t1.col3 AS col3, t1.col4 AS col4", "t): for darg in (\"*\", \"mssql\"): self.assert_compile( t.delete().where(t.c.somecolumn == \"q\").", "(id))\" ) def test_identity_illegal_two_autoincrements(self): metadata = MetaData() tbl = Table('test',", "selectable=t2, dialect_name=darg), \"UPDATE sometable SET somecolumn=:somecolumn \" \"FROM sometable, othertable", "Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=quoted_name(\"foo.dbo\", True) ) self.assert_compile(", "i = insert(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(i, 'INSERT INTO mytable (name)", ") def test_identity_start_0(self): metadata = MetaData() tbl = Table('test', metadata,", "== t2.c.somecolumn). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=t2, dialect_name=darg), \"UPDATE sometable SET", "tbl = Table('test', metadata, Column('id', Integer, autoincrement=False, primary_key=True), Column('x', Integer,", "IN (SELECT banana.paj.test.id ' 'FROM banana.paj.test WHERE ' 'banana.paj.test.id =", "metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer, primary_key=True))", "= select([expr1]).order_by(expr1.desc()).offset(1) stmt2 = select([expr2]).order_by(expr2.desc()).offset(1) self.assert_compile( stmt1, \"SELECT anon_1.x FROM", "s = select([t]).where(t.c.x == 5).order_by(t.c.y).offset(20) # test that the select", "= table('sometable', column('somecolumn')) self.assert_compile(t.select(), 'SELECT sometable.somecolumn FROM sometable') def test_select_with_nolock(self):", "('x', 'y', 'z')\", ), ( t.c.foo.in_([None]), \"sometable.foo IN (NULL)\" )", "column('name', String), column('description', String), ) q = select([table1.c.myid], order_by=[table1.c.myid]).alias('foo') crit", "FROM (SELECT mytable.myid AS \" \"myid FROM mytable) AS foo,", "tbl = Table('test', metadata, Column('id', Integer, mssql_identity_start=0, primary_key=True)) self.assert_compile( schema.CreateTable(tbl),", ":x_1 ORDER BY t.y\", checkparams={'x_1': 5} ) c = s.compile(dialect=mssql.dialect())", "WHERE \" \"sometable.somecolumn = :somecolumn_1\" ) def test_delete_extra_froms(self): t1 =", "def test_delete_hint(self): t = table('sometable', column('somecolumn')) for targ in (None,", "column('y', Integer)) cols = [t.c.x, t.c.x.label('q'), t.c.x.label('p'), t.c.y] s =", "ROW_NUMBER() OVER (ORDER BY t.y) AS \" \"mssql_rn FROM t", "s, \"SELECT anon_1.x, anon_1.q, anon_1.p, anon_1.y \" \"FROM (SELECT t.x", "column('myid', Integer), column('name', String), column('description', String), ) q = select([table1.c.myid],", "metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer)) idx", "column('col3'), column('col4')) t2 = table( 't2', column('col1'), column('col2'), column('col3'), column('col4'))", "tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema=\"foo.dbo\" )", "column('description', String(128))) u = update( table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name) self.assert_compile(u, 'UPDATE", "String), ) q = select([table1.c.myid], order_by=[table1.c.myid]).alias('foo') crit = q.c.myid ==", "\" \"FROM t \" \"WHERE t.x = :x_1) AS anon_1", "metadata, Column('id', Integer, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id", "= mssql.dialect() for identifier, expected_schema, expected_owner in [ (\"foo\", None,", "\"id2 INTEGER NOT NULL IDENTITY(1,1))\" ) def test_identity_start_0(self): metadata =", "'tbl_row_count FROM sometable') def test_noorderby_insubquery(self): \"\"\"test that the ms-sql dialect", "split].paj.test WHERE ' '[banana split].paj.test.id IN (' 'SELECT [banana split].paj.test.id", "darg in (\"*\", \"mssql\"): self.assert_compile( t.update().where(t.c.somecolumn == t2.c.somecolumn). values(somecolumn=\"x\"). with_hint(\"WITH", "\"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_delete_hint(self): t = table('sometable',", "will do right now self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id", "FROM banana.paj.test WHERE ' 'banana.paj.test.id IN (SELECT banana.paj.test.id ' 'FROM", "expected_schema) def test_delete_schema(self): metadata = MetaData() tbl = Table('test', metadata,", "= MetaData() tbl = Table('test', metadata, Column('x', Integer, autoincrement=False), Column('y',", "col4 ' 'FROM t2 WHERE t2.col2 IN (:col2_3, ' ':col2_4))", "test (x) INCLUDE (y)\" ) class SchemaTest(fixtures.TestBase): def setup(self): t", "'CURRENT_TIME') self.assert_compile(func.foo(), 'foo()') m = MetaData() t = Table( 'sometable',", "\" \"WHERE t.x = :x_1) AS anon_1 \" \"WHERE mssql_rn", "delete(table1).where(table1.c.name == 'bar' ).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM mytable OUTPUT", "t.c.x in set(c._create_result_map()['x'][1]) def test_limit_offset_using_window(self): t = table('t', column('x', Integer),", "':col2_4)) AS bar') def test_function(self): self.assert_compile(func.foo(1, 2), 'foo(:foo_1, :foo_2)') self.assert_compile(func.current_time(),", "select([t]).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x, anon_1.y \" \"FROM", "\"foo.myid = mytable.myid\") def test_force_schema_quoted_name_w_dot_case_insensitive(self): metadata = MetaData() tbl =", "metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\"), UniqueConstraint(\"y\", mssql_clustered=True))", "primary_key=True)) with testing.expect_deprecated( \"Use of Sequence with SQL Server in", "schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(5,1))\" )", "(\"[Foo.Bar]\", None, \"Foo.Bar\"), (\"[Foo.Bar].[bat]\", \"Foo.Bar\", \"bat\"), ]: schema, owner =", "\"UPDATE [schema].sometable SET val=\" \"(SELECT [#other].newval FROM [#other] \" \"WHERE", "== \"q\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"DELETE FROM sometable WITH", "table( 'mytable', column('myid', Integer), column('name', String(128)), column('description', String(128))) d =", ") def test_table_pkc_clustering(self): metadata = MetaData() tbl = Table('test', metadata,", "(x, y))\" ) def test_table_idx_explicit_nonclustered(self): metadata = MetaData() tbl =", "sqlalchemy import Integer, String, Table, Column, select, MetaData,\\ update, delete,", "'(:col2_3, :col2_4) ORDER BY col3, col4') self.assert_compile(u.alias('bar').select(), 'SELECT bar.col3, bar.col4", "AND mssql_rn <= :param_2 + :param_1\", checkparams={'param_1': 20, 'param_2': 10,", "m = MetaData() t = Table('t', m, Column('x', Integer)) expr1", "MetaData() tbl = Table('test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer,", "\"q\"). with_hint(\"XYZ\", dialect_name=\"mysql\"), \"DELETE FROM sometable WHERE \" \"sometable.somecolumn =", "+ :param_1\", checkparams={'param_1': 20, 'param_2': 10, 'x_1': 5} ) c", "start=5), primary_key=False)) with testing.expect_deprecated( \"Use of Sequence with SQL Server", "t \" \"WHERE t.x = :x_1) AS anon_1 \" \"WHERE", "t = table('sometable', column('somecolumn')) self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT sometable.somecolumn", "table('sometable', column('somecolumn')) self.assert_compile(t.select().where(t.c.somecolumn == t.select()), 'SELECT sometable.somecolumn FROM ' 'sometable", "not altered with subsequent compile # calls for i in", ") stmt = table.update().values( val=select([other.c.newval]). where(table.c.sym == other.c.sym).as_scalar()) self.assert_compile( stmt,", "Table( 'test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False) )", "in cols: is_(result_map[col.key][1][0], col) def test_limit_offset_with_correlated_order_by(self): t1 = table('t1', column('x',", "AS col4 ' 'FROM t1 WHERE t1.col2 IN (:col2_1, '", "FROM [Foo].dbo.test\" ) def test_owner_database_pairs(self): dialect = mssql.dialect() for identifier,", "inserted.name') u = update(table1, values=dict(name='foo')).returning(table1) self.assert_compile(u, 'UPDATE mytable SET name=:name", "Integer)) expr1 = func.foo(t.c.x).label('x') expr2 = func.foo(t.c.x).label('y') stmt1 = select([expr1]).order_by(expr1.desc()).offset(1)", "self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id INTEGER NOT NULL IDENTITY(1,1),", "metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\", mssql_clustered=True))", "Integer), Column('z', Integer)) idx = Index(\"foo\", tbl.c.x, mssql_include=[tbl.c.y]) self.assert_compile(schema.CreateIndex(idx), \"CREATE", "anon_1.x FROM (SELECT foo(t.x) AS x, \" \"ROW_NUMBER() OVER (ORDER", "= ' '(SELECT sometable.somecolumn FROM ' 'sometable)') self.assert_compile(t.select().where(t.c.somecolumn != t.select()),", "2) assert t.c.x in set(c._create_result_map()['x'][1]) assert t.c.y in set(c._create_result_map()['y'][1]) def", "Integer), schema='test_schema') self.assert_compile( t.select().with_hint(t, 'WITH (NOLOCK)'), 'SELECT test_schema.sometable.somecolumn ' 'FROM", "WHERE t1.c1 = t2.c1\" ) def test_delete_extra_froms_alias(self): a1 = table('t1',", "table('mytable', column('myid', Integer), column('name', String), column('description', String), ) q =", "Table('test', metadata, Column('x', Integer, autoincrement=False), Column('y', Integer, autoincrement=False), PrimaryKeyConstraint(\"x\", \"y\",", "Column('id', Integer, autoincrement=False, primary_key=True)) self.assert_compile( schema.CreateTable(tbl), \"CREATE TABLE test (id", "String), Column(\"val\", Integer), schema=\"schema\" ) other = Table( \"#other\", meta,", "= table( 'mytable', column('myid', Integer), column('name', String(128)), column('description', String(128))) u", "t.y\", checkparams={'x_1': 5} ) def test_limit_zero_using_top(self): t = table('t', column('x',", "tbl = Table('test', metadata, Column('id', Integer, primary_key=True), schema='paj') self.assert_compile(tbl.delete(tbl.c.id ==", "def test_identity_start_0(self): metadata = MetaData() tbl = Table('test', metadata, Column('id',", "= delete(table1).where(table1.c.name == 'bar' ).returning(table1.c.myid, table1.c.name) self.assert_compile(d, 'DELETE FROM mytable", "AS max_1 FROM ' 'sometable') def test_function_overrides(self): self.assert_compile(func.current_date(), \"GETDATE()\") self.assert_compile(func.length(3),", "' 'sometable WHERE sometable.somecolumn != ' '(SELECT sometable.somecolumn FROM '", "Integer) ) self.assert_compile( schema.CreateIndex(Index(\"bar\", t1.c.x > 5)), \"CREATE INDEX bar", "\" \"AS anon_1 WHERE mssql_rn > :param_1\" ) self.assert_compile( stmt2,", "= c._create_result_map() for col in cols: is_(result_map[col.key][1][0], col) def test_limit_offset_with_correlated_order_by(self):", "self.assert_compile( sql.false(), \"0\" ) self.assert_compile( sql.true(), \"1\" ) def test_select(self):", "stmt = table.update().values(val=other.c.newval).\\ where(table.c.sym == other.c.sym) self.assert_compile( stmt, \"UPDATE [schema].sometable", "metadata, Column('id', Integer, autoincrement=True), Column('id2', Integer, autoincrement=True), ) # this", "= ' ':name_1') u = update(table1, values=dict(name='foo' )).returning(func.length(table1.c.name)) self.assert_compile(u, 'UPDATE", "DATEPART(%s, t.col1) AS anon_1 FROM t' % field) def test_update_returning(self):", "test_identity_start_0(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer,", "String)) self.assert_compile( select([t]). order_by( t.c.somecolumn.collate(\"Latin1_General_CS_AS_KS_WS_CI\").asc()), \"SELECT sometable.somecolumn FROM sometable \"", "MetaData() tbl = Table( 'test', metadata, Column('id', Integer, primary_key=True), schema='banana.paj')", "= :x_1 ORDER BY t.y\", checkparams={'x_1': 5} ) def test_primary_key_no_identity(self):", "AS length_1 VALUES ' '(:name)') def test_limit_using_top(self): t = table('t',", "col4') self.assert_compile(u.alias('bar').select(), 'SELECT bar.col3, bar.col4 FROM (SELECT ' 't1.col3 AS", "col4 FROM t1 ' 'WHERE t1.col2 IN (:col2_1, :col2_2) UNION", "anon_1.x, anon_1.y FROM (SELECT t.x AS x, t.y \" \"AS", "(None, t): for darg in (\"*\", \"mssql\"): self.assert_compile( t.delete().where(t.c.somecolumn ==", "\"AS anon_1 WHERE mssql_rn > :param_1\" ) def test_limit_zero_offset_using_window(self): t", "* FROM (SELECT mytable.myid AS \" \"myid FROM mytable) AS", "test_that_mssql_specified_nullable_emits_null(self): self.column.nullable = True eq_(\"test_column VARCHAR(max) NULL\", self._column_spec()) def test_that_mssql_specified_not_nullable_emits_not_null(self):", "t.y) AS \" \"mssql_rn FROM t WHERE t.x = :x_1)", "FROM sometable \" \"ORDER BY sometable.somecolumn COLLATE \" \"Latin1_General_CS_AS_KS_WS_CI ASC\"", "== \"q\"). values(somecolumn=\"x\"). with_hint(\"WITH (PAGLOCK)\", selectable=targ, dialect_name=darg), \"UPDATE sometable WITH", "Integer)) s = select([t]).where(t.c.x == 5).order_by(t.c.y).offset(20) # test that the", "IDENTITY(1,1))\" ) def test_identity_start_0(self): metadata = MetaData() tbl = Table('test',", "INTEGER NOT NULL IDENTITY(5,1))\" ) def test_table_pkc_clustering(self): metadata = MetaData()", "def test_function_overrides(self): self.assert_compile(func.current_date(), \"GETDATE()\") self.assert_compile(func.length(3), \"LEN(:length_1)\") def test_extract(self): t =", "\"WHERE sometable.somecolumn = :somecolumn_1\" ) def test_update_exclude_hint(self): t = table('sometable',", "= select([t]).where(t.c.x == 5).order_by(t.c.y).limit(0) self.assert_compile( s, \"SELECT TOP 0 t.x,", "\"Foo.Bar\"), (\"[Foo.Bar].[bat]\", \"Foo.Bar\", \"bat\"), ]: schema, owner = base._owner_plus_db(dialect, identifier)", "\"bat\"), ]: schema, owner = base._owner_plus_db(dialect, identifier) eq_(owner, expected_owner) eq_(schema,", "# t = table('sometable', column('somecolumn')) # t2 = table('othertable', column('somecolumn'))", "schema=\"Foo.dbo\" ) self.assert_compile( select([tbl]), \"SELECT [Foo].dbo.test.id FROM [Foo].dbo.test\" ) def", "that the ms-sql dialect removes ORDER BY clauses from subqueries\"\"\"", "t.y FROM t \" \"WHERE t.x = :x_1 ORDER BY", "= select([t1]).where(t1.c.x == 5).order_by(order_by) \\ .limit(10).offset(20) self.assert_compile( s, \"SELECT anon_1.x,", "t = table('t', column('col1')) for field in 'day', 'month', 'year':", "Column('somecolumn', String)) self.assert_compile( select([t]). order_by( t.c.somecolumn.collate(\"Latin1_General_CS_AS_KS_WS_CI\").asc()), \"SELECT sometable.somecolumn FROM sometable", "[#other].sym)\", ) stmt = table.update().values(val=other.c.newval).\\ where(table.c.sym == other.c.sym) self.assert_compile( stmt,", "a space].test.id = :id_1)\" ) def test_union(self): t1 = table(", "mytable OUTPUT deleted.myid, ' 'deleted.name WHERE mytable.name = :name_1') def", "Table('foo', m, Column('x', Integer), schema='bar' ) self.assert_compile( schema.DropIndex(Index(\"idx_foo\", t1.c.x)), \"DROP", "is not altered with subsequent compile # calls for i", "\" \"FROM t1 \" \"WHERE t1.x = :x_1) AS anon_1", "Column('y', Integer), Column('z', Integer)) idx = Index(\"foo\", tbl.c.x, mssql_include=[tbl.c.y]) self.assert_compile(schema.CreateIndex(idx),", "schema='bar' ) self.assert_compile( schema.DropIndex(Index(\"idx_foo\", t1.c.x)), \"DROP INDEX idx_foo ON bar.foo\"", "test_that_mssql_none_nullability_does_not_emit_nullability(self): self.column.nullable = None eq_(\"test_column VARCHAR(max)\", self._column_spec()) def test_that_mssql_specified_nullable_emits_null(self): self.column.nullable", "Column('z', Integer)) idx = Index(\"foo\", tbl.c.x, mssql_include=['y']) self.assert_compile(schema.CreateIndex(idx), \"CREATE INDEX", "0 t.x, t.y FROM t WHERE t.x = :x_1 ORDER", "VALUES ' '(:somecolumn)') def test_update(self): t = table('sometable', column('somecolumn')) self.assert_compile(t.update(t.c.somecolumn", "Integer), schema='bar' ) self.assert_compile( schema.DropIndex(Index(\"idx_foo\", t1.c.x)), \"DROP INDEX idx_foo ON", "banana.paj.test WHERE ' 'banana.paj.test.id = :id_1') s = select([tbl.c.id]).where(tbl.c.id ==", "m, Column('x', Integer), schema='bar' ) self.assert_compile( schema.DropIndex(Index(\"idx_foo\", t1.c.x)), \"DROP INDEX", "' 'inserted.myid, inserted.name, ' 'inserted.description VALUES (:name)') i = insert(table1," ]
[ "of a current lease. :param pulumi.Input[int] lease_duration_seconds: leaseDurationSeconds is a", "lease_duration_seconds is not None: pulumi.set(__self__, \"lease_duration_seconds\", lease_duration_seconds) if lease_transitions is", "renew_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"renew_time\", value) @pulumi.input_type class LeaseArgs: def", "of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" return pulumi.get(self, \"spec\")", "None: pulumi.set(__self__, \"metadata\", metadata) if spec is not None: pulumi.set(__self__,", "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param pulumi.Input['LeaseSpecArgs'] spec: Specification of the Lease.", "pulumi.get(self, \"metadata\") @metadata.setter def metadata(self, value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]): pulumi.set(self, \"metadata\", value)", "acquire it. This is measure against time of last observed", "pulumi.Input[str] kind: Kind is a string value representing the REST", "the endpoint the client submits requests to. Cannot be updated.", "This is measure against time of last observed RenewTime. :param", "current holder of a lease has last updated the lease.", "return pulumi.get(self, \"renew_time\") @renew_time.setter def renew_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"renew_time\",", ":param pulumi.Input[int] lease_duration_seconds: leaseDurationSeconds is a duration that candidates for", "object. Servers should convert recognized schemas to the latest internal", "time when the current lease was acquired. \"\"\" return pulumi.get(self,", "kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"kind\", value) @property @pulumi.getter def metadata(self)", "acquired. \"\"\" return pulumi.get(self, \"acquire_time\") @acquire_time.setter def acquire_time(self, value: Optional[pulumi.Input[str]]):", "@pulumi.getter def metadata(self) -> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]: \"\"\" More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata \"\"\"", "need to wait to force acquire it. This is measure", "kind(self) -> Optional[pulumi.Input[str]]: \"\"\" Kind is a string value representing", "\"\"\" return pulumi.get(self, \"api_version\") @api_version.setter def api_version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,", "return pulumi.get(self, \"metadata\") @metadata.setter def metadata(self, value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]): pulumi.set(self, \"metadata\",", "updated the lease. \"\"\" return pulumi.get(self, \"renew_time\") @renew_time.setter def renew_time(self,", "Optional[pulumi.Input[int]] = None, renew_time: Optional[pulumi.Input[str]] = None): \"\"\" LeaseSpec is", "def renew_time(self) -> Optional[pulumi.Input[str]]: \"\"\" renewTime is a time when", "value: Optional[pulumi.Input[str]]): pulumi.set(self, \"api_version\", value) @property @pulumi.getter def kind(self) ->", "the lease. \"\"\" if acquire_time is not None: pulumi.set(__self__, \"acquire_time\",", "REST resource this object represents. Servers may infer this from", "of a current lease. \"\"\" return pulumi.get(self, \"holder_identity\") @holder_identity.setter def", "has last updated the lease. \"\"\" return pulumi.get(self, \"renew_time\") @renew_time.setter", "class LeaseArgs: def __init__(__self__, *, api_version: Optional[pulumi.Input[str]] = None, kind:", "class LeaseSpecArgs: def __init__(__self__, *, acquire_time: Optional[pulumi.Input[str]] = None, holder_identity:", "pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence,", "*, acquire_time: Optional[pulumi.Input[str]] = None, holder_identity: Optional[pulumi.Input[str]] = None, lease_duration_seconds:", "None, holder_identity: Optional[pulumi.Input[str]] = None, lease_duration_seconds: Optional[pulumi.Input[int]] = None, lease_transitions:", "@pulumi.getter(name=\"acquireTime\") def acquire_time(self) -> Optional[pulumi.Input[str]]: \"\"\" acquireTime is a time", "'LeaseSpecArgs', 'LeaseArgs', ] @pulumi.input_type class LeaseSpecArgs: def __init__(__self__, *, acquire_time:", "https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources \"\"\" return pulumi.get(self, \"api_version\") @api_version.setter def api_version(self, value: Optional[pulumi.Input[str]]):", "if renew_time is not None: pulumi.set(__self__, \"renew_time\", renew_time) @property @pulumi.getter(name=\"acquireTime\")", "defines a lease concept. :param pulumi.Input[str] api_version: APIVersion defines the", "@property @pulumi.getter def spec(self) -> Optional[pulumi.Input['LeaseSpecArgs']]: \"\"\" Specification of the", "api_version: APIVersion defines the versioned schema of this representation of", "not None: pulumi.set(__self__, \"lease_duration_seconds\", lease_duration_seconds) if lease_transitions is not None:", "@property @pulumi.getter(name=\"apiVersion\") def api_version(self) -> Optional[pulumi.Input[str]]: \"\"\" APIVersion defines the", "\"renew_time\", value) @pulumi.input_type class LeaseArgs: def __init__(__self__, *, api_version: Optional[pulumi.Input[str]]", "of a Lease. :param pulumi.Input[str] acquire_time: acquireTime is a time", "Servers should convert recognized schemas to the latest internal value,", "if spec is not None: pulumi.set(__self__, \"spec\", spec) @property @pulumi.getter(name=\"apiVersion\")", "holder_identity(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"holder_identity\", value) @property @pulumi.getter(name=\"leaseDurationSeconds\") def lease_duration_seconds(self)", "pulumi.set(__self__, \"metadata\", metadata) if spec is not None: pulumi.set(__self__, \"spec\",", "'Lease') if metadata is not None: pulumi.set(__self__, \"metadata\", metadata) if", "is not None: pulumi.set(__self__, \"spec\", spec) @property @pulumi.getter(name=\"apiVersion\") def api_version(self)", "is not None: pulumi.set(__self__, \"acquire_time\", acquire_time) if holder_identity is not", "@property @pulumi.getter(name=\"holderIdentity\") def holder_identity(self) -> Optional[pulumi.Input[str]]: \"\"\" holderIdentity contains the", "to force acquire it. This is measure against time of", ":param pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata: More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param pulumi.Input['LeaseSpecArgs'] spec: Specification", "Optional[pulumi.Input[str]] = None, kind: Optional[pulumi.Input[str]] = None, metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] =", "@pulumi.getter(name=\"renewTime\") def renew_time(self) -> Optional[pulumi.Input[str]]: \"\"\" renewTime is a time", "\"\"\" Lease defines a lease concept. :param pulumi.Input[str] api_version: APIVersion", "@pulumi.getter def kind(self) -> Optional[pulumi.Input[str]]: \"\"\" Kind is a string", "value: Optional[pulumi.Input[str]]): pulumi.set(self, \"holder_identity\", value) @property @pulumi.getter(name=\"leaseDurationSeconds\") def lease_duration_seconds(self) ->", "@property @pulumi.getter def metadata(self) -> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]: \"\"\" More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "from ... import meta as _meta __all__ = [ 'LeaseSpecArgs',", "lease_duration_seconds: Optional[pulumi.Input[int]] = None, lease_transitions: Optional[pulumi.Input[int]] = None, renew_time: Optional[pulumi.Input[str]]", "contains the identity of the holder of a current lease.", "__init__(__self__, *, acquire_time: Optional[pulumi.Input[str]] = None, holder_identity: Optional[pulumi.Input[str]] = None,", "that candidates for a lease need to wait to force", "None: pulumi.set(__self__, \"lease_duration_seconds\", lease_duration_seconds) if lease_transitions is not None: pulumi.set(__self__,", "\"\"\" Kind is a string value representing the REST resource", "lease has last updated the lease. \"\"\" if acquire_time is", "updated the lease. \"\"\" if acquire_time is not None: pulumi.set(__self__,", "value: Optional[pulumi.Input[str]]): pulumi.set(self, \"renew_time\", value) @pulumi.input_type class LeaseArgs: def __init__(__self__,", "None): \"\"\" Lease defines a lease concept. :param pulumi.Input[str] api_version:", "\"kind\", value) @property @pulumi.getter def metadata(self) -> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]: \"\"\" More", "__all__ = [ 'LeaseSpecArgs', 'LeaseArgs', ] @pulumi.input_type class LeaseSpecArgs: def", "@pulumi.input_type class LeaseSpecArgs: def __init__(__self__, *, acquire_time: Optional[pulumi.Input[str]] = None,", "current lease was acquired. :param pulumi.Input[str] holder_identity: holderIdentity contains the", "def api_version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"api_version\", value) @property @pulumi.getter def", "None: pulumi.set(__self__, \"lease_transitions\", lease_transitions) if renew_time is not None: pulumi.set(__self__,", "leaseTransitions is the number of transitions of a lease between", "pulumi.Input[str] api_version: APIVersion defines the versioned schema of this representation", "Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" if api_version is not None:", "Specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" if api_version", "None): \"\"\" LeaseSpec is a specification of a Lease. :param", "-> Optional[pulumi.Input['LeaseSpecArgs']]: \"\"\" Specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" return pulumi.get(self, \"spec\") @spec.setter def spec(self,", "spec) @property @pulumi.getter(name=\"apiVersion\") def api_version(self) -> Optional[pulumi.Input[str]]: \"\"\" APIVersion defines", "pulumi.set(self, \"api_version\", value) @property @pulumi.getter def kind(self) -> Optional[pulumi.Input[str]]: \"\"\"", "return pulumi.get(self, \"acquire_time\") @acquire_time.setter def acquire_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"acquire_time\",", "\"lease_duration_seconds\", value) @property @pulumi.getter(name=\"leaseTransitions\") def lease_transitions(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseTransitions", "of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" if api_version is", "Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param pulumi.Input['_meta.v1.ObjectMetaArgs']", "Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]): pulumi.set(self, \"metadata\", value) @property @pulumi.getter def spec(self) -> Optional[pulumi.Input['LeaseSpecArgs']]:", "holder_identity: Optional[pulumi.Input[str]] = None, lease_duration_seconds: Optional[pulumi.Input[int]] = None, lease_transitions: Optional[pulumi.Input[int]]", "hand unless you're certain you know what you are doing!", "schema of this representation of an object. Servers should convert", "'LeaseArgs', ] @pulumi.input_type class LeaseSpecArgs: def __init__(__self__, *, acquire_time: Optional[pulumi.Input[str]]", "has last updated the lease. \"\"\" if acquire_time is not", "Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_duration_seconds\", value) @property @pulumi.getter(name=\"leaseTransitions\") def lease_transitions(self) -> Optional[pulumi.Input[int]]:", "Optional[pulumi.Input[str]]): pulumi.set(self, \"renew_time\", value) @pulumi.input_type class LeaseArgs: def __init__(__self__, *,", "@property @pulumi.getter(name=\"leaseDurationSeconds\") def lease_duration_seconds(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseDurationSeconds is a", "concept. :param pulumi.Input[str] api_version: APIVersion defines the versioned schema of", "@lease_transitions.setter def lease_transitions(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_transitions\", value) @property @pulumi.getter(name=\"renewTime\")", "not None: pulumi.set(__self__, \"metadata\", metadata) if spec is not None:", "renew_time: Optional[pulumi.Input[str]] = None): \"\"\" LeaseSpec is a specification of", "\"metadata\", metadata) if spec is not None: pulumi.set(__self__, \"spec\", spec)", "renew_time) @property @pulumi.getter(name=\"acquireTime\") def acquire_time(self) -> Optional[pulumi.Input[str]]: \"\"\" acquireTime is", "<reponame>polivbr/pulumi-kubernetes # coding=utf-8 # *** WARNING: this file was generated", "be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds \"\"\" return pulumi.get(self,", "In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds \"\"\" return pulumi.get(self, \"kind\") @kind.setter", "unless you're certain you know what you are doing! ***", "def lease_transitions(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseTransitions is the number of", "None: pulumi.set(__self__, \"holder_identity\", holder_identity) if lease_duration_seconds is not None: pulumi.set(__self__,", "may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param pulumi.Input[str] kind:", "submits requests to. Cannot be updated. In CamelCase. More info:", "pulumi.Input[int] lease_duration_seconds: leaseDurationSeconds is a duration that candidates for a", "CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata: More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "is a time when the current lease was acquired. :param", "reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param pulumi.Input[str] kind: Kind", "value) @property @pulumi.getter def metadata(self) -> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]: \"\"\" More info:", "https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds \"\"\" return pulumi.get(self, \"kind\") @kind.setter def kind(self, value: Optional[pulumi.Input[str]]):", "None, lease_duration_seconds: Optional[pulumi.Input[int]] = None, lease_transitions: Optional[pulumi.Input[int]] = None, renew_time:", "acquire_time is not None: pulumi.set(__self__, \"acquire_time\", acquire_time) if holder_identity is", "internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", "Optional[pulumi.Input[str]]: \"\"\" renewTime is a time when the current holder", "\"\"\" if api_version is not None: pulumi.set(__self__, \"api_version\", 'coordination.k8s.io/v1') if", "identity of the holder of a current lease. \"\"\" return", ":param pulumi.Input[str] acquire_time: acquireTime is a time when the current", "holder_identity(self) -> Optional[pulumi.Input[str]]: \"\"\" holderIdentity contains the identity of the", "Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities", "identity of the holder of a current lease. :param pulumi.Input[int]", "the current lease was acquired. :param pulumi.Input[str] holder_identity: holderIdentity contains", "\"api_version\", value) @property @pulumi.getter def kind(self) -> Optional[pulumi.Input[str]]: \"\"\" Kind", "Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]: \"\"\" More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata \"\"\" return pulumi.get(self, \"metadata\") @metadata.setter", "Optional[pulumi.Input[str]]): pulumi.set(self, \"kind\", value) @property @pulumi.getter def metadata(self) -> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]:", "value) @pulumi.input_type class LeaseArgs: def __init__(__self__, *, api_version: Optional[pulumi.Input[str]] =", "values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources \"\"\" return pulumi.get(self, \"api_version\") @api_version.setter def", "import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union,", "what you are doing! *** import warnings import pulumi import", "an object. Servers should convert recognized schemas to the latest", "the identity of the holder of a current lease. \"\"\"", "for a lease need to wait to force acquire it.", "a current lease. :param pulumi.Input[int] lease_duration_seconds: leaseDurationSeconds is a duration", ":param pulumi.Input[str] kind: Kind is a string value representing the", "spec: Optional[pulumi.Input['LeaseSpecArgs']] = None): \"\"\" Lease defines a lease concept.", "object represents. Servers may infer this from the endpoint the", "time when the current holder of a lease has last", "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata \"\"\" return pulumi.get(self, \"metadata\") @metadata.setter def metadata(self,", "= None): \"\"\" Lease defines a lease concept. :param pulumi.Input[str]", "@property @pulumi.getter(name=\"acquireTime\") def acquire_time(self) -> Optional[pulumi.Input[str]]: \"\"\" acquireTime is a", "the lease. \"\"\" return pulumi.get(self, \"renew_time\") @renew_time.setter def renew_time(self, value:", "\"lease_transitions\", lease_transitions) if renew_time is not None: pulumi.set(__self__, \"renew_time\", renew_time)", "api_version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"api_version\", value) @property @pulumi.getter def kind(self)", "*, api_version: Optional[pulumi.Input[str]] = None, kind: Optional[pulumi.Input[str]] = None, metadata:", "Union, overload from ... import _utilities from ... import meta", "spec(self) -> Optional[pulumi.Input['LeaseSpecArgs']]: \"\"\" Specification of the Lease. More info:", "a lease has last updated the lease. \"\"\" if acquire_time", "current lease. \"\"\" return pulumi.get(self, \"holder_identity\") @holder_identity.setter def holder_identity(self, value:", "pulumigen. *** # *** Do not edit by hand unless", "LeaseSpecArgs: def __init__(__self__, *, acquire_time: Optional[pulumi.Input[str]] = None, holder_identity: Optional[pulumi.Input[str]]", "against time of last observed RenewTime. \"\"\" return pulumi.get(self, \"lease_duration_seconds\")", "convert recognized schemas to the latest internal value, and may", "pulumi.set(__self__, \"lease_transitions\", lease_transitions) if renew_time is not None: pulumi.set(__self__, \"renew_time\",", "return pulumi.get(self, \"spec\") @spec.setter def spec(self, value: Optional[pulumi.Input['LeaseSpecArgs']]): pulumi.set(self, \"spec\",", "this object represents. Servers may infer this from the endpoint", "@acquire_time.setter def acquire_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"acquire_time\", value) @property @pulumi.getter(name=\"holderIdentity\")", "info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds \"\"\" return pulumi.get(self, \"kind\") @kind.setter def kind(self, value:", "the number of transitions of a lease between holders. :param", "warnings import pulumi import pulumi.runtime from typing import Any, Mapping,", "measure against time of last observed RenewTime. \"\"\" return pulumi.get(self,", "last observed RenewTime. \"\"\" return pulumi.get(self, \"lease_duration_seconds\") @lease_duration_seconds.setter def lease_duration_seconds(self,", "number of transitions of a lease between holders. :param pulumi.Input[str]", "value) @property @pulumi.getter def kind(self) -> Optional[pulumi.Input[str]]: \"\"\" Kind is", "the client submits requests to. Cannot be updated. In CamelCase.", "if holder_identity is not None: pulumi.set(__self__, \"holder_identity\", holder_identity) if lease_duration_seconds", "@property @pulumi.getter def kind(self) -> Optional[pulumi.Input[str]]: \"\"\" Kind is a", "# coding=utf-8 # *** WARNING: this file was generated by", "import warnings import pulumi import pulumi.runtime from typing import Any,", "spec: Specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" if", "be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata:", "to wait to force acquire it. This is measure against", "*** import warnings import pulumi import pulumi.runtime from typing import", "by pulumigen. *** # *** Do not edit by hand", "@kind.setter def kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"kind\", value) @property @pulumi.getter", ":param pulumi.Input[str] holder_identity: holderIdentity contains the identity of the holder", "https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" return pulumi.get(self, \"spec\") @spec.setter def spec(self, value: Optional[pulumi.Input['LeaseSpecArgs']]):", "you know what you are doing! *** import warnings import", "= None, kind: Optional[pulumi.Input[str]] = None, metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] = None,", "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata: More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param", "lease_transitions: leaseTransitions is the number of transitions of a lease", "api_version is not None: pulumi.set(__self__, \"api_version\", 'coordination.k8s.io/v1') if kind is", "\"\"\" leaseDurationSeconds is a duration that candidates for a lease", "@property @pulumi.getter(name=\"renewTime\") def renew_time(self) -> Optional[pulumi.Input[str]]: \"\"\" renewTime is a", "holder_identity is not None: pulumi.set(__self__, \"holder_identity\", holder_identity) if lease_duration_seconds is", "should convert recognized schemas to the latest internal value, and", "reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources \"\"\" return pulumi.get(self, \"api_version\")", "of a lease between holders. :param pulumi.Input[str] renew_time: renewTime is", "endpoint the client submits requests to. Cannot be updated. In", "metadata: More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param pulumi.Input['LeaseSpecArgs'] spec: Specification of the", "leaseDurationSeconds is a duration that candidates for a lease need", "of a lease has last updated the lease. \"\"\" return", "lease was acquired. :param pulumi.Input[str] holder_identity: holderIdentity contains the identity", "lease has last updated the lease. \"\"\" return pulumi.get(self, \"renew_time\")", "a time when the current lease was acquired. \"\"\" return", "a lease need to wait to force acquire it. This", "lease_duration_seconds(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_duration_seconds\", value) @property @pulumi.getter(name=\"leaseTransitions\") def lease_transitions(self)", "return pulumi.get(self, \"lease_transitions\") @lease_transitions.setter def lease_transitions(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_transitions\",", "pulumi.set(__self__, \"kind\", 'Lease') if metadata is not None: pulumi.set(__self__, \"metadata\",", "value) @property @pulumi.getter def spec(self) -> Optional[pulumi.Input['LeaseSpecArgs']]: \"\"\" Specification of", "Specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" return pulumi.get(self,", "@pulumi.getter(name=\"leaseTransitions\") def lease_transitions(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseTransitions is the number", "metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] = None, spec: Optional[pulumi.Input['LeaseSpecArgs']] = None): \"\"\" Lease", "lease was acquired. \"\"\" return pulumi.get(self, \"acquire_time\") @acquire_time.setter def acquire_time(self,", "@lease_duration_seconds.setter def lease_duration_seconds(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_duration_seconds\", value) @property @pulumi.getter(name=\"leaseTransitions\")", "of last observed RenewTime. :param pulumi.Input[int] lease_transitions: leaseTransitions is the", "holder of a current lease. \"\"\" return pulumi.get(self, \"holder_identity\") @holder_identity.setter", "pulumi.Input[int] lease_transitions: leaseTransitions is the number of transitions of a", "@api_version.setter def api_version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"api_version\", value) @property @pulumi.getter", "def metadata(self) -> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]: \"\"\" More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata \"\"\" return", "... import meta as _meta __all__ = [ 'LeaseSpecArgs', 'LeaseArgs',", "metadata is not None: pulumi.set(__self__, \"metadata\", metadata) if spec is", "updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds \"\"\" return pulumi.get(self, \"kind\")", "lease_transitions(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseTransitions is the number of transitions", "value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param", "if api_version is not None: pulumi.set(__self__, \"api_version\", 'coordination.k8s.io/v1') if kind", "\"metadata\") @metadata.setter def metadata(self, value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]): pulumi.set(self, \"metadata\", value) @property", "pulumi.set(__self__, \"api_version\", 'coordination.k8s.io/v1') if kind is not None: pulumi.set(__self__, \"kind\",", "unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources \"\"\" return pulumi.get(self, \"api_version\") @api_version.setter", "if lease_duration_seconds is not None: pulumi.set(__self__, \"lease_duration_seconds\", lease_duration_seconds) if lease_transitions", "_utilities from ... import meta as _meta __all__ = [", "api_version(self) -> Optional[pulumi.Input[str]]: \"\"\" APIVersion defines the versioned schema of", "Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_transitions\", value) @property @pulumi.getter(name=\"renewTime\") def renew_time(self) -> Optional[pulumi.Input[str]]:", "between holders. :param pulumi.Input[str] renew_time: renewTime is a time when", "@property @pulumi.getter(name=\"leaseTransitions\") def lease_transitions(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseTransitions is the", "-> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]: \"\"\" More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata \"\"\" return pulumi.get(self, \"metadata\")", "Optional[pulumi.Input[str]] = None, lease_duration_seconds: Optional[pulumi.Input[int]] = None, lease_transitions: Optional[pulumi.Input[int]] =", "*** # *** Do not edit by hand unless you're", "a string value representing the REST resource this object represents.", "a Lease. :param pulumi.Input[str] acquire_time: acquireTime is a time when", "*** Do not edit by hand unless you're certain you", "if acquire_time is not None: pulumi.set(__self__, \"acquire_time\", acquire_time) if holder_identity", "def spec(self) -> Optional[pulumi.Input['LeaseSpecArgs']]: \"\"\" Specification of the Lease. More", "value: Optional[pulumi.Input[str]]): pulumi.set(self, \"acquire_time\", value) @property @pulumi.getter(name=\"holderIdentity\") def holder_identity(self) ->", "unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param pulumi.Input[str] kind: Kind is", "this file was generated by pulumigen. *** # *** Do", "the current lease was acquired. \"\"\" return pulumi.get(self, \"acquire_time\") @acquire_time.setter", ":param pulumi.Input[int] lease_transitions: leaseTransitions is the number of transitions of", "return pulumi.get(self, \"holder_identity\") @holder_identity.setter def holder_identity(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"holder_identity\",", "overload from ... import _utilities from ... import meta as", "\"\"\" return pulumi.get(self, \"spec\") @spec.setter def spec(self, value: Optional[pulumi.Input['LeaseSpecArgs']]): pulumi.set(self,", "file was generated by pulumigen. *** # *** Do not", "In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata: More info:", "a lease has last updated the lease. \"\"\" return pulumi.get(self,", "schemas to the latest internal value, and may reject unrecognized", "return pulumi.get(self, \"api_version\") @api_version.setter def api_version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"api_version\",", "pulumi.set(__self__, \"holder_identity\", holder_identity) if lease_duration_seconds is not None: pulumi.set(__self__, \"lease_duration_seconds\",", "\"\"\" holderIdentity contains the identity of the holder of a", ":param pulumi.Input[str] renew_time: renewTime is a time when the current", "represents. Servers may infer this from the endpoint the client", "value representing the REST resource this object represents. Servers may", "pulumi.set(self, \"metadata\", value) @property @pulumi.getter def spec(self) -> Optional[pulumi.Input['LeaseSpecArgs']]: \"\"\"", "holder_identity) if lease_duration_seconds is not None: pulumi.set(__self__, \"lease_duration_seconds\", lease_duration_seconds) if", "\"acquire_time\", value) @property @pulumi.getter(name=\"holderIdentity\") def holder_identity(self) -> Optional[pulumi.Input[str]]: \"\"\" holderIdentity", "spec is not None: pulumi.set(__self__, \"spec\", spec) @property @pulumi.getter(name=\"apiVersion\") def", "def metadata(self, value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]): pulumi.set(self, \"metadata\", value) @property @pulumi.getter def", "doing! *** import warnings import pulumi import pulumi.runtime from typing", "pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata: More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param pulumi.Input['LeaseSpecArgs'] spec: Specification of", "lease between holders. :param pulumi.Input[str] renew_time: renewTime is a time", "info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata \"\"\" return pulumi.get(self, \"metadata\") @metadata.setter def metadata(self, value:", "import meta as _meta __all__ = [ 'LeaseSpecArgs', 'LeaseArgs', ]", "resource this object represents. Servers may infer this from the", "\"\"\" return pulumi.get(self, \"kind\") @kind.setter def kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,", "from the endpoint the client submits requests to. Cannot be", "value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources \"\"\"", "a lease concept. :param pulumi.Input[str] api_version: APIVersion defines the versioned", "value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_transitions\", value) @property @pulumi.getter(name=\"renewTime\") def renew_time(self) ->", "Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" return pulumi.get(self, \"spec\") @spec.setter def", "not None: pulumi.set(__self__, \"renew_time\", renew_time) @property @pulumi.getter(name=\"acquireTime\") def acquire_time(self) ->", "it. This is measure against time of last observed RenewTime.", "pulumi.set(self, \"renew_time\", value) @pulumi.input_type class LeaseArgs: def __init__(__self__, *, api_version:", "is not None: pulumi.set(__self__, \"api_version\", 'coordination.k8s.io/v1') if kind is not", "\"lease_transitions\") @lease_transitions.setter def lease_transitions(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_transitions\", value) @property", "Optional[pulumi.Input[int]]: \"\"\" leaseTransitions is the number of transitions of a", "\"api_version\", 'coordination.k8s.io/v1') if kind is not None: pulumi.set(__self__, \"kind\", 'Lease')", "kind is not None: pulumi.set(__self__, \"kind\", 'Lease') if metadata is", "pulumi.get(self, \"lease_transitions\") @lease_transitions.setter def lease_transitions(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_transitions\", value)", "] @pulumi.input_type class LeaseSpecArgs: def __init__(__self__, *, acquire_time: Optional[pulumi.Input[str]] =", "pulumi.get(self, \"renew_time\") @renew_time.setter def renew_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"renew_time\", value)", "the holder of a current lease. \"\"\" return pulumi.get(self, \"holder_identity\")", "and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources \"\"\" return", "\"holder_identity\") @holder_identity.setter def holder_identity(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"holder_identity\", value) @property", "return pulumi.get(self, \"kind\") @kind.setter def kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"kind\",", "of the holder of a current lease. \"\"\" return pulumi.get(self,", "pulumi.get(self, \"spec\") @spec.setter def spec(self, value: Optional[pulumi.Input['LeaseSpecArgs']]): pulumi.set(self, \"spec\", value)", "generated by pulumigen. *** # *** Do not edit by", "lease_transitions(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_transitions\", value) @property @pulumi.getter(name=\"renewTime\") def renew_time(self)", "https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata: More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param pulumi.Input['LeaseSpecArgs'] spec:", "-> Optional[pulumi.Input[str]]: \"\"\" APIVersion defines the versioned schema of this", "holder of a current lease. :param pulumi.Input[int] lease_duration_seconds: leaseDurationSeconds is", "is measure against time of last observed RenewTime. :param pulumi.Input[int]", "pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload", "pulumi.Input[str] acquire_time: acquireTime is a time when the current lease", "was acquired. \"\"\" return pulumi.get(self, \"acquire_time\") @acquire_time.setter def acquire_time(self, value:", "acquired. :param pulumi.Input[str] holder_identity: holderIdentity contains the identity of the", "value) @property @pulumi.getter(name=\"leaseDurationSeconds\") def lease_duration_seconds(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseDurationSeconds is", "value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_duration_seconds\", value) @property @pulumi.getter(name=\"leaseTransitions\") def lease_transitions(self) ->", "to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param", "last updated the lease. \"\"\" return pulumi.get(self, \"renew_time\") @renew_time.setter def", "is not None: pulumi.set(__self__, \"metadata\", metadata) if spec is not", "this from the endpoint the client submits requests to. Cannot", "of the holder of a current lease. :param pulumi.Input[int] lease_duration_seconds:", "if metadata is not None: pulumi.set(__self__, \"metadata\", metadata) if spec", "last updated the lease. \"\"\" if acquire_time is not None:", "defines the versioned schema of this representation of an object.", "is a time when the current holder of a lease", "None: pulumi.set(__self__, \"kind\", 'Lease') if metadata is not None: pulumi.set(__self__,", "is a time when the current lease was acquired. \"\"\"", "@pulumi.input_type class LeaseArgs: def __init__(__self__, *, api_version: Optional[pulumi.Input[str]] = None,", "not None: pulumi.set(__self__, \"lease_transitions\", lease_transitions) if renew_time is not None:", "lease concept. :param pulumi.Input[str] api_version: APIVersion defines the versioned schema", "pulumi.Input[str] holder_identity: holderIdentity contains the identity of the holder of", "info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param pulumi.Input[str] kind: Kind is a string value", "infer this from the endpoint the client submits requests to.", "\"\"\" APIVersion defines the versioned schema of this representation of", "Kind is a string value representing the REST resource this", "Optional[pulumi.Input[str]]: \"\"\" Kind is a string value representing the REST", "None, metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] = None, spec: Optional[pulumi.Input['LeaseSpecArgs']] = None): \"\"\"", "https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param pulumi.Input['LeaseSpecArgs'] spec: Specification of the Lease. More info:", "Mapping, Optional, Sequence, Union, overload from ... import _utilities from", "a current lease. \"\"\" return pulumi.get(self, \"holder_identity\") @holder_identity.setter def holder_identity(self,", "\"renew_time\") @renew_time.setter def renew_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"renew_time\", value) @pulumi.input_type", "None: pulumi.set(__self__, \"spec\", spec) @property @pulumi.getter(name=\"apiVersion\") def api_version(self) -> Optional[pulumi.Input[str]]:", "representation of an object. Servers should convert recognized schemas to", "-> Optional[pulumi.Input[str]]: \"\"\" renewTime is a time when the current", "of a lease has last updated the lease. \"\"\" if", "from typing import Any, Mapping, Optional, Sequence, Union, overload from", "a duration that candidates for a lease need to wait", "transitions of a lease between holders. :param pulumi.Input[str] renew_time: renewTime", "Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] = None, spec: Optional[pulumi.Input['LeaseSpecArgs']] = None): \"\"\" Lease defines", "RenewTime. :param pulumi.Input[int] lease_transitions: leaseTransitions is the number of transitions", "info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata: More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param pulumi.Input['LeaseSpecArgs']", "not None: pulumi.set(__self__, \"acquire_time\", acquire_time) if holder_identity is not None:", "requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", "is not None: pulumi.set(__self__, \"lease_transitions\", lease_transitions) if renew_time is not", "a time when the current holder of a lease has", "pulumi.get(self, \"kind\") @kind.setter def kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"kind\", value)", "import Any, Mapping, Optional, Sequence, Union, overload from ... import", "know what you are doing! *** import warnings import pulumi", "= None, holder_identity: Optional[pulumi.Input[str]] = None, lease_duration_seconds: Optional[pulumi.Input[int]] = None,", "from ... import _utilities from ... import meta as _meta", "@metadata.setter def metadata(self, value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]): pulumi.set(self, \"metadata\", value) @property @pulumi.getter", "and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param pulumi.Input[str]", "the current holder of a lease has last updated the", "# *** WARNING: this file was generated by pulumigen. ***", "certain you know what you are doing! *** import warnings", "was generated by pulumigen. *** # *** Do not edit", "between holders. \"\"\" return pulumi.get(self, \"lease_transitions\") @lease_transitions.setter def lease_transitions(self, value:", "of this representation of an object. Servers should convert recognized", "= None, lease_duration_seconds: Optional[pulumi.Input[int]] = None, lease_transitions: Optional[pulumi.Input[int]] = None,", "Sequence, Union, overload from ... import _utilities from ... import", "def holder_identity(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"holder_identity\", value) @property @pulumi.getter(name=\"leaseDurationSeconds\") def", "wait to force acquire it. This is measure against time", "pulumi.get(self, \"acquire_time\") @acquire_time.setter def acquire_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"acquire_time\", value)", "pulumi.Input['LeaseSpecArgs'] spec: Specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\"", "Optional[pulumi.Input[int]] = None, lease_transitions: Optional[pulumi.Input[int]] = None, renew_time: Optional[pulumi.Input[str]] =", "you're certain you know what you are doing! *** import", "\"lease_duration_seconds\", lease_duration_seconds) if lease_transitions is not None: pulumi.set(__self__, \"lease_transitions\", lease_transitions)", "\"lease_transitions\", value) @property @pulumi.getter(name=\"renewTime\") def renew_time(self) -> Optional[pulumi.Input[str]]: \"\"\" renewTime", "api_version: Optional[pulumi.Input[str]] = None, kind: Optional[pulumi.Input[str]] = None, metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]", "return pulumi.get(self, \"lease_duration_seconds\") @lease_duration_seconds.setter def lease_duration_seconds(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_duration_seconds\",", "versioned schema of this representation of an object. Servers should", "metadata(self) -> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]: \"\"\" More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata \"\"\" return pulumi.get(self,", "metadata(self, value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]): pulumi.set(self, \"metadata\", value) @property @pulumi.getter def spec(self)", "not edit by hand unless you're certain you know what", "holderIdentity contains the identity of the holder of a current", "renew_time: renewTime is a time when the current holder of", "lease. \"\"\" if acquire_time is not None: pulumi.set(__self__, \"acquire_time\", acquire_time)", "\"holder_identity\", value) @property @pulumi.getter(name=\"leaseDurationSeconds\") def lease_duration_seconds(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseDurationSeconds", "pulumi.set(self, \"holder_identity\", value) @property @pulumi.getter(name=\"leaseDurationSeconds\") def lease_duration_seconds(self) -> Optional[pulumi.Input[int]]: \"\"\"", "value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]): pulumi.set(self, \"metadata\", value) @property @pulumi.getter def spec(self) ->", "the holder of a current lease. :param pulumi.Input[int] lease_duration_seconds: leaseDurationSeconds", "pulumi.get(self, \"lease_duration_seconds\") @lease_duration_seconds.setter def lease_duration_seconds(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_duration_seconds\", value)", "the versioned schema of this representation of an object. Servers", "not None: pulumi.set(__self__, \"api_version\", 'coordination.k8s.io/v1') if kind is not None:", "Optional[pulumi.Input['LeaseSpecArgs']] = None): \"\"\" Lease defines a lease concept. :param", "-> Optional[pulumi.Input[str]]: \"\"\" acquireTime is a time when the current", "\"\"\" return pulumi.get(self, \"metadata\") @metadata.setter def metadata(self, value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]): pulumi.set(self,", "\"\"\" return pulumi.get(self, \"holder_identity\") @holder_identity.setter def holder_identity(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,", "latest internal value, and may reject unrecognized values. More info:", "the latest internal value, and may reject unrecognized values. More", "lease_transitions) if renew_time is not None: pulumi.set(__self__, \"renew_time\", renew_time) @property", "when the current lease was acquired. :param pulumi.Input[str] holder_identity: holderIdentity", "if kind is not None: pulumi.set(__self__, \"kind\", 'Lease') if metadata", "the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" if api_version is not", "Optional[pulumi.Input[str]] = None, holder_identity: Optional[pulumi.Input[str]] = None, lease_duration_seconds: Optional[pulumi.Input[int]] =", "is not None: pulumi.set(__self__, \"holder_identity\", holder_identity) if lease_duration_seconds is not", "@renew_time.setter def renew_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"renew_time\", value) @pulumi.input_type class", "the REST resource this object represents. Servers may infer this", "by hand unless you're certain you know what you are", "lease_duration_seconds(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseDurationSeconds is a duration that candidates", "as _meta __all__ = [ 'LeaseSpecArgs', 'LeaseArgs', ] @pulumi.input_type class", "client submits requests to. Cannot be updated. In CamelCase. More", "def kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"kind\", value) @property @pulumi.getter def", "*** WARNING: this file was generated by pulumigen. *** #", "@pulumi.getter(name=\"apiVersion\") def api_version(self) -> Optional[pulumi.Input[str]]: \"\"\" APIVersion defines the versioned", "value: Optional[pulumi.Input[str]]): pulumi.set(self, \"kind\", value) @property @pulumi.getter def metadata(self) ->", "Optional[pulumi.Input[str]]): pulumi.set(self, \"api_version\", value) @property @pulumi.getter def kind(self) -> Optional[pulumi.Input[str]]:", "is not None: pulumi.set(__self__, \"renew_time\", renew_time) @property @pulumi.getter(name=\"acquireTime\") def acquire_time(self)", "def renew_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"renew_time\", value) @pulumi.input_type class LeaseArgs:", "pulumi.set(self, \"acquire_time\", value) @property @pulumi.getter(name=\"holderIdentity\") def holder_identity(self) -> Optional[pulumi.Input[str]]: \"\"\"", "is measure against time of last observed RenewTime. \"\"\" return", "def api_version(self) -> Optional[pulumi.Input[str]]: \"\"\" APIVersion defines the versioned schema", "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources \"\"\" return pulumi.get(self, \"api_version\") @api_version.setter def api_version(self,", "you are doing! *** import warnings import pulumi import pulumi.runtime", "is not None: pulumi.set(__self__, \"kind\", 'Lease') if metadata is not", "pulumi.set(self, \"kind\", value) @property @pulumi.getter def metadata(self) -> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]: \"\"\"", "__init__(__self__, *, api_version: Optional[pulumi.Input[str]] = None, kind: Optional[pulumi.Input[str]] = None,", "\"metadata\", value) @property @pulumi.getter def spec(self) -> Optional[pulumi.Input['LeaseSpecArgs']]: \"\"\" Specification", "info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param pulumi.Input['LeaseSpecArgs'] spec: Specification of the Lease. More", ":param pulumi.Input['LeaseSpecArgs'] spec: Specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", "lease_transitions is not None: pulumi.set(__self__, \"lease_transitions\", lease_transitions) if renew_time is", "pulumi.set(__self__, \"renew_time\", renew_time) @property @pulumi.getter(name=\"acquireTime\") def acquire_time(self) -> Optional[pulumi.Input[str]]: \"\"\"", "acquire_time: acquireTime is a time when the current lease was", "\"\"\" LeaseSpec is a specification of a Lease. :param pulumi.Input[str]", "updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata: More", "lease between holders. \"\"\" return pulumi.get(self, \"lease_transitions\") @lease_transitions.setter def lease_transitions(self,", "\"\"\" More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata \"\"\" return pulumi.get(self, \"metadata\") @metadata.setter def", "pulumi.set(self, \"lease_transitions\", value) @property @pulumi.getter(name=\"renewTime\") def renew_time(self) -> Optional[pulumi.Input[str]]: \"\"\"", "may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources \"\"\" return pulumi.get(self,", "Lease defines a lease concept. :param pulumi.Input[str] api_version: APIVersion defines", ":param pulumi.Input[str] api_version: APIVersion defines the versioned schema of this", "info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" return pulumi.get(self, \"spec\") @spec.setter def spec(self, value:", "acquire_time(self) -> Optional[pulumi.Input[str]]: \"\"\" acquireTime is a time when the", "\"\"\" if acquire_time is not None: pulumi.set(__self__, \"acquire_time\", acquire_time) if", "Optional[pulumi.Input['LeaseSpecArgs']]: \"\"\" Specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\"", "-> Optional[pulumi.Input[int]]: \"\"\" leaseTransitions is the number of transitions of", "current lease was acquired. \"\"\" return pulumi.get(self, \"acquire_time\") @acquire_time.setter def", "= [ 'LeaseSpecArgs', 'LeaseArgs', ] @pulumi.input_type class LeaseSpecArgs: def __init__(__self__,", "value) @property @pulumi.getter(name=\"renewTime\") def renew_time(self) -> Optional[pulumi.Input[str]]: \"\"\" renewTime is", "against time of last observed RenewTime. :param pulumi.Input[int] lease_transitions: leaseTransitions", "\"renew_time\", renew_time) @property @pulumi.getter(name=\"acquireTime\") def acquire_time(self) -> Optional[pulumi.Input[str]]: \"\"\" acquireTime", "acquire_time: Optional[pulumi.Input[str]] = None, holder_identity: Optional[pulumi.Input[str]] = None, lease_duration_seconds: Optional[pulumi.Input[int]]", "when the current lease was acquired. \"\"\" return pulumi.get(self, \"acquire_time\")", "pulumi.set(self, \"lease_duration_seconds\", value) @property @pulumi.getter(name=\"leaseTransitions\") def lease_transitions(self) -> Optional[pulumi.Input[int]]: \"\"\"", "\"acquire_time\") @acquire_time.setter def acquire_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"acquire_time\", value) @property", "[ 'LeaseSpecArgs', 'LeaseArgs', ] @pulumi.input_type class LeaseSpecArgs: def __init__(__self__, *,", "observed RenewTime. \"\"\" return pulumi.get(self, \"lease_duration_seconds\") @lease_duration_seconds.setter def lease_duration_seconds(self, value:", "import pulumi import pulumi.runtime from typing import Any, Mapping, Optional,", "= None, lease_transitions: Optional[pulumi.Input[int]] = None, renew_time: Optional[pulumi.Input[str]] = None):", "holder of a lease has last updated the lease. \"\"\"", "def lease_duration_seconds(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_duration_seconds\", value) @property @pulumi.getter(name=\"leaseTransitions\") def", "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" if api_version is not None: pulumi.set(__self__,", "def acquire_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"acquire_time\", value) @property @pulumi.getter(name=\"holderIdentity\") def", "was acquired. :param pulumi.Input[str] holder_identity: holderIdentity contains the identity of", "info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources \"\"\" return pulumi.get(self, \"api_version\") @api_version.setter def api_version(self, value:", "def acquire_time(self) -> Optional[pulumi.Input[str]]: \"\"\" acquireTime is a time when", "the number of transitions of a lease between holders. \"\"\"", "import _utilities from ... import meta as _meta __all__ =", "def lease_duration_seconds(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseDurationSeconds is a duration that", "coding=utf-8 # *** WARNING: this file was generated by pulumigen.", "lease_duration_seconds) if lease_transitions is not None: pulumi.set(__self__, \"lease_transitions\", lease_transitions) if", "string value representing the REST resource this object represents. Servers", "None: pulumi.set(__self__, \"renew_time\", renew_time) @property @pulumi.getter(name=\"acquireTime\") def acquire_time(self) -> Optional[pulumi.Input[str]]:", "not None: pulumi.set(__self__, \"spec\", spec) @property @pulumi.getter(name=\"apiVersion\") def api_version(self) ->", "pulumi.set(__self__, \"lease_duration_seconds\", lease_duration_seconds) if lease_transitions is not None: pulumi.set(__self__, \"lease_transitions\",", "duration that candidates for a lease need to wait to", "holders. :param pulumi.Input[str] renew_time: renewTime is a time when the", "acquire_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"acquire_time\", value) @property @pulumi.getter(name=\"holderIdentity\") def holder_identity(self)", "\"\"\" Specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" return", "the identity of the holder of a current lease. :param", "https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata \"\"\" return pulumi.get(self, \"metadata\") @metadata.setter def metadata(self, value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]):", "last observed RenewTime. :param pulumi.Input[int] lease_transitions: leaseTransitions is the number", "value) @property @pulumi.getter(name=\"holderIdentity\") def holder_identity(self) -> Optional[pulumi.Input[str]]: \"\"\" holderIdentity contains", "a specification of a Lease. :param pulumi.Input[str] acquire_time: acquireTime is", "Optional[pulumi.Input[str]]): pulumi.set(self, \"acquire_time\", value) @property @pulumi.getter(name=\"holderIdentity\") def holder_identity(self) -> Optional[pulumi.Input[str]]:", "... import _utilities from ... import meta as _meta __all__", "Servers may infer this from the endpoint the client submits", "acquireTime is a time when the current lease was acquired.", "\"\"\" return pulumi.get(self, \"lease_duration_seconds\") @lease_duration_seconds.setter def lease_duration_seconds(self, value: Optional[pulumi.Input[int]]): pulumi.set(self,", "@pulumi.getter(name=\"holderIdentity\") def holder_identity(self) -> Optional[pulumi.Input[str]]: \"\"\" holderIdentity contains the identity", "observed RenewTime. :param pulumi.Input[int] lease_transitions: leaseTransitions is the number of", "measure against time of last observed RenewTime. :param pulumi.Input[int] lease_transitions:", "acquire_time) if holder_identity is not None: pulumi.set(__self__, \"holder_identity\", holder_identity) if", "def lease_transitions(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_transitions\", value) @property @pulumi.getter(name=\"renewTime\") def", "a lease between holders. :param pulumi.Input[str] renew_time: renewTime is a", "Optional, Sequence, Union, overload from ... import _utilities from ...", "\"\"\" return pulumi.get(self, \"renew_time\") @renew_time.setter def renew_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,", "Optional[pulumi.Input[str]]: \"\"\" acquireTime is a time when the current lease", "of transitions of a lease between holders. :param pulumi.Input[str] renew_time:", "\"api_version\") @api_version.setter def api_version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"api_version\", value) @property", "Optional[pulumi.Input[str]]): pulumi.set(self, \"holder_identity\", value) @property @pulumi.getter(name=\"leaseDurationSeconds\") def lease_duration_seconds(self) -> Optional[pulumi.Input[int]]:", "This is measure against time of last observed RenewTime. \"\"\"", "of transitions of a lease between holders. \"\"\" return pulumi.get(self,", "is not None: pulumi.set(__self__, \"lease_duration_seconds\", lease_duration_seconds) if lease_transitions is not", "\"\"\" renewTime is a time when the current holder of", "the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" return pulumi.get(self, \"spec\") @spec.setter", "number of transitions of a lease between holders. \"\"\" return", "info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" if api_version is not None: pulumi.set(__self__, \"api_version\",", "None: pulumi.set(__self__, \"api_version\", 'coordination.k8s.io/v1') if kind is not None: pulumi.set(__self__,", "a lease between holders. \"\"\" return pulumi.get(self, \"lease_transitions\") @lease_transitions.setter def", "holders. \"\"\" return pulumi.get(self, \"lease_transitions\") @lease_transitions.setter def lease_transitions(self, value: Optional[pulumi.Input[int]]):", "CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds \"\"\" return pulumi.get(self, \"kind\") @kind.setter def", "are doing! *** import warnings import pulumi import pulumi.runtime from", "\"lease_duration_seconds\") @lease_duration_seconds.setter def lease_duration_seconds(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, \"lease_duration_seconds\", value) @property", "time when the current lease was acquired. :param pulumi.Input[str] holder_identity:", "'coordination.k8s.io/v1') if kind is not None: pulumi.set(__self__, \"kind\", 'Lease') if", "-> Optional[pulumi.Input[int]]: \"\"\" leaseDurationSeconds is a duration that candidates for", "renew_time(self) -> Optional[pulumi.Input[str]]: \"\"\" renewTime is a time when the", "None, lease_transitions: Optional[pulumi.Input[int]] = None, renew_time: Optional[pulumi.Input[str]] = None): \"\"\"", "kind: Kind is a string value representing the REST resource", "Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds \"\"\" return", "@pulumi.getter(name=\"leaseDurationSeconds\") def lease_duration_seconds(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseDurationSeconds is a duration", "edit by hand unless you're certain you know what you", "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param pulumi.Input[str] kind: Kind is a string", "APIVersion defines the versioned schema of this representation of an", "\"spec\", spec) @property @pulumi.getter(name=\"apiVersion\") def api_version(self) -> Optional[pulumi.Input[str]]: \"\"\" APIVersion", "is the number of transitions of a lease between holders.", "of last observed RenewTime. \"\"\" return pulumi.get(self, \"lease_duration_seconds\") @lease_duration_seconds.setter def", "transitions of a lease between holders. \"\"\" return pulumi.get(self, \"lease_transitions\")", "current lease. :param pulumi.Input[int] lease_duration_seconds: leaseDurationSeconds is a duration that", "this representation of an object. Servers should convert recognized schemas", "meta as _meta __all__ = [ 'LeaseSpecArgs', 'LeaseArgs', ] @pulumi.input_type", "\"holder_identity\", holder_identity) if lease_duration_seconds is not None: pulumi.set(__self__, \"lease_duration_seconds\", lease_duration_seconds)", "Do not edit by hand unless you're certain you know", "Lease. :param pulumi.Input[str] acquire_time: acquireTime is a time when the", "pulumi.set(__self__, \"acquire_time\", acquire_time) if holder_identity is not None: pulumi.set(__self__, \"holder_identity\",", "@pulumi.getter def spec(self) -> Optional[pulumi.Input['LeaseSpecArgs']]: \"\"\" Specification of the Lease.", "None, renew_time: Optional[pulumi.Input[str]] = None): \"\"\" LeaseSpec is a specification", "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds \"\"\" return pulumi.get(self, \"kind\") @kind.setter def kind(self,", "is a duration that candidates for a lease need to", "None, spec: Optional[pulumi.Input['LeaseSpecArgs']] = None): \"\"\" Lease defines a lease", "is a specification of a Lease. :param pulumi.Input[str] acquire_time: acquireTime", "of an object. Servers should convert recognized schemas to the", "not None: pulumi.set(__self__, \"holder_identity\", holder_identity) if lease_duration_seconds is not None:", "RenewTime. \"\"\" return pulumi.get(self, \"lease_duration_seconds\") @lease_duration_seconds.setter def lease_duration_seconds(self, value: Optional[pulumi.Input[int]]):", "lease_duration_seconds: leaseDurationSeconds is a duration that candidates for a lease", "# *** Do not edit by hand unless you're certain", "typing import Any, Mapping, Optional, Sequence, Union, overload from ...", "of a lease between holders. \"\"\" return pulumi.get(self, \"lease_transitions\") @lease_transitions.setter", "candidates for a lease need to wait to force acquire", "@holder_identity.setter def holder_identity(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"holder_identity\", value) @property @pulumi.getter(name=\"leaseDurationSeconds\")", "\"\"\" leaseTransitions is the number of transitions of a lease", "representing the REST resource this object represents. Servers may infer", "-> Optional[pulumi.Input[str]]: \"\"\" holderIdentity contains the identity of the holder", "lease. \"\"\" return pulumi.get(self, \"renew_time\") @renew_time.setter def renew_time(self, value: Optional[pulumi.Input[str]]):", "time of last observed RenewTime. :param pulumi.Input[int] lease_transitions: leaseTransitions is", "renew_time is not None: pulumi.set(__self__, \"renew_time\", renew_time) @property @pulumi.getter(name=\"acquireTime\") def", "\"kind\", 'Lease') if metadata is not None: pulumi.set(__self__, \"metadata\", metadata)", "lease_transitions: Optional[pulumi.Input[int]] = None, renew_time: Optional[pulumi.Input[str]] = None): \"\"\" LeaseSpec", "time of last observed RenewTime. \"\"\" return pulumi.get(self, \"lease_duration_seconds\") @lease_duration_seconds.setter", "recognized schemas to the latest internal value, and may reject", "if lease_transitions is not None: pulumi.set(__self__, \"lease_transitions\", lease_transitions) if renew_time", "def kind(self) -> Optional[pulumi.Input[str]]: \"\"\" Kind is a string value", "def __init__(__self__, *, acquire_time: Optional[pulumi.Input[str]] = None, holder_identity: Optional[pulumi.Input[str]] =", "renewTime is a time when the current holder of a", "def __init__(__self__, *, api_version: Optional[pulumi.Input[str]] = None, kind: Optional[pulumi.Input[str]] =", "\"\"\" return pulumi.get(self, \"lease_transitions\") @lease_transitions.setter def lease_transitions(self, value: Optional[pulumi.Input[int]]): pulumi.set(self,", "kind: Optional[pulumi.Input[str]] = None, metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] = None, spec: Optional[pulumi.Input['LeaseSpecArgs']]", "a time when the current lease was acquired. :param pulumi.Input[str]", "LeaseArgs: def __init__(__self__, *, api_version: Optional[pulumi.Input[str]] = None, kind: Optional[pulumi.Input[str]]", "not None: pulumi.set(__self__, \"kind\", 'Lease') if metadata is not None:", "Optional[pulumi.Input[int]]: \"\"\" leaseDurationSeconds is a duration that candidates for a", "force acquire it. This is measure against time of last", "Optional[pulumi.Input[str]] = None): \"\"\" LeaseSpec is a specification of a", "= None): \"\"\" LeaseSpec is a specification of a Lease.", "= None, metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] = None, spec: Optional[pulumi.Input['LeaseSpecArgs']] = None):", "lease. \"\"\" return pulumi.get(self, \"holder_identity\") @holder_identity.setter def holder_identity(self, value: Optional[pulumi.Input[str]]):", "https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status \"\"\" if api_version is not None: pulumi.set(__self__, \"api_version\", 'coordination.k8s.io/v1')", "to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds \"\"\"", "pulumi.set(__self__, \"spec\", spec) @property @pulumi.getter(name=\"apiVersion\") def api_version(self) -> Optional[pulumi.Input[str]]: \"\"\"", "-> Optional[pulumi.Input[str]]: \"\"\" Kind is a string value representing the", "_meta __all__ = [ 'LeaseSpecArgs', 'LeaseArgs', ] @pulumi.input_type class LeaseSpecArgs:", "None, kind: Optional[pulumi.Input[str]] = None, metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] = None, spec:", "is a string value representing the REST resource this object", "lease need to wait to force acquire it. This is", "\"kind\") @kind.setter def kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"kind\", value) @property", "\"\"\" return pulumi.get(self, \"acquire_time\") @acquire_time.setter def acquire_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,", "pulumi.get(self, \"holder_identity\") @holder_identity.setter def holder_identity(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"holder_identity\", value)", "values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param pulumi.Input[str] kind: Kind is a", "specification of a Lease. :param pulumi.Input[str] acquire_time: acquireTime is a", "lease. :param pulumi.Input[int] lease_duration_seconds: leaseDurationSeconds is a duration that candidates", "Optional[pulumi.Input[str]]: \"\"\" APIVersion defines the versioned schema of this representation", "None: pulumi.set(__self__, \"acquire_time\", acquire_time) if holder_identity is not None: pulumi.set(__self__,", "may infer this from the endpoint the client submits requests", "Optional[pulumi.Input[str]] = None, metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] = None, spec: Optional[pulumi.Input['LeaseSpecArgs']] =", "LeaseSpec is a specification of a Lease. :param pulumi.Input[str] acquire_time:", "\"acquire_time\", acquire_time) if holder_identity is not None: pulumi.set(__self__, \"holder_identity\", holder_identity)", "https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param pulumi.Input[str] kind: Kind is a string value representing", "= None, renew_time: Optional[pulumi.Input[str]] = None): \"\"\" LeaseSpec is a", "when the current holder of a lease has last updated", "def holder_identity(self) -> Optional[pulumi.Input[str]]: \"\"\" holderIdentity contains the identity of", "holder_identity: holderIdentity contains the identity of the holder of a", "Optional[pulumi.Input[str]]: \"\"\" holderIdentity contains the identity of the holder of", "pulumi.Input[str] renew_time: renewTime is a time when the current holder", "= None, spec: Optional[pulumi.Input['LeaseSpecArgs']] = None): \"\"\" Lease defines a", "\"\"\" acquireTime is a time when the current lease was", "pulumi.get(self, \"api_version\") @api_version.setter def api_version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"api_version\", value)", "value) @property @pulumi.getter(name=\"leaseTransitions\") def lease_transitions(self) -> Optional[pulumi.Input[int]]: \"\"\" leaseTransitions is", "to the latest internal value, and may reject unrecognized values.", "WARNING: this file was generated by pulumigen. *** # ***", "metadata) if spec is not None: pulumi.set(__self__, \"spec\", spec) @property" ]
[ "thisFont.selectedFontMaster.id # active master listOfSelectedLayers = thisFont.selectedLayers # active layers", "advance = 0.0 for thisComponent in thisLayer.components: thisComponent.position = NSPoint(", "advance += thisComponent.component.layers[thisFontMasterID].width thisLayer.width = advance thisFont.disableUpdateInterface() # suppresses UI", "Glyphs.font # frontmost font thisFontMaster = thisFont.selectedFontMaster # active master", "glyphs that cannot be auto-aligned. \"\"\" import GlyphsApp thisFont =", "0.0 for thisComponent in thisLayer.components: thisComponent.position = NSPoint( advance, 0.0", "advance thisFont.disableUpdateInterface() # suppresses UI updates in Font View for", "listOfSelectedLayers = thisFont.selectedLayers # active layers of selected glyphs def", "# active master listOfSelectedLayers = thisFont.selectedLayers # active layers of", "undo grouping thisFont.enableUpdateInterface() # re-enables UI updates in Font View", "\"Aligning components in:\", thisGlyph.name thisGlyph.beginUndo() # begin undo grouping process(", ") advance += thisComponent.component.layers[thisFontMasterID].width thisLayer.width = advance thisFont.disableUpdateInterface() # suppresses", "Components # -*- coding: utf-8 -*- __doc__=\"\"\" Fakes auto-alignment in", "cannot be auto-aligned. \"\"\" import GlyphsApp thisFont = Glyphs.font #", "thisFontMaster = thisFont.selectedFontMaster # active master thisFontMasterID = thisFont.selectedFontMaster.id #", "auto-alignment in glyphs that cannot be auto-aligned. \"\"\" import GlyphsApp", "thisLayer in listOfSelectedLayers: thisGlyph = thisLayer.parent print \"Aligning components in:\",", "process( thisLayer ): advance = 0.0 for thisComponent in thisLayer.components:", "View for thisLayer in listOfSelectedLayers: thisGlyph = thisLayer.parent print \"Aligning", "thisGlyph.endUndo() # end undo grouping thisFont.enableUpdateInterface() # re-enables UI updates", ") thisGlyph.endUndo() # end undo grouping thisFont.enableUpdateInterface() # re-enables UI", "thisLayer ) thisGlyph.endUndo() # end undo grouping thisFont.enableUpdateInterface() # re-enables", "thisFontMasterID = thisFont.selectedFontMaster.id # active master listOfSelectedLayers = thisFont.selectedLayers #", "grouping process( thisLayer ) thisGlyph.endUndo() # end undo grouping thisFont.enableUpdateInterface()", "in thisLayer.components: thisComponent.position = NSPoint( advance, 0.0 ) advance +=", "in:\", thisGlyph.name thisGlyph.beginUndo() # begin undo grouping process( thisLayer )", "= thisFont.selectedFontMaster # active master thisFontMasterID = thisFont.selectedFontMaster.id # active", "= thisFont.selectedLayers # active layers of selected glyphs def process(", "in glyphs that cannot be auto-aligned. \"\"\" import GlyphsApp thisFont", "master thisFontMasterID = thisFont.selectedFontMaster.id # active master listOfSelectedLayers = thisFont.selectedLayers", "undo grouping process( thisLayer ) thisGlyph.endUndo() # end undo grouping", "selected glyphs def process( thisLayer ): advance = 0.0 for", "= 0.0 for thisComponent in thisLayer.components: thisComponent.position = NSPoint( advance,", "#MenuTitle: Align All Components # -*- coding: utf-8 -*- __doc__=\"\"\"", "active master listOfSelectedLayers = thisFont.selectedLayers # active layers of selected", "= Glyphs.font # frontmost font thisFontMaster = thisFont.selectedFontMaster # active", "-*- coding: utf-8 -*- __doc__=\"\"\" Fakes auto-alignment in glyphs that", "import GlyphsApp thisFont = Glyphs.font # frontmost font thisFontMaster =", "GlyphsApp thisFont = Glyphs.font # frontmost font thisFontMaster = thisFont.selectedFontMaster", "-*- __doc__=\"\"\" Fakes auto-alignment in glyphs that cannot be auto-aligned.", "# active layers of selected glyphs def process( thisLayer ):", "in listOfSelectedLayers: thisGlyph = thisLayer.parent print \"Aligning components in:\", thisGlyph.name", "= advance thisFont.disableUpdateInterface() # suppresses UI updates in Font View", "thisComponent.component.layers[thisFontMasterID].width thisLayer.width = advance thisFont.disableUpdateInterface() # suppresses UI updates in", "# end undo grouping thisFont.enableUpdateInterface() # re-enables UI updates in", "end undo grouping thisFont.enableUpdateInterface() # re-enables UI updates in Font", "UI updates in Font View for thisLayer in listOfSelectedLayers: thisGlyph", "Font View for thisLayer in listOfSelectedLayers: thisGlyph = thisLayer.parent print", "thisComponent.position = NSPoint( advance, 0.0 ) advance += thisComponent.component.layers[thisFontMasterID].width thisLayer.width", "# suppresses UI updates in Font View for thisLayer in", "suppresses UI updates in Font View for thisLayer in listOfSelectedLayers:", "# begin undo grouping process( thisLayer ) thisGlyph.endUndo() # end", "thisGlyph.beginUndo() # begin undo grouping process( thisLayer ) thisGlyph.endUndo() #", "\"\"\" import GlyphsApp thisFont = Glyphs.font # frontmost font thisFontMaster", "thisFont.selectedLayers # active layers of selected glyphs def process( thisLayer", "All Components.py #MenuTitle: Align All Components # -*- coding: utf-8", "All Components # -*- coding: utf-8 -*- __doc__=\"\"\" Fakes auto-alignment", "= thisLayer.parent print \"Aligning components in:\", thisGlyph.name thisGlyph.beginUndo() # begin", "= NSPoint( advance, 0.0 ) advance += thisComponent.component.layers[thisFontMasterID].width thisLayer.width =", "in Font View for thisLayer in listOfSelectedLayers: thisGlyph = thisLayer.parent", "# frontmost font thisFontMaster = thisFont.selectedFontMaster # active master thisFontMasterID", "thisComponent in thisLayer.components: thisComponent.position = NSPoint( advance, 0.0 ) advance", "auto-aligned. \"\"\" import GlyphsApp thisFont = Glyphs.font # frontmost font", "thisFont = Glyphs.font # frontmost font thisFontMaster = thisFont.selectedFontMaster #", "): advance = 0.0 for thisComponent in thisLayer.components: thisComponent.position =", "components in:\", thisGlyph.name thisGlyph.beginUndo() # begin undo grouping process( thisLayer", "be auto-aligned. \"\"\" import GlyphsApp thisFont = Glyphs.font # frontmost", "updates in Font View for thisLayer in listOfSelectedLayers: thisGlyph =", "NSPoint( advance, 0.0 ) advance += thisComponent.component.layers[thisFontMasterID].width thisLayer.width = advance", "thisLayer.width = advance thisFont.disableUpdateInterface() # suppresses UI updates in Font", "thisGlyph = thisLayer.parent print \"Aligning components in:\", thisGlyph.name thisGlyph.beginUndo() #", "advance, 0.0 ) advance += thisComponent.component.layers[thisFontMasterID].width thisLayer.width = advance thisFont.disableUpdateInterface()", "thisLayer.parent print \"Aligning components in:\", thisGlyph.name thisGlyph.beginUndo() # begin undo", "utf-8 -*- __doc__=\"\"\" Fakes auto-alignment in glyphs that cannot be", "coding: utf-8 -*- __doc__=\"\"\" Fakes auto-alignment in glyphs that cannot", "listOfSelectedLayers: thisGlyph = thisLayer.parent print \"Aligning components in:\", thisGlyph.name thisGlyph.beginUndo()", "begin undo grouping process( thisLayer ) thisGlyph.endUndo() # end undo", "font thisFontMaster = thisFont.selectedFontMaster # active master thisFontMasterID = thisFont.selectedFontMaster.id", "+= thisComponent.component.layers[thisFontMasterID].width thisLayer.width = advance thisFont.disableUpdateInterface() # suppresses UI updates", "thisFont.selectedFontMaster # active master thisFontMasterID = thisFont.selectedFontMaster.id # active master", "__doc__=\"\"\" Fakes auto-alignment in glyphs that cannot be auto-aligned. \"\"\"", "print \"Aligning components in:\", thisGlyph.name thisGlyph.beginUndo() # begin undo grouping", "active layers of selected glyphs def process( thisLayer ): advance", "for thisLayer in listOfSelectedLayers: thisGlyph = thisLayer.parent print \"Aligning components", "frontmost font thisFontMaster = thisFont.selectedFontMaster # active master thisFontMasterID =", "glyphs def process( thisLayer ): advance = 0.0 for thisComponent", "= thisFont.selectedFontMaster.id # active master listOfSelectedLayers = thisFont.selectedLayers # active", "thisGlyph.name thisGlyph.beginUndo() # begin undo grouping process( thisLayer ) thisGlyph.endUndo()", "0.0 ) advance += thisComponent.component.layers[thisFontMasterID].width thisLayer.width = advance thisFont.disableUpdateInterface() #", "thisLayer ): advance = 0.0 for thisComponent in thisLayer.components: thisComponent.position", "Fakes auto-alignment in glyphs that cannot be auto-aligned. \"\"\" import", "Components.py #MenuTitle: Align All Components # -*- coding: utf-8 -*-", "that cannot be auto-aligned. \"\"\" import GlyphsApp thisFont = Glyphs.font", "def process( thisLayer ): advance = 0.0 for thisComponent in", "# -*- coding: utf-8 -*- __doc__=\"\"\" Fakes auto-alignment in glyphs", "<reponame>davidtahim/Glyphs-Scripts<filename>Components/Align All Components.py #MenuTitle: Align All Components # -*- coding:", "thisFont.disableUpdateInterface() # suppresses UI updates in Font View for thisLayer", "active master thisFontMasterID = thisFont.selectedFontMaster.id # active master listOfSelectedLayers =", "thisLayer.components: thisComponent.position = NSPoint( advance, 0.0 ) advance += thisComponent.component.layers[thisFontMasterID].width", "# active master thisFontMasterID = thisFont.selectedFontMaster.id # active master listOfSelectedLayers", "for thisComponent in thisLayer.components: thisComponent.position = NSPoint( advance, 0.0 )", "of selected glyphs def process( thisLayer ): advance = 0.0", "master listOfSelectedLayers = thisFont.selectedLayers # active layers of selected glyphs", "Align All Components # -*- coding: utf-8 -*- __doc__=\"\"\" Fakes", "layers of selected glyphs def process( thisLayer ): advance =", "process( thisLayer ) thisGlyph.endUndo() # end undo grouping thisFont.enableUpdateInterface() #" ]
[ "int size, ready for drawing. \"\"\" top = tk.Tk() top.minsize(width=width", "w.create_text(0, 0, text='SC101', anchor=tk.NW, font='times 80') tk.mainloop() #告訴電腦不要關掉視窗 if __name__", "TK Drawing Lecture Exercises Courtesy of <NAME> \"\"\" import tkinter", "complete def make_canvas(width, height): \"\"\" Creates and returns a drawing", "make_canvas(1000, 500) w.create_line(0, 0, 1000, 500, width=5, fill='red') w.create_text(0, 0,", "works correctly canvas.yview_scroll(6, \"units\") return canvas def main(): w =", "width=width, height=height) canvas.pack() canvas.xview_scroll(6, \"units\") # hack so (0, 0)", "<NAME> \"\"\" import tkinter as tk # provided function, this", "this code is complete def make_canvas(width, height): \"\"\" Creates and", "canvas = tk.Canvas(top, width=width, height=height) canvas.pack() canvas.xview_scroll(6, \"units\") # hack", "is complete def make_canvas(width, height): \"\"\" Creates and returns a", "size, ready for drawing. \"\"\" top = tk.Tk() top.minsize(width=width +", "\"\"\" Stanford CS106AP TK Drawing Lecture Exercises Courtesy of <NAME>", "of <NAME> \"\"\" import tkinter as tk # provided function,", "\"\"\" import tkinter as tk # provided function, this code", "python3 \"\"\" Stanford CS106AP TK Drawing Lecture Exercises Courtesy of", "anchor=tk.NW, font='times 80') tk.mainloop() #告訴電腦不要關掉視窗 if __name__ == '__main__': main()", "given int size, ready for drawing. \"\"\" top = tk.Tk()", "\"\"\" top = tk.Tk() top.minsize(width=width + 10, height=height + 10)", "canvas def main(): w = make_canvas(1000, 500) w.create_line(0, 0, 1000,", "= tk.Tk() top.minsize(width=width + 10, height=height + 10) canvas =", "+ 10) canvas = tk.Canvas(top, width=width, height=height) canvas.pack() canvas.xview_scroll(6, \"units\")", "hack so (0, 0) works correctly canvas.yview_scroll(6, \"units\") return canvas", "Stanford CS106AP TK Drawing Lecture Exercises Courtesy of <NAME> \"\"\"", "the given int size, ready for drawing. \"\"\" top =", "\"units\") # hack so (0, 0) works correctly canvas.yview_scroll(6, \"units\")", "as tk # provided function, this code is complete def", "0, 1000, 500, width=5, fill='red') w.create_text(0, 0, text='SC101', anchor=tk.NW, font='times", "Exercises Courtesy of <NAME> \"\"\" import tkinter as tk #", "provided function, this code is complete def make_canvas(width, height): \"\"\"", "# hack so (0, 0) works correctly canvas.yview_scroll(6, \"units\") return", "1000, 500, width=5, fill='red') w.create_text(0, 0, text='SC101', anchor=tk.NW, font='times 80')", "tk.Canvas(top, width=width, height=height) canvas.pack() canvas.xview_scroll(6, \"units\") # hack so (0,", "Drawing Lecture Exercises Courtesy of <NAME> \"\"\" import tkinter as", "+ 10, height=height + 10) canvas = tk.Canvas(top, width=width, height=height)", "function, this code is complete def make_canvas(width, height): \"\"\" Creates", "ready for drawing. \"\"\" top = tk.Tk() top.minsize(width=width + 10,", "return canvas def main(): w = make_canvas(1000, 500) w.create_line(0, 0,", "correctly canvas.yview_scroll(6, \"units\") return canvas def main(): w = make_canvas(1000,", "CS106AP TK Drawing Lecture Exercises Courtesy of <NAME> \"\"\" import", "height): \"\"\" Creates and returns a drawing canvas of the", "height=height + 10) canvas = tk.Canvas(top, width=width, height=height) canvas.pack() canvas.xview_scroll(6,", "import tkinter as tk # provided function, this code is", "\"units\") return canvas def main(): w = make_canvas(1000, 500) w.create_line(0,", "width=5, fill='red') w.create_text(0, 0, text='SC101', anchor=tk.NW, font='times 80') tk.mainloop() #告訴電腦不要關掉視窗", "make_canvas(width, height): \"\"\" Creates and returns a drawing canvas of", "returns a drawing canvas of the given int size, ready", "top.minsize(width=width + 10, height=height + 10) canvas = tk.Canvas(top, width=width,", "canvas.pack() canvas.xview_scroll(6, \"units\") # hack so (0, 0) works correctly", "500) w.create_line(0, 0, 1000, 500, width=5, fill='red') w.create_text(0, 0, text='SC101',", "w.create_line(0, 0, 1000, 500, width=5, fill='red') w.create_text(0, 0, text='SC101', anchor=tk.NW,", "# provided function, this code is complete def make_canvas(width, height):", "so (0, 0) works correctly canvas.yview_scroll(6, \"units\") return canvas def", "text='SC101', anchor=tk.NW, font='times 80') tk.mainloop() #告訴電腦不要關掉視窗 if __name__ == '__main__':", "drawing. \"\"\" top = tk.Tk() top.minsize(width=width + 10, height=height +", "10) canvas = tk.Canvas(top, width=width, height=height) canvas.pack() canvas.xview_scroll(6, \"units\") #", "Creates and returns a drawing canvas of the given int", "0, text='SC101', anchor=tk.NW, font='times 80') tk.mainloop() #告訴電腦不要關掉視窗 if __name__ ==", "w = make_canvas(1000, 500) w.create_line(0, 0, 1000, 500, width=5, fill='red')", "= tk.Canvas(top, width=width, height=height) canvas.pack() canvas.xview_scroll(6, \"units\") # hack so", "0) works correctly canvas.yview_scroll(6, \"units\") return canvas def main(): w", "500, width=5, fill='red') w.create_text(0, 0, text='SC101', anchor=tk.NW, font='times 80') tk.mainloop()", "Lecture Exercises Courtesy of <NAME> \"\"\" import tkinter as tk", "drawing canvas of the given int size, ready for drawing.", "of the given int size, ready for drawing. \"\"\" top", "<gh_stars>0 #!/usr/bin/env python3 \"\"\" Stanford CS106AP TK Drawing Lecture Exercises", "tkinter as tk # provided function, this code is complete", "canvas of the given int size, ready for drawing. \"\"\"", "\"\"\" Creates and returns a drawing canvas of the given", "#!/usr/bin/env python3 \"\"\" Stanford CS106AP TK Drawing Lecture Exercises Courtesy", "tk.Tk() top.minsize(width=width + 10, height=height + 10) canvas = tk.Canvas(top,", "main(): w = make_canvas(1000, 500) w.create_line(0, 0, 1000, 500, width=5,", "canvas.yview_scroll(6, \"units\") return canvas def main(): w = make_canvas(1000, 500)", "top = tk.Tk() top.minsize(width=width + 10, height=height + 10) canvas", "def main(): w = make_canvas(1000, 500) w.create_line(0, 0, 1000, 500,", "and returns a drawing canvas of the given int size,", "10, height=height + 10) canvas = tk.Canvas(top, width=width, height=height) canvas.pack()", "fill='red') w.create_text(0, 0, text='SC101', anchor=tk.NW, font='times 80') tk.mainloop() #告訴電腦不要關掉視窗 if", "def make_canvas(width, height): \"\"\" Creates and returns a drawing canvas", "height=height) canvas.pack() canvas.xview_scroll(6, \"units\") # hack so (0, 0) works", "tk # provided function, this code is complete def make_canvas(width,", "a drawing canvas of the given int size, ready for", "Courtesy of <NAME> \"\"\" import tkinter as tk # provided", "= make_canvas(1000, 500) w.create_line(0, 0, 1000, 500, width=5, fill='red') w.create_text(0,", "canvas.xview_scroll(6, \"units\") # hack so (0, 0) works correctly canvas.yview_scroll(6,", "for drawing. \"\"\" top = tk.Tk() top.minsize(width=width + 10, height=height", "code is complete def make_canvas(width, height): \"\"\" Creates and returns", "(0, 0) works correctly canvas.yview_scroll(6, \"units\") return canvas def main():" ]
[ "[default: 9002]', default=9002) parser.add_argument('-device', type=str, help='audio device [default: \\'sysdefault\\']', default='sysdefault')", "cachefile = 'cache'+str(self.idcache) self.idcache = (self.idcache+1)%10 tmpfile = \"/tmp/cache.wav\" ofile", "None asr_server = None def TTS_callback(in_data, frame_count, time_info, status): global", "# def playwav_pa(self, sfile): # global soundfile # self.streaming =", "understood: %s' %data) self.reply('ERR') elif (data == None or data==\"\"):", "cmd = 'rm %s %s' %(tmpfile, ofile) os.system(cmd) if (lang=='en'):", "setVolume(self,volperc): # volume in percentag [0-100] cmdstr = 'amixer set", "%volperc os.system(cmdstr) def run(self): global asr_server if (use_sound_play and self.soundhandle", "self.connection.send(mstr+'\\n\\r') except: print('Connection closed') def setVolume(self,volperc): # volume in percentag", "data %d' %(len(data))) if self.aa_stream != None: self.aa_stream.write(data) data =", "retry = 3 while retry>0: try: self.output_device='default' print(\"Audio device used:", "= alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device) retry = 0 except Exception as", "os.system(cmd) if (lang=='en'): lang = 'en-US' elif (len(lang)==2): lang =", "default=9001) parser.add_argument('-asrport', type=int, help='ASR server port [default: 9002]', default=9002) parser.add_argument('-device',", "(self.dorun): try: data = self.connection.recv(320) data = data.strip() except socket.timeout:", "bop.wav synth 0.25 sine 400 # Voices # pico2wave -l", "%(SOUNDS_DIR,name) time.sleep(1) i += 1 if (soundfile != None and", "# Note: some initial sound may not be played. #", "print cmd os.system(cmd) time.sleep(0.2) # convert samplerate tfm = sox.Transformer()", "= 'rm %s %s' %(tmpfile, ofile) os.system(cmd) if (lang=='en'): lang", "\"choose \",l self.output_device = l # choose default device break", "select proper sysdefault name for l in pp: print(' %s'", "= soundfile.readframes(self.periodsize) # def playwav_pa(self, sfile): # global soundfile #", "lang = lang+'-'+lang.upper() time.sleep(0.2) cmd = 'pico2wave -l \"%s\" -w", "= alsaaudio.pcms() if (self.output_device=='sysdefault'): # select proper sysdefault name for", "print(\"Audio device used: %s\" %self.output_device) self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device)", "%s' %data) self.reply('ERR') elif (data == None or data==\"\"): break", "{} self.Sounds['bip'] = wave.open(SOUNDS_DIR+'bip.wav', 'rb') self.idcache = 0 def init_alsaaudio(self):", "server has been closed.', 'en') time.sleep(2) self.aa_stream = None def", "if bh!='': print('ASR sent [%s]' %bh) elif (data.startswith('SOUND')): self.play(data[6:]) #", "while (self.dorun and not connected): try: # print 'Waiting for", "# cmd = 'play -n --no-show-progress -r 44100 -c1 synth", "default='sysdefault') args = parser.parse_args() tts_server = TTSServer(args.ttsport,args.device) asr_server = ASRServer(args.asrport)", "if (data.startswith('TTS')): lang = 'en-US' # default language strsay =", "to the port server_address = ('', port) self.sock.bind(server_address) self.sock.listen(1) print", "ASRServer SOUNDS_DIR = \"sounds/\" # dir with sounds soundfile =", "elif (use_alsaaudio): self.init_alsaaudio() else: print('Cannot initializa audio interface') # Create", "\"Listen again ...\" def reply(self,mstr): if (self.connection != None): try:", "print('Play completed.') def playwav_aa(self, soundfile): soundfile.setpos(0) data = soundfile.readframes(self.periodsize) while", "if self.aa_stream == None: retry = 3 while retry>0: try:", "= self.audio_rate / 8 if self.aa_stream != None: self.aa_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.aa_stream.setchannels(1)", "synth 0.25 sine 400 # Voices # pico2wave -l \"it-IT\"", "help='TTS server port [default: 9001]', default=9001) parser.add_argument('-asrport', type=int, help='ASR server", "the socket to the port server_address = ('', port) self.sock.bind(server_address)", "== None: retry = 3 while retry>0: try: self.output_device='default' print(\"Audio", "sounds soundfile = None # sound file tts_server = None", "init_alsaaudio(self): print(\"Audio devices available\") pp = alsaaudio.pcms() if (self.output_device=='sysdefault'): #", "(self.output_device=='sysdefault'): # select proper sysdefault name for l in pp:", "%s \" , %s\"' %(lang,tmpfile, data) print cmd os.system(cmd) time.sleep(0.2)", "if self.aa_stream != None: self.aa_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.aa_stream.setchannels(1) self.aa_stream.setrate(self.audio_rate) self.aa_stream.setperiodsize(self.periodsize) def stop(self):", "= data.strip() except socket.timeout: data = \"***\" except: data =", "'rm %s %s' %(tmpfile, ofile) os.system(cmd) if (lang=='en'): lang =", "# Only PCM 16 bit wav 44100 Hz - Use", "time.sleep(3) self.setVolume(99) # set volume (99% = +3 dB) #print('bip')", "# Synth # sox -n --no-show-progress -G --channels 1 -r", "= vd[1] strsay = vd[2] self.say(strsay,lang) self.reply('OK') elif (data==\"ASR\"): #print('asr", "self.connection.settimeout(3) # timeout when listening (exit with CTRL+C) connected =", "--channels 1 -r 44100 -b 16 -t wav bip.wav synth", "time import socket import sys, os, platform import re import", "use_alsaaudio = False elif (use_alsaaudio): self.init_alsaaudio() else: print('Cannot initializa audio", "soundfile): soundfile.setpos(0) data = soundfile.readframes(self.periodsize) while (len(data)>0): # print('stream data", "or sox to convert audio files. # WAV generation #", "try: mstr = mstr.encode('utf-8') self.connection.send(mstr+'\\n\\r') except: print('Connection closed') def setVolume(self,volperc):", "Server Connection closed.' # Clean up the connection if (self.connection", "\"/tmp/cache.wav\" ofile = \"%s%s.wav\" %(SOUNDS_DIR, cachefile) cmd = 'rm %s", "time.sleep(1) i += 1 if (soundfile != None and use_alsaaudio):", "3 while retry>0: try: self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device) retry", "# Initialize audio player self.streaming = False self.output_device = output_device", "platform.machine() print \"Machine type:\" , m if (m[0:3]=='arm'): use_sound_play =", "print(e) retry -= 1 time.sleep(2) if self.aa_stream == None: retry", "audacity or sox to convert audio files. # WAV generation", "volume in percentag [0-100] cmdstr = 'amixer set PCM %d%%'", "vd[1] strsay = vd[2] self.say(strsay,lang) self.reply('OK') elif (data==\"ASR\"): #print('asr request')", "# soundfile = sfile # soundfile.setpos(0) # self.stream.start_stream() # while", "# time.sleep(1.0) # self.stream.stop_stream() # self.stream.close() # self.streaming = False", "argparse.ArgumentParser(description='audio_server') parser.add_argument('-ttsport', type=int, help='TTS server port [default: 9001]', default=9001) parser.add_argument('-asrport',", "import ASRServer SOUNDS_DIR = \"sounds/\" # dir with sounds soundfile", "= 'en-US' elif (len(lang)==2): lang = lang+'-'+lang.upper() time.sleep(0.2) cmd =", "[%s]' % data if (data.startswith('TTS')): lang = 'en-US' # default", "server_address = ('', port) self.sock.bind(server_address) self.sock.listen(1) print \"TTS Server running", "in pp: print(' %s' %l) if (l[0:10]=='sysdefault'): print \"choose \",l", "#print 'sending data back to the client' #self.connection.sendall(\"OK\") else: print('Message", "= \"sounds/\" # dir with sounds soundfile = None #", "socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.settimeout(3) # Bind the socket", "# set volume (99% = +3 dB) #print('bip') #self.play('bip') #time.sleep(3)", "status): global soundfile if (soundfile==None): return (None, True) else: data", "= 0 except Exception as e: print(e) retry -= 1", "True) else: data = soundfile.readframes(frame_count) return (data, pyaudio.paContinue) class TTSServer(threading.Thread):", "self.aa_stream == None: retry = 3 while retry>0: try: self.output_device='default'", "'TTS Server Connection from ', client_address except: pass #print \"Listen", "audio. No infrastructure available.') def play(self, name): if (use_alsaaudio): print('Playing", "server port [default: 9002]', default=9002) parser.add_argument('-device', type=str, help='audio device [default:", "self.reply('OK') #print 'sending data back to the client' #self.connection.sendall(\"OK\") else:", "except Exception as e: print(e) retry -= 1 time.sleep(2) if", "'en') time.sleep(2) self.aa_stream = None def say(self, data, lang): print", "= argparse.ArgumentParser(description='audio_server') parser.add_argument('-ttsport', type=int, help='TTS server port [default: 9001]', default=9001)", "% voice print 'Volume: %s' % volume self.soundhandle.say(data, voice, volume)", "the connection if (self.connection != None): self.connection.close() self.connection = None", "%(tmpfile, ofile) os.system(cmd) if (lang=='en'): lang = 'en-US' elif (len(lang)==2):", "lang+'-'+lang.upper() time.sleep(0.2) cmd = 'pico2wave -l \"%s\" -w %s \"", "cmd os.system(cmd) time.sleep(0.2) # convert samplerate tfm = sox.Transformer() tfm.rate(samplerate=self.audio_rate)", "set PCM %d%%' %volperc os.system(cmdstr) def run(self): global asr_server if", "\"Bene! Si Parte!\" # Then convert wav files to to", "(self.connection != None): self.connection.close() self.connection = None self.say('Audio server has", "sound self.reply('OK') #print 'sending data back to the client' #self.connection.sendall(\"OK\")", "sound_play.libsoundplay import SoundClient except: print('ROS package sound_play required.') print('Install with:", "# alsaaudio examples # https://larsimmisch.github.io/pyalsaaudio/libalsaaudio.html import threading import time import", "retry = 3 while retry>0: try: self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL,", "up the connection if (self.connection != None): self.connection.close() self.connection =", "= data[4:] if (data[3]=='['): vd = re.split('\\[|\\]',data) lang = vd[1]", "# self.stream = self.pa.open(format = 8, #self.pa.get_format_from_width(f.getsampwidth#()), # channels =", "= self.connection.recv(320) data = data.strip() except socket.timeout: data = \"***\"", "= None def TTS_callback(in_data, frame_count, time_info, status): global soundfile if", "def init_alsaaudio(self): print(\"Audio devices available\") pp = alsaaudio.pcms() if (self.output_device=='sysdefault'):", "# choose default device break print(\"Audio device used: %s\" %self.output_device)", "as e: print(e) retry -= 1 time.sleep(2) if self.aa_stream ==", "# output = True, # stream_callback = TTS_callback, # output_device_index", "= wave.open(SOUNDS_DIR+'bip.wav', 'rb') self.idcache = 0 def init_alsaaudio(self): print(\"Audio devices", "# os.system(cmd) except KeyboardInterrupt: print \"Exit\" run = False tts_server.stop()", "# self.stream.stop_stream() # self.stream.close() # self.streaming = False if __name__", "soundfile.setpos(0) data = soundfile.readframes(self.periodsize) while (len(data)>0): # print('stream data %d'", "bh!='': print('ASR sent [%s]' %bh) elif (data.startswith('SOUND')): self.play(data[6:]) # play", "(data==\"ASR\"): #print('asr request') bh = asr_server.get_asr() self.reply(bh) if bh!='': print('ASR", "global soundfile if (soundfile==None): return (None, True) else: data =", "self.connection = None self.say('Audio server has been closed.', 'en') time.sleep(2)", "= lang+'-'+lang.upper() time.sleep(0.2) cmd = 'pico2wave -l \"%s\" -w %s", "-l \"it-IT\" -w start.wav \"Bene! Si Parte!\" # Then convert", "return (None, True) else: data = soundfile.readframes(frame_count) return (data, pyaudio.paContinue)", "# soundfile.setpos(0) # self.stream.start_stream() # while self.stream.is_active(): # time.sleep(1.0) #", "(None, True) else: data = soundfile.readframes(frame_count) return (data, pyaudio.paContinue) class", "listening (exit with CTRL+C) connected = True print 'TTS Server", "\"TTS Server running on port \", port, \" ...\" self.dorun", "if self.aa_stream != None: self.aa_stream.write(data) data = soundfile.readframes(self.periodsize) # def", "try: # print 'Waiting for a connection ...' # Wait", "use_sound_play threading.Thread.__init__(self) # Initialize audio player self.streaming = False self.output_device", "1 -r 44100 -b 16 -t wav bop.wav synth 0.25", "self.aa_stream != None: self.aa_stream.write(data) data = soundfile.readframes(self.periodsize) # def playwav_pa(self,", "Use audacity or sox to convert audio files. # WAV", "print('ASR sent [%s]' %bh) elif (data.startswith('SOUND')): self.play(data[6:]) # play this", "#f.getnchannels(), # rate = 44100, #f.getframerate(), # output = True,", "-r 44100 -c1 synth 0.1 sine 50 vol 0.01' #", "None): self.connection.close() self.connection = None self.say('Audio server has been closed.',", "...' %name) soundfile = None i = 0 while (i<3):", "= 1, #f.getnchannels(), # rate = 44100, #f.getframerate(), # output", "used: %s\" %self.output_device) self.aa_stream = None retry = 3 while", "%s\" %self.output_device) self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device) retry = 0", "wave import argparse import rospy use_sound_play = False use_alsaaudio =", "# sound file tts_server = None asr_server = None def", "(data.startswith('SOUND')): self.play(data[6:]) # play this sound self.reply('OK') #print 'sending data", "#if (not tts_server.streaming): # cmd = 'play -n --no-show-progress -r", "pyalsaaudio') use_alsaaudio = False #sys.exit(0) from asr_server import ASRServer SOUNDS_DIR", "completed.') def playwav_aa(self, soundfile): soundfile.setpos(0) data = soundfile.readframes(self.periodsize) while (len(data)>0):", "# https://larsimmisch.github.io/pyalsaaudio/libalsaaudio.html import threading import time import socket import sys,", "closed') def setVolume(self,volperc): # volume in percentag [0-100] cmdstr =", "(soundfile != None and use_alsaaudio): #(name in self.Sounds): self.playwav_aa(soundfile) print('Play", "soundfile except: print \"File %s%s.wav not found.\" %(SOUNDS_DIR,name) time.sleep(1) i", "bip.wav synth 0.25 sine 800 # sox -n --no-show-progress -G", "wav bop.wav synth 0.25 sine 400 # Voices # pico2wave", "from ', client_address except: pass #print \"Listen again ...\" def", "= +3 dB) #print('bip') #self.play('bip') #time.sleep(3) self.say('Hello!', 'en') self.say('Audio server", "if (self.connection != None): self.connection.close() self.connection = None self.say('Audio server", "#((not name in self.Sounds) and (i<3)): try: soundfile = wave.open(SOUNDS_DIR+name+\".wav\",", "self.playwav_aa(soundfile) print('Play completed.') def playwav_aa(self, soundfile): soundfile.setpos(0) data = soundfile.readframes(self.periodsize)", "TTS_callback(in_data, frame_count, time_info, status): global soundfile if (soundfile==None): return (None,", "#f.getframerate(), # output = True, # stream_callback = TTS_callback, #", "sine 800 # sox -n --no-show-progress -G --channels 1 -r", "= parser.parse_args() tts_server = TTSServer(args.ttsport,args.device) asr_server = ASRServer(args.asrport) tts_server.start() time.sleep(1)", "16 -t wav bip.wav synth 0.25 sine 800 # sox", "# pico2wave -l \"it-IT\" -w start.wav \"Bene! Si Parte!\" #", "sound file tts_server = None asr_server = None def TTS_callback(in_data,", "in self.Sounds): self.playwav_aa(soundfile) print('Play completed.') def playwav_aa(self, soundfile): soundfile.setpos(0) data", "data in small chunks while (self.dorun): try: data = self.connection.recv(320)", "wav files to to 44100 Hz # Note: some initial", "Wait for a connection self.connection, client_address = self.sock.accept() self.connection.settimeout(3) #", "use_sound_play = False if (use_sound_play): os.system('roslaunch sound_play.launch &') time.sleep(5) rospy.init_node('sound_client',", "play audio. No infrastructure available.') def play(self, name): if (use_alsaaudio):", "self.streaming = False self.output_device = output_device self.soundhandle = None m", "-t wav bop.wav synth 0.25 sine 400 # Voices #", "Initialize audio player self.streaming = False self.output_device = output_device self.soundhandle", "self.idcache = (self.idcache+1)%10 tmpfile = \"/tmp/cache.wav\" ofile = \"%s%s.wav\" %(SOUNDS_DIR,", "= sfile # soundfile.setpos(0) # self.stream.start_stream() # while self.stream.is_active(): #", "data !=\"\" and data!=\"***\"): if data!=\"ASR\": print 'TTS Received [%s]'", "= soundfile.readframes(self.periodsize) while (len(data)>0): # print('stream data %d' %(len(data))) if", "required. Install with: pip install --user sox') sys.exit(0) try: import", "!= None: self.aa_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.aa_stream.setchannels(1) self.aa_stream.setrate(self.audio_rate) self.aa_stream.setperiodsize(self.periodsize) def stop(self): self.dorun =", "name): if (use_alsaaudio): print('Playing %s ...' %name) soundfile = None", "self.output_device) # soundfile = sfile # soundfile.setpos(0) # self.stream.start_stream() #", "self.connection.close() self.connection = None self.say('Audio server has been closed.', 'en')", "self.connection.recv(320) data = data.strip() except socket.timeout: data = \"***\" except:", "False #sys.exit(0) from asr_server import ASRServer SOUNDS_DIR = \"sounds/\" #", "as e: print(e) retry -= 1 time.sleep(2) self.audio_rate = 44100", "%self.output_device) self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device) retry = 0 except", "retry -= 1 time.sleep(2) self.audio_rate = 44100 self.periodsize = self.audio_rate", "(i<3)): try: soundfile = wave.open(SOUNDS_DIR+name+\".wav\", 'rb') #self.Sounds[name] = soundfile except:", "sudo apt-get install ros-kinetic-audio-common libasound2') use_sound_play = False #sys.exit(0) try:", "= mstr.encode('utf-8') self.connection.send(mstr+'\\n\\r') except: print('Connection closed') def setVolume(self,volperc): # volume", "data!=\"***\"): if data!=\"ASR\": print 'TTS Received [%s]' % data if", "= 'play -n --no-show-progress -r 44100 -c1 synth 0.1 sine", "self.setVolume(99) # set volume (99% = +3 dB) #print('bip') #self.play('bip')", "print(' %s' %l) if (l[0:10]=='sysdefault'): print \"choose \",l self.output_device =", "if (soundfile != None and use_alsaaudio): #(name in self.Sounds): self.playwav_aa(soundfile)", "= None m = platform.machine() print \"Machine type:\" , m", "not found.\" %(SOUNDS_DIR,name) time.sleep(1) i += 1 if (soundfile !=", "and data !=\"\" and data!=\"***\"): if data!=\"ASR\": print 'TTS Received", "os, platform import re import wave import argparse import rospy", "-r 44100 -b 16 -t wav bop.wav synth 0.25 sine", "...' # Wait for a connection self.connection, client_address = self.sock.accept()", "import alsaaudio except: print('alsaaudio required. Install with: pip install --user", "voice, volume) rospy.sleep(3) elif (use_alsaaudio): cachefile = 'cache'+str(self.idcache) self.idcache =", "soundfile.readframes(self.periodsize) while (len(data)>0): # print('stream data %d' %(len(data))) if self.aa_stream", "# Dictionary of sounds self.Sounds = {} self.Sounds['bip'] = wave.open(SOUNDS_DIR+'bip.wav',", "import socket import sys, os, platform import re import wave", "self.play(data[6:]) # play this sound self.reply('OK') #print 'sending data back", "for a connection self.connection, client_address = self.sock.accept() self.connection.settimeout(3) # timeout", "Install with: pip install --user pyalsaaudio') use_alsaaudio = False #sys.exit(0)", "Clean up the connection if (self.connection != None): self.connection.close() self.connection", "wave.open(SOUNDS_DIR+name+\".wav\", 'rb') #self.Sounds[name] = soundfile except: print \"File %s%s.wav not", "try: self.output_device='default' print(\"Audio device used: %s\" %self.output_device) self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK,", "(self.connection != None): try: mstr = mstr.encode('utf-8') self.connection.send(mstr+'\\n\\r') except: print('Connection", "and use_alsaaudio): #(name in self.Sounds): self.playwav_aa(soundfile) print('Play completed.') def playwav_aa(self,", "to to 44100 Hz # Note: some initial sound may", "= 1.0 print 'Saying: %s' % data print 'Voice: %s'", "vol 0.01' # keep sound alive # os.system(cmd) except KeyboardInterrupt:", "set volume (99% = +3 dB) #print('bip') #self.play('bip') #time.sleep(3) self.say('Hello!',", "https://larsimmisch.github.io/pyalsaaudio/libalsaaudio.html import threading import time import socket import sys, os,", "44100 -b 16 -t wav bop.wav synth 0.25 sine 400", "-l \"%s\" -w %s \" , %s\"' %(lang,tmpfile, data) print", "disable_signals=True) use_alsaaudio = False elif (use_alsaaudio): self.init_alsaaudio() else: print('Cannot initializa", "client_address except: pass #print \"Listen again ...\" def reply(self,mstr): if", "', client_address except: pass #print \"Listen again ...\" def reply(self,mstr):", "devices available\") pp = alsaaudio.pcms() if (self.output_device=='sysdefault'): # select proper", "re.split('\\[|\\]',data) lang = vd[1] strsay = vd[2] self.say(strsay,lang) self.reply('OK') elif", "audio files. # WAV generation # Synth # sox -n", "# sox -n --no-show-progress -G --channels 1 -r 44100 -b", "Si Parte!\" # Then convert wav files to to 44100", "sound alive # os.system(cmd) except KeyboardInterrupt: print \"Exit\" run =", "\" , %s\"' %(lang,tmpfile, data) print cmd os.system(cmd) time.sleep(0.2) #", "%name) soundfile = None i = 0 while (i<3): #((not", "playwav_aa(self, soundfile): soundfile.setpos(0) data = soundfile.readframes(self.periodsize) while (len(data)>0): # print('stream", "time.sleep(0.2) self.play(cachefile) else: print('Cannot play audio. No infrastructure available.') def", "if (l[0:10]=='sysdefault'): print \"choose \",l self.output_device = l # choose", "to convert audio files. # WAV generation # Synth #", "%bh) elif (data.startswith('SOUND')): self.play(data[6:]) # play this sound self.reply('OK') #print", "lang): print 'Say ',data if (use_sound_play): voice = 'voice_kal_diphone' volume", "except: data = None if (data!=None and data !=\"\" and", "SOUNDS_DIR = \"sounds/\" # dir with sounds soundfile = None", "elif (use_alsaaudio): cachefile = 'cache'+str(self.idcache) self.idcache = (self.idcache+1)%10 tmpfile =", "-b 16 -t wav bop.wav synth 0.25 sine 400 #", "0 def init_alsaaudio(self): print(\"Audio devices available\") pp = alsaaudio.pcms() if", "type=int, help='ASR server port [default: 9002]', default=9002) parser.add_argument('-device', type=str, help='audio", "/ 8 if self.aa_stream != None: self.aa_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.aa_stream.setchannels(1) self.aa_stream.setrate(self.audio_rate) self.aa_stream.setperiodsize(self.periodsize)", "self.aa_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.aa_stream.setchannels(1) self.aa_stream.setrate(self.audio_rate) self.aa_stream.setperiodsize(self.periodsize) def stop(self): self.dorun = False def", "= TTS_callback, # output_device_index = self.output_device) # soundfile = sfile", "e: print(e) retry -= 1 time.sleep(2) if self.aa_stream == None:", "= ('', port) self.sock.bind(server_address) self.sock.listen(1) print \"TTS Server running on", "if (data[3]=='['): vd = re.split('\\[|\\]',data) lang = vd[1] strsay =", "'rb') self.idcache = 0 def init_alsaaudio(self): print(\"Audio devices available\") pp", "import time import socket import sys, os, platform import re", "sound_play required.') print('Install with: sudo apt-get install ros-kinetic-audio-common libasound2') use_sound_play", "required.') print('Install with: sudo apt-get install ros-kinetic-audio-common libasound2') use_sound_play =", "None: self.aa_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.aa_stream.setchannels(1) self.aa_stream.setrate(self.audio_rate) self.aa_stream.setperiodsize(self.periodsize) def stop(self): self.dorun = False", "self.say(strsay,lang) self.reply('OK') elif (data==\"ASR\"): #print('asr request') bh = asr_server.get_asr() self.reply(bh)", "run = True while (run): try: time.sleep(3) #if (not tts_server.streaming):", "proper sysdefault name for l in pp: print(' %s' %l)", "= soundfile except: print \"File %s%s.wav not found.\" %(SOUNDS_DIR,name) time.sleep(1)", "None: retry = 3 while retry>0: try: self.output_device='default' print(\"Audio device", "= None if (data!=None and data !=\"\" and data!=\"***\"): if", "has been closed.', 'en') time.sleep(2) self.aa_stream = None def say(self,", "def playwav_aa(self, soundfile): soundfile.setpos(0) data = soundfile.readframes(self.periodsize) while (len(data)>0): #", "sound_play.msg import SoundRequest from sound_play.libsoundplay import SoundClient except: print('ROS package", "SoundRequest from sound_play.libsoundplay import SoundClient except: print('ROS package sound_play required.')", "'sending data back to the client' #self.connection.sendall(\"OK\") else: print('Message not", "vd = re.split('\\[|\\]',data) lang = vd[1] strsay = vd[2] self.say(strsay,lang)", "while retry>0: try: self.output_device='default' print(\"Audio device used: %s\" %self.output_device) self.aa_stream", "sfile): # global soundfile # self.streaming = True # self.stream", "connection if (self.connection != None): self.connection.close() self.connection = None self.say('Audio", "client' #self.connection.sendall(\"OK\") else: print('Message not understood: %s' %data) self.reply('ERR') elif", "Only PCM 16 bit wav 44100 Hz - Use audacity", "(m[0:3]=='arm'): use_sound_play = False if (use_sound_play): os.system('roslaunch sound_play.launch &') time.sleep(5)", "= sox.Transformer() tfm.rate(samplerate=self.audio_rate) tfm.build(tmpfile, ofile) time.sleep(0.2) self.play(cachefile) else: print('Cannot play", "server is running.', 'en') time.sleep(3) while (self.dorun): self.connect() try: #", "[default: \\'sysdefault\\']', default='sysdefault') args = parser.parse_args() tts_server = TTSServer(args.ttsport,args.device) asr_server", "cmd = 'pico2wave -l \"%s\" -w %s \" , %s\"'", "16 bit wav 44100 Hz - Use audacity or sox", "PCM 16 bit wav 44100 Hz - Use audacity or", "False while (self.dorun and not connected): try: # print 'Waiting", "# WAV generation # Synth # sox -n --no-show-progress -G", "(data.startswith('TTS')): lang = 'en-US' # default language strsay = data[4:]", "again ...\" def reply(self,mstr): if (self.connection != None): try: mstr", "(run): try: time.sleep(3) #if (not tts_server.streaming): # cmd = 'play", "self.output_device = output_device self.soundhandle = None m = platform.machine() print", "None self.say('Audio server has been closed.', 'en') time.sleep(2) self.aa_stream =", "sox except: print('sox required. Install with: pip install --user sox')", "try: soundfile = wave.open(SOUNDS_DIR+name+\".wav\", 'rb') #self.Sounds[name] = soundfile except: print", "SoundClient() time.sleep(3) self.setVolume(99) # set volume (99% = +3 dB)", "files. # WAV generation # Synth # sox -n --no-show-progress", "#self.connection.sendall(\"OK\") else: print('Message not understood: %s' %data) self.reply('ERR') elif (data", "print('Install with: sudo apt-get install ros-kinetic-audio-common libasound2') use_sound_play = False", "try: import sox except: print('sox required. Install with: pip install", "= 0 def init_alsaaudio(self): print(\"Audio devices available\") pp = alsaaudio.pcms()", "# while self.stream.is_active(): # time.sleep(1.0) # self.stream.stop_stream() # self.stream.close() #", "used: %s\" %self.output_device) self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device) retry =", "import argparse import rospy use_sound_play = False use_alsaaudio = True", "\", port, \" ...\" self.dorun = True self.connection = None", "connect(self): connected = False while (self.dorun and not connected): try:", "on port \", port, \" ...\" self.dorun = True self.connection", "TTSServer(threading.Thread): def __init__(self, port, output_device): global use_alsaaudio, use_sound_play threading.Thread.__init__(self) #", "say(self, data, lang): print 'Say ',data if (use_sound_play): voice =", "the client' #self.connection.sendall(\"OK\") else: print('Message not understood: %s' %data) self.reply('ERR')", "(data[3]=='['): vd = re.split('\\[|\\]',data) lang = vd[1] strsay = vd[2]", "install --user pyalsaaudio') use_alsaaudio = False #sys.exit(0) from asr_server import", "#sys.exit(0) from asr_server import ASRServer SOUNDS_DIR = \"sounds/\" # dir", "self.aa_stream.setperiodsize(self.periodsize) def stop(self): self.dorun = False def connect(self): connected =", "print \"Machine type:\" , m if (m[0:3]=='arm'): use_sound_play = False", "\"***\" except: data = None if (data!=None and data !=\"\"", "self.reply('ERR') elif (data == None or data==\"\"): break finally: print", "i = 0 while (i<3): #((not name in self.Sounds) and", "'TTS Received [%s]' % data if (data.startswith('TTS')): lang = 'en-US'", "dir with sounds soundfile = None # sound file tts_server", "name in self.Sounds) and (i<3)): try: soundfile = wave.open(SOUNDS_DIR+name+\".wav\", 'rb')", "play this sound self.reply('OK') #print 'sending data back to the", "-b 16 -t wav bip.wav synth 0.25 sine 800 #", "choose default device break print(\"Audio device used: %s\" %self.output_device) self.aa_stream", ", m if (m[0:3]=='arm'): use_sound_play = False if (use_sound_play): os.system('roslaunch", "= None retry = 3 while retry>0: try: self.aa_stream =", "sys, os, platform import re import wave import argparse import", "= 3 while retry>0: try: self.output_device='default' print(\"Audio device used: %s\"", "install --user sox') sys.exit(0) try: import alsaaudio except: print('alsaaudio required.", "self.idcache = 0 def init_alsaaudio(self): print(\"Audio devices available\") pp =", "(self.dorun and not connected): try: # print 'Waiting for a", "for a connection ...' # Wait for a connection self.connection,", "print('Cannot play audio. No infrastructure available.') def play(self, name): if", "default device break print(\"Audio device used: %s\" %self.output_device) self.aa_stream =", "%self.output_device) self.aa_stream = None retry = 3 while retry>0: try:", "# select proper sysdefault name for l in pp: print('", "self.output_device) retry = 0 except Exception as e: print(e) retry", "port [default: 9002]', default=9002) parser.add_argument('-device', type=str, help='audio device [default: \\'sysdefault\\']',", "'Say ',data if (use_sound_play): voice = 'voice_kal_diphone' volume = 1.0", "interface') # Create a TCP/IP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)", "rate = 44100, #f.getframerate(), # output = True, # stream_callback", "(exit with CTRL+C) connected = True print 'TTS Server Connection", "socket to the port server_address = ('', port) self.sock.bind(server_address) self.sock.listen(1)", "Server running on port \", port, \" ...\" self.dorun =", "alive # os.system(cmd) except KeyboardInterrupt: print \"Exit\" run = False", "l # choose default device break print(\"Audio device used: %s\"", "be played. # alsaaudio examples # https://larsimmisch.github.io/pyalsaaudio/libalsaaudio.html import threading import", "= 0 while (i<3): #((not name in self.Sounds) and (i<3)):", "(99% = +3 dB) #print('bip') #self.play('bip') #time.sleep(3) self.say('Hello!', 'en') self.say('Audio", "use_sound_play = False #sys.exit(0) try: import sox except: print('sox required.", "# convert samplerate tfm = sox.Transformer() tfm.rate(samplerate=self.audio_rate) tfm.build(tmpfile, ofile) time.sleep(0.2)", "run(self): global asr_server if (use_sound_play and self.soundhandle == None): self.soundhandle", "Create a TCP/IP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,", "= SoundClient() time.sleep(3) self.setVolume(99) # set volume (99% = +3", "soundfile = None # sound file tts_server = None asr_server", "__name__ == \"__main__\": parser = argparse.ArgumentParser(description='audio_server') parser.add_argument('-ttsport', type=int, help='TTS server", "if (soundfile==None): return (None, True) else: data = soundfile.readframes(frame_count) return", "= asr_server.get_asr() self.reply(bh) if bh!='': print('ASR sent [%s]' %bh) elif", "(len(data)>0): # print('stream data %d' %(len(data))) if self.aa_stream != None:", "generation # Synth # sox -n --no-show-progress -G --channels 1", "Parte!\" # Then convert wav files to to 44100 Hz", "volume (99% = +3 dB) #print('bip') #self.play('bip') #time.sleep(3) self.say('Hello!', 'en')", "WAV generation # Synth # sox -n --no-show-progress -G --channels", "'Voice: %s' % voice print 'Volume: %s' % volume self.soundhandle.say(data,", "infrastructure available.') def play(self, name): if (use_alsaaudio): print('Playing %s ...'", "sounds self.Sounds = {} self.Sounds['bip'] = wave.open(SOUNDS_DIR+'bip.wav', 'rb') self.idcache =", "import sys, os, platform import re import wave import argparse", "False use_alsaaudio = True try: from sound_play.msg import SoundRequest from", "print 'TTS Received [%s]' % data if (data.startswith('TTS')): lang =", "# self.streaming = False if __name__ == \"__main__\": parser =", "while (self.dorun): try: data = self.connection.recv(320) data = data.strip() except", "device used: %s\" %self.output_device) self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device) retry", "player self.streaming = False self.output_device = output_device self.soundhandle = None", "while self.stream.is_active(): # time.sleep(1.0) # self.stream.stop_stream() # self.stream.close() # self.streaming", "if (lang=='en'): lang = 'en-US' elif (len(lang)==2): lang = lang+'-'+lang.upper()", "print \"TTS Server running on port \", port, \" ...\"", "help='audio device [default: \\'sysdefault\\']', default='sysdefault') args = parser.parse_args() tts_server =", "default language strsay = data[4:] if (data[3]=='['): vd = re.split('\\[|\\]',data)", "print('sox required. Install with: pip install --user sox') sys.exit(0) try:", "= TTSServer(args.ttsport,args.device) asr_server = ASRServer(args.asrport) tts_server.start() time.sleep(1) asr_server.start() run =", "if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='audio_server') parser.add_argument('-ttsport', type=int, help='TTS", "--no-show-progress -r 44100 -c1 synth 0.1 sine 50 vol 0.01'", "def say(self, data, lang): print 'Say ',data if (use_sound_play): voice", "tts_server.streaming): # cmd = 'play -n --no-show-progress -r 44100 -c1", "small chunks while (self.dorun): try: data = self.connection.recv(320) data =", "= 'cache'+str(self.idcache) self.idcache = (self.idcache+1)%10 tmpfile = \"/tmp/cache.wav\" ofile =", "-G --channels 1 -r 44100 -b 16 -t wav bip.wav", "sox') sys.exit(0) try: import alsaaudio except: print('alsaaudio required. Install with:", "None i = 0 while (i<3): #((not name in self.Sounds)", "\\'sysdefault\\']', default='sysdefault') args = parser.parse_args() tts_server = TTSServer(args.ttsport,args.device) asr_server =", "output_device): global use_alsaaudio, use_sound_play threading.Thread.__init__(self) # Initialize audio player self.streaming", "%s\" %self.output_device) self.aa_stream = None retry = 3 while retry>0:", "tts_server = TTSServer(args.ttsport,args.device) asr_server = ASRServer(args.asrport) tts_server.start() time.sleep(1) asr_server.start() run", "= self.sock.accept() self.connection.settimeout(3) # timeout when listening (exit with CTRL+C)", "self.Sounds = {} self.Sounds['bip'] = wave.open(SOUNDS_DIR+'bip.wav', 'rb') self.idcache = 0", "-= 1 time.sleep(2) self.audio_rate = 44100 self.periodsize = self.audio_rate /", "0.25 sine 400 # Voices # pico2wave -l \"it-IT\" -w", "self.aa_stream != None: self.aa_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.aa_stream.setchannels(1) self.aa_stream.setrate(self.audio_rate) self.aa_stream.setperiodsize(self.periodsize) def stop(self): self.dorun", "self.say('Audio server is running.', 'en') time.sleep(3) while (self.dorun): self.connect() try:", "= re.split('\\[|\\]',data) lang = vd[1] strsay = vd[2] self.say(strsay,lang) self.reply('OK')", "print \"File %s%s.wav not found.\" %(SOUNDS_DIR,name) time.sleep(1) i += 1", "asr_server import ASRServer SOUNDS_DIR = \"sounds/\" # dir with sounds", "data = soundfile.readframes(self.periodsize) # def playwav_pa(self, sfile): # global soundfile", "connection ...' # Wait for a connection self.connection, client_address =", "running on port \", port, \" ...\" self.dorun = True", "volume = 1.0 print 'Saying: %s' % data print 'Voice:", "= None asr_server = None def TTS_callback(in_data, frame_count, time_info, status):", "\"%s%s.wav\" %(SOUNDS_DIR, cachefile) cmd = 'rm %s %s' %(tmpfile, ofile)", "keep sound alive # os.system(cmd) except KeyboardInterrupt: print \"Exit\" run", "'Saying: %s' % data print 'Voice: %s' % voice print", "# Clean up the connection if (self.connection != None): self.connection.close()", "self.reply(bh) if bh!='': print('ASR sent [%s]' %bh) elif (data.startswith('SOUND')): self.play(data[6:])", "with: pip install --user pyalsaaudio') use_alsaaudio = False #sys.exit(0) from", "initializa audio interface') # Create a TCP/IP socket self.sock =", "retry = 0 except Exception as e: print(e) retry -=", "self.say('Audio server has been closed.', 'en') time.sleep(2) self.aa_stream = None", "(i<3): #((not name in self.Sounds) and (i<3)): try: soundfile =", "output_device_index = self.output_device) # soundfile = sfile # soundfile.setpos(0) #", "sound may not be played. # alsaaudio examples # https://larsimmisch.github.io/pyalsaaudio/libalsaaudio.html", "if (use_sound_play): os.system('roslaunch sound_play.launch &') time.sleep(5) rospy.init_node('sound_client', disable_signals=True) use_alsaaudio =", "required. Install with: pip install --user pyalsaaudio') use_alsaaudio = False", "connected = False while (self.dorun and not connected): try: #", "print 'TTS Server Connection closed.' # Clean up the connection", "!= None): self.connection.close() self.connection = None self.say('Audio server has been", "False self.output_device = output_device self.soundhandle = None m = platform.machine()", "= True try: from sound_play.msg import SoundRequest from sound_play.libsoundplay import", "= True print 'TTS Server Connection from ', client_address except:", "print('Playing %s ...' %name) soundfile = None i = 0", "self.soundhandle = None m = platform.machine() print \"Machine type:\" ,", "# print 'Waiting for a connection ...' # Wait for", "l in pp: print(' %s' %l) if (l[0:10]=='sysdefault'): print \"choose", "files to to 44100 Hz # Note: some initial sound", "convert audio files. # WAV generation # Synth # sox", "port, \" ...\" self.dorun = True self.connection = None #", "= 'voice_kal_diphone' volume = 1.0 print 'Saying: %s' % data", "self.sock.accept() self.connection.settimeout(3) # timeout when listening (exit with CTRL+C) connected", "...\" def reply(self,mstr): if (self.connection != None): try: mstr =", "self.stream = self.pa.open(format = 8, #self.pa.get_format_from_width(f.getsampwidth#()), # channels = 1,", "cmd = 'play -n --no-show-progress -r 44100 -c1 synth 0.1", "cachefile) cmd = 'rm %s %s' %(tmpfile, ofile) os.system(cmd) if", "rospy use_sound_play = False use_alsaaudio = True try: from sound_play.msg", "device used: %s\" %self.output_device) self.aa_stream = None retry = 3", "dB) #print('bip') #self.play('bip') #time.sleep(3) self.say('Hello!', 'en') self.say('Audio server is running.',", "= \"%s%s.wav\" %(SOUNDS_DIR, cachefile) cmd = 'rm %s %s' %(tmpfile,", "output = True, # stream_callback = TTS_callback, # output_device_index =", "self.stream.start_stream() # while self.stream.is_active(): # time.sleep(1.0) # self.stream.stop_stream() # self.stream.close()", "time.sleep(3) #if (not tts_server.streaming): # cmd = 'play -n --no-show-progress", "socket.SO_REUSEADDR, 1) self.sock.settimeout(3) # Bind the socket to the port", "%(lang,tmpfile, data) print cmd os.system(cmd) time.sleep(0.2) # convert samplerate tfm", "parser.add_argument('-device', type=str, help='audio device [default: \\'sysdefault\\']', default='sysdefault') args = parser.parse_args()", "Receive the data in small chunks while (self.dorun): try: data", "data.strip() except socket.timeout: data = \"***\" except: data = None", "'en-US' # default language strsay = data[4:] if (data[3]=='['): vd", "= True, # stream_callback = TTS_callback, # output_device_index = self.output_device)", "if (use_alsaaudio): print('Playing %s ...' %name) soundfile = None i", "print 'Waiting for a connection ...' # Wait for a", "not be played. # alsaaudio examples # https://larsimmisch.github.io/pyalsaaudio/libalsaaudio.html import threading", "socket import sys, os, platform import re import wave import", "Bind the socket to the port server_address = ('', port)", ", %s\"' %(lang,tmpfile, data) print cmd os.system(cmd) time.sleep(0.2) # convert", "+3 dB) #print('bip') #self.play('bip') #time.sleep(3) self.say('Hello!', 'en') self.say('Audio server is", "if (self.connection != None): try: mstr = mstr.encode('utf-8') self.connection.send(mstr+'\\n\\r') except:", "(use_sound_play): voice = 'voice_kal_diphone' volume = 1.0 print 'Saying: %s'", "# Wait for a connection self.connection, client_address = self.sock.accept() self.connection.settimeout(3)", "language strsay = data[4:] if (data[3]=='['): vd = re.split('\\[|\\]',data) lang", "#print('asr request') bh = asr_server.get_asr() self.reply(bh) if bh!='': print('ASR sent", "global soundfile # self.streaming = True # self.stream = self.pa.open(format", "1 if (soundfile != None and use_alsaaudio): #(name in self.Sounds):", "tts_server = None asr_server = None def TTS_callback(in_data, frame_count, time_info,", "44100 Hz # Note: some initial sound may not be", "retry>0: try: self.output_device='default' print(\"Audio device used: %s\" %self.output_device) self.aa_stream =", "try: # Receive the data in small chunks while (self.dorun):", "!=\"\" and data!=\"***\"): if data!=\"ASR\": print 'TTS Received [%s]' %", "True # self.stream = self.pa.open(format = 8, #self.pa.get_format_from_width(f.getsampwidth#()), # channels", "data = \"***\" except: data = None if (data!=None and", "retry -= 1 time.sleep(2) if self.aa_stream == None: retry =", "asr_server if (use_sound_play and self.soundhandle == None): self.soundhandle = SoundClient()", "self.connection = None # Dictionary of sounds self.Sounds = {}", "sent [%s]' %bh) elif (data.startswith('SOUND')): self.play(data[6:]) # play this sound", "for l in pp: print(' %s' %l) if (l[0:10]=='sysdefault'): print", "- Use audacity or sox to convert audio files. #", "else: print('Cannot initializa audio interface') # Create a TCP/IP socket", "mstr.encode('utf-8') self.connection.send(mstr+'\\n\\r') except: print('Connection closed') def setVolume(self,volperc): # volume in", "'cache'+str(self.idcache) self.idcache = (self.idcache+1)%10 tmpfile = \"/tmp/cache.wav\" ofile = \"%s%s.wav\"", "%(SOUNDS_DIR, cachefile) cmd = 'rm %s %s' %(tmpfile, ofile) os.system(cmd)", "use_alsaaudio = True try: from sound_play.msg import SoundRequest from sound_play.libsoundplay", "= platform.machine() print \"Machine type:\" , m if (m[0:3]=='arm'): use_sound_play", "print \"choose \",l self.output_device = l # choose default device", "%data) self.reply('ERR') elif (data == None or data==\"\"): break finally:", "(lang=='en'): lang = 'en-US' elif (len(lang)==2): lang = lang+'-'+lang.upper() time.sleep(0.2)", "parser = argparse.ArgumentParser(description='audio_server') parser.add_argument('-ttsport', type=int, help='TTS server port [default: 9001]',", "self.init_alsaaudio() else: print('Cannot initializa audio interface') # Create a TCP/IP", "stop(self): self.dorun = False def connect(self): connected = False while", "print(e) retry -= 1 time.sleep(2) self.audio_rate = 44100 self.periodsize =", "samplerate tfm = sox.Transformer() tfm.rate(samplerate=self.audio_rate) tfm.build(tmpfile, ofile) time.sleep(0.2) self.play(cachefile) else:", "parser.parse_args() tts_server = TTSServer(args.ttsport,args.device) asr_server = ASRServer(args.asrport) tts_server.start() time.sleep(1) asr_server.start()", "synth 0.25 sine 800 # sox -n --no-show-progress -G --channels", "0.01' # keep sound alive # os.system(cmd) except KeyboardInterrupt: print", "else: print('Message not understood: %s' %data) self.reply('ERR') elif (data ==", "%s' % data print 'Voice: %s' % voice print 'Volume:", "alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device) retry = 0 except Exception as e:", "%s' %l) if (l[0:10]=='sysdefault'): print \"choose \",l self.output_device = l", "self.connection, client_address = self.sock.accept() self.connection.settimeout(3) # timeout when listening (exit", "install ros-kinetic-audio-common libasound2') use_sound_play = False #sys.exit(0) try: import sox", "print('Cannot initializa audio interface') # Create a TCP/IP socket self.sock", "channels = 1, #f.getnchannels(), # rate = 44100, #f.getframerate(), #", "if (use_sound_play and self.soundhandle == None): self.soundhandle = SoundClient() time.sleep(3)", "# keep sound alive # os.system(cmd) except KeyboardInterrupt: print \"Exit\"", "os.system(cmdstr) def run(self): global asr_server if (use_sound_play and self.soundhandle ==", "self.reply('OK') elif (data==\"ASR\"): #print('asr request') bh = asr_server.get_asr() self.reply(bh) if", "-c1 synth 0.1 sine 50 vol 0.01' # keep sound", "import rospy use_sound_play = False use_alsaaudio = True try: from", "# self.stream.close() # self.streaming = False if __name__ == \"__main__\":", "tfm.rate(samplerate=self.audio_rate) tfm.build(tmpfile, ofile) time.sleep(0.2) self.play(cachefile) else: print('Cannot play audio. No", "800 # sox -n --no-show-progress -G --channels 1 -r 44100", "= (self.idcache+1)%10 tmpfile = \"/tmp/cache.wav\" ofile = \"%s%s.wav\" %(SOUNDS_DIR, cachefile)", "\"File %s%s.wav not found.\" %(SOUNDS_DIR,name) time.sleep(1) i += 1 if", "= 8, #self.pa.get_format_from_width(f.getsampwidth#()), # channels = 1, #f.getnchannels(), # rate", "port \", port, \" ...\" self.dorun = True self.connection =", "self.Sounds['bip'] = wave.open(SOUNDS_DIR+'bip.wav', 'rb') self.idcache = 0 def init_alsaaudio(self): print(\"Audio", "CTRL+C) connected = True print 'TTS Server Connection from ',", "time.sleep(1) asr_server.start() run = True while (run): try: time.sleep(3) #if", "!= None): try: mstr = mstr.encode('utf-8') self.connection.send(mstr+'\\n\\r') except: print('Connection closed')", "0 while (i<3): #((not name in self.Sounds) and (i<3)): try:", "-r 44100 -b 16 -t wav bip.wav synth 0.25 sine", "retry>0: try: self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device) retry = 0", "Received [%s]' % data if (data.startswith('TTS')): lang = 'en-US' #", "initial sound may not be played. # alsaaudio examples #", "44100 self.periodsize = self.audio_rate / 8 if self.aa_stream != None:", "tts_server.start() time.sleep(1) asr_server.start() run = True while (run): try: time.sleep(3)", "self.stream.stop_stream() # self.stream.close() # self.streaming = False if __name__ ==", "PCM %d%%' %volperc os.system(cmdstr) def run(self): global asr_server if (use_sound_play", "data[4:] if (data[3]=='['): vd = re.split('\\[|\\]',data) lang = vd[1] strsay", "def playwav_pa(self, sfile): # global soundfile # self.streaming = True", "examples # https://larsimmisch.github.io/pyalsaaudio/libalsaaudio.html import threading import time import socket import", "use_sound_play = False use_alsaaudio = True try: from sound_play.msg import", "= False use_alsaaudio = True try: from sound_play.msg import SoundRequest", "#self.play('bip') #time.sleep(3) self.say('Hello!', 'en') self.say('Audio server is running.', 'en') time.sleep(3)", "socket.timeout: data = \"***\" except: data = None if (data!=None", "voice = 'voice_kal_diphone' volume = 1.0 print 'Saying: %s' %", "None and use_alsaaudio): #(name in self.Sounds): self.playwav_aa(soundfile) print('Play completed.') def", "back to the client' #self.connection.sendall(\"OK\") else: print('Message not understood: %s'", "% data print 'Voice: %s' % voice print 'Volume: %s'", "= l # choose default device break print(\"Audio device used:", "Connection from ', client_address except: pass #print \"Listen again ...\"", "= False #sys.exit(0) from asr_server import ASRServer SOUNDS_DIR = \"sounds/\"", "start.wav \"Bene! Si Parte!\" # Then convert wav files to", "True print 'TTS Server Connection from ', client_address except: pass", "self.say('Hello!', 'en') self.say('Audio server is running.', 'en') time.sleep(3) while (self.dorun):", "return (data, pyaudio.paContinue) class TTSServer(threading.Thread): def __init__(self, port, output_device): global", "break print(\"Audio device used: %s\" %self.output_device) self.aa_stream = None retry", "= soundfile.readframes(frame_count) return (data, pyaudio.paContinue) class TTSServer(threading.Thread): def __init__(self, port,", "use_alsaaudio): #(name in self.Sounds): self.playwav_aa(soundfile) print('Play completed.') def playwav_aa(self, soundfile):", "Connection closed.' # Clean up the connection if (self.connection !=", "time.sleep(0.2) # convert samplerate tfm = sox.Transformer() tfm.rate(samplerate=self.audio_rate) tfm.build(tmpfile, ofile)", "False #sys.exit(0) try: import sox except: print('sox required. Install with:", "when listening (exit with CTRL+C) connected = True print 'TTS", "data = self.connection.recv(320) data = data.strip() except socket.timeout: data =", "(use_alsaaudio): print('Playing %s ...' %name) soundfile = None i =", "= self.pa.open(format = 8, #self.pa.get_format_from_width(f.getsampwidth#()), # channels = 1, #f.getnchannels(),", "elif (data==\"ASR\"): #print('asr request') bh = asr_server.get_asr() self.reply(bh) if bh!='':", "0 except Exception as e: print(e) retry -= 1 time.sleep(2)", "os.system(cmd) time.sleep(0.2) # convert samplerate tfm = sox.Transformer() tfm.rate(samplerate=self.audio_rate) tfm.build(tmpfile,", "# Voices # pico2wave -l \"it-IT\" -w start.wav \"Bene! Si", "(use_alsaaudio): cachefile = 'cache'+str(self.idcache) self.idcache = (self.idcache+1)%10 tmpfile = \"/tmp/cache.wav\"", "None m = platform.machine() print \"Machine type:\" , m if", "= None i = 0 while (i<3): #((not name in", "connected = True print 'TTS Server Connection from ', client_address", "available.') def play(self, name): if (use_alsaaudio): print('Playing %s ...' %name)", "time_info, status): global soundfile if (soundfile==None): return (None, True) else:", "--user pyalsaaudio') use_alsaaudio = False #sys.exit(0) from asr_server import ASRServer", "parser.add_argument('-asrport', type=int, help='ASR server port [default: 9002]', default=9002) parser.add_argument('-device', type=str,", "self.dorun = True self.connection = None # Dictionary of sounds", "connected): try: # print 'Waiting for a connection ...' #", "convert samplerate tfm = sox.Transformer() tfm.rate(samplerate=self.audio_rate) tfm.build(tmpfile, ofile) time.sleep(0.2) self.play(cachefile)", "None # sound file tts_server = None asr_server = None", "some initial sound may not be played. # alsaaudio examples", "def connect(self): connected = False while (self.dorun and not connected):", "a connection ...' # Wait for a connection self.connection, client_address", "if (data!=None and data !=\"\" and data!=\"***\"): if data!=\"ASR\": print", "(self.dorun): self.connect() try: # Receive the data in small chunks", "&') time.sleep(5) rospy.init_node('sound_client', disable_signals=True) use_alsaaudio = False elif (use_alsaaudio): self.init_alsaaudio()", "self.sock.bind(server_address) self.sock.listen(1) print \"TTS Server running on port \", port,", "#time.sleep(3) self.say('Hello!', 'en') self.say('Audio server is running.', 'en') time.sleep(3) while", "asr_server.start() run = True while (run): try: time.sleep(3) #if (not", "Synth # sox -n --no-show-progress -G --channels 1 -r 44100", "tmpfile = \"/tmp/cache.wav\" ofile = \"%s%s.wav\" %(SOUNDS_DIR, cachefile) cmd =", "time.sleep(0.2) cmd = 'pico2wave -l \"%s\" -w %s \" ,", "%(len(data))) if self.aa_stream != None: self.aa_stream.write(data) data = soundfile.readframes(self.periodsize) #", "print 'Saying: %s' % data print 'Voice: %s' % voice", "use_alsaaudio = False #sys.exit(0) from asr_server import ASRServer SOUNDS_DIR =", "self.output_device='default' print(\"Audio device used: %s\" %self.output_device) self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL,", "in percentag [0-100] cmdstr = 'amixer set PCM %d%%' %volperc", "import SoundRequest from sound_play.libsoundplay import SoundClient except: print('ROS package sound_play", "while (len(data)>0): # print('stream data %d' %(len(data))) if self.aa_stream !=", "use_alsaaudio, use_sound_play threading.Thread.__init__(self) # Initialize audio player self.streaming = False", "e: print(e) retry -= 1 time.sleep(2) self.audio_rate = 44100 self.periodsize", "-n --no-show-progress -r 44100 -c1 synth 0.1 sine 50 vol", "sine 50 vol 0.01' # keep sound alive # os.system(cmd)", "# Bind the socket to the port server_address = ('',", "pp: print(' %s' %l) if (l[0:10]=='sysdefault'): print \"choose \",l self.output_device", "= \"/tmp/cache.wav\" ofile = \"%s%s.wav\" %(SOUNDS_DIR, cachefile) cmd = 'rm", "8, #self.pa.get_format_from_width(f.getsampwidth#()), # channels = 1, #f.getnchannels(), # rate =", "played. # alsaaudio examples # https://larsimmisch.github.io/pyalsaaudio/libalsaaudio.html import threading import time", "if data!=\"ASR\": print 'TTS Received [%s]' % data if (data.startswith('TTS')):", "vd[2] self.say(strsay,lang) self.reply('OK') elif (data==\"ASR\"): #print('asr request') bh = asr_server.get_asr()", "try: import alsaaudio except: print('alsaaudio required. Install with: pip install", "audio interface') # Create a TCP/IP socket self.sock = socket.socket(socket.AF_INET,", "play(self, name): if (use_alsaaudio): print('Playing %s ...' %name) soundfile =", "else: data = soundfile.readframes(frame_count) return (data, pyaudio.paContinue) class TTSServer(threading.Thread): def", "def play(self, name): if (use_alsaaudio): print('Playing %s ...' %name) soundfile", "connection self.connection, client_address = self.sock.accept() self.connection.settimeout(3) # timeout when listening", "import wave import argparse import rospy use_sound_play = False use_alsaaudio", "reply(self,mstr): if (self.connection != None): try: mstr = mstr.encode('utf-8') self.connection.send(mstr+'\\n\\r')", "0.1 sine 50 vol 0.01' # keep sound alive #", "from asr_server import ASRServer SOUNDS_DIR = \"sounds/\" # dir with", "44100, #f.getframerate(), # output = True, # stream_callback = TTS_callback,", "= False if (use_sound_play): os.system('roslaunch sound_play.launch &') time.sleep(5) rospy.init_node('sound_client', disable_signals=True)", "= False elif (use_alsaaudio): self.init_alsaaudio() else: print('Cannot initializa audio interface')", "except: print('Connection closed') def setVolume(self,volperc): # volume in percentag [0-100]", "soundfile.readframes(self.periodsize) # def playwav_pa(self, sfile): # global soundfile # self.streaming", "import SoundClient except: print('ROS package sound_play required.') print('Install with: sudo", "# global soundfile # self.streaming = True # self.stream =", "to the client' #self.connection.sendall(\"OK\") else: print('Message not understood: %s' %data)", "== None or data==\"\"): break finally: print 'TTS Server Connection", "print 'Volume: %s' % volume self.soundhandle.say(data, voice, volume) rospy.sleep(3) elif", "socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.settimeout(3) # Bind the socket to", "'pico2wave -l \"%s\" -w %s \" , %s\"' %(lang,tmpfile, data)", "\"%s\" -w %s \" , %s\"' %(lang,tmpfile, data) print cmd", "= self.output_device) # soundfile = sfile # soundfile.setpos(0) # self.stream.start_stream()", "try: from sound_play.msg import SoundRequest from sound_play.libsoundplay import SoundClient except:", "#(name in self.Sounds): self.playwav_aa(soundfile) print('Play completed.') def playwav_aa(self, soundfile): soundfile.setpos(0)", "TTS_callback, # output_device_index = self.output_device) # soundfile = sfile #", "8 if self.aa_stream != None: self.aa_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.aa_stream.setchannels(1) self.aa_stream.setrate(self.audio_rate) self.aa_stream.setperiodsize(self.periodsize) def", "soundfile.readframes(frame_count) return (data, pyaudio.paContinue) class TTSServer(threading.Thread): def __init__(self, port, output_device):", "= output_device self.soundhandle = None m = platform.machine() print \"Machine", "re import wave import argparse import rospy use_sound_play = False", "self.sock.settimeout(3) # Bind the socket to the port server_address =", "with: sudo apt-get install ros-kinetic-audio-common libasound2') use_sound_play = False #sys.exit(0)", "stream_callback = TTS_callback, # output_device_index = self.output_device) # soundfile =", "sound_play.launch &') time.sleep(5) rospy.init_node('sound_client', disable_signals=True) use_alsaaudio = False elif (use_alsaaudio):", "--no-show-progress -G --channels 1 -r 44100 -b 16 -t wav", "pip install --user pyalsaaudio') use_alsaaudio = False #sys.exit(0) from asr_server", "bit wav 44100 Hz - Use audacity or sox to", "self.dorun = False def connect(self): connected = False while (self.dorun", "self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.settimeout(3) # Bind the socket to the", "timeout when listening (exit with CTRL+C) connected = True print", "except: pass #print \"Listen again ...\" def reply(self,mstr): if (self.connection", "import threading import time import socket import sys, os, platform", "!= None: self.aa_stream.write(data) data = soundfile.readframes(self.periodsize) # def playwav_pa(self, sfile):", "'en') time.sleep(3) while (self.dorun): self.connect() try: # Receive the data", "except: print \"File %s%s.wav not found.\" %(SOUNDS_DIR,name) time.sleep(1) i +=", "50 vol 0.01' # keep sound alive # os.system(cmd) except", "chunks while (self.dorun): try: data = self.connection.recv(320) data = data.strip()", "None or data==\"\"): break finally: print 'TTS Server Connection closed.'", "data print 'Voice: %s' % voice print 'Volume: %s' %", "#print('bip') #self.play('bip') #time.sleep(3) self.say('Hello!', 'en') self.say('Audio server is running.', 'en')", "self.connect() try: # Receive the data in small chunks while", "try: data = self.connection.recv(320) data = data.strip() except socket.timeout: data", "#sys.exit(0) try: import sox except: print('sox required. Install with: pip", "threading import time import socket import sys, os, platform import", "while (self.dorun): self.connect() try: # Receive the data in small", "elif (data.startswith('SOUND')): self.play(data[6:]) # play this sound self.reply('OK') #print 'sending", "= False #sys.exit(0) try: import sox except: print('sox required. Install", "sfile # soundfile.setpos(0) # self.stream.start_stream() # while self.stream.is_active(): # time.sleep(1.0)", "parser.add_argument('-ttsport', type=int, help='TTS server port [default: 9001]', default=9001) parser.add_argument('-asrport', type=int,", "except: print('alsaaudio required. Install with: pip install --user pyalsaaudio') use_alsaaudio", "def run(self): global asr_server if (use_sound_play and self.soundhandle == None):", "asr_server = ASRServer(args.asrport) tts_server.start() time.sleep(1) asr_server.start() run = True while", "type:\" , m if (m[0:3]=='arm'): use_sound_play = False if (use_sound_play):", "== None): self.soundhandle = SoundClient() time.sleep(3) self.setVolume(99) # set volume", "-t wav bip.wav synth 0.25 sine 800 # sox -n", "1, #f.getnchannels(), # rate = 44100, #f.getframerate(), # output =", "this sound self.reply('OK') #print 'sending data back to the client'", "# play this sound self.reply('OK') #print 'sending data back to", "# stream_callback = TTS_callback, # output_device_index = self.output_device) # soundfile", "from sound_play.libsoundplay import SoundClient except: print('ROS package sound_play required.') print('Install", "Note: some initial sound may not be played. # alsaaudio", "strsay = data[4:] if (data[3]=='['): vd = re.split('\\[|\\]',data) lang =", "None: self.aa_stream.write(data) data = soundfile.readframes(self.periodsize) # def playwav_pa(self, sfile): #", "self.aa_stream.write(data) data = soundfile.readframes(self.periodsize) # def playwav_pa(self, sfile): # global", "= False self.output_device = output_device self.soundhandle = None m =", "sine 400 # Voices # pico2wave -l \"it-IT\" -w start.wav", "m if (m[0:3]=='arm'): use_sound_play = False if (use_sound_play): os.system('roslaunch sound_play.launch", "-w %s \" , %s\"' %(lang,tmpfile, data) print cmd os.system(cmd)", "%s%s.wav not found.\" %(SOUNDS_DIR,name) time.sleep(1) i += 1 if (soundfile", "9001]', default=9001) parser.add_argument('-asrport', type=int, help='ASR server port [default: 9002]', default=9002)", "closed.' # Clean up the connection if (self.connection != None):", "pass #print \"Listen again ...\" def reply(self,mstr): if (self.connection !=", "asr_server.get_asr() self.reply(bh) if bh!='': print('ASR sent [%s]' %bh) elif (data.startswith('SOUND')):", "(use_sound_play): os.system('roslaunch sound_play.launch &') time.sleep(5) rospy.init_node('sound_client', disable_signals=True) use_alsaaudio = False", "__init__(self, port, output_device): global use_alsaaudio, use_sound_play threading.Thread.__init__(self) # Initialize audio", "print('stream data %d' %(len(data))) if self.aa_stream != None: self.aa_stream.write(data) data", "except KeyboardInterrupt: print \"Exit\" run = False tts_server.stop() asr_server.stop() sys.exit(0)", "False elif (use_alsaaudio): self.init_alsaaudio() else: print('Cannot initializa audio interface') #", "elif (len(lang)==2): lang = lang+'-'+lang.upper() time.sleep(0.2) cmd = 'pico2wave -l", "a connection self.connection, client_address = self.sock.accept() self.connection.settimeout(3) # timeout when", "port, output_device): global use_alsaaudio, use_sound_play threading.Thread.__init__(self) # Initialize audio player", "# timeout when listening (exit with CTRL+C) connected = True", "self.soundhandle.say(data, voice, volume) rospy.sleep(3) elif (use_alsaaudio): cachefile = 'cache'+str(self.idcache) self.idcache", "import re import wave import argparse import rospy use_sound_play =", "volume) rospy.sleep(3) elif (use_alsaaudio): cachefile = 'cache'+str(self.idcache) self.idcache = (self.idcache+1)%10", "# self.streaming = True # self.stream = self.pa.open(format = 8,", "Exception as e: print(e) retry -= 1 time.sleep(2) self.audio_rate =", "convert wav files to to 44100 Hz # Note: some", "name for l in pp: print(' %s' %l) if (l[0:10]=='sysdefault'):", "data back to the client' #self.connection.sendall(\"OK\") else: print('Message not understood:", "44100 Hz - Use audacity or sox to convert audio", "ofile) os.system(cmd) if (lang=='en'): lang = 'en-US' elif (len(lang)==2): lang", "= ASRServer(args.asrport) tts_server.start() time.sleep(1) asr_server.start() run = True while (run):", "...\" self.dorun = True self.connection = None # Dictionary of", "if (self.output_device=='sysdefault'): # select proper sysdefault name for l in", "data = data.strip() except socket.timeout: data = \"***\" except: data", "%d%%' %volperc os.system(cmdstr) def run(self): global asr_server if (use_sound_play and", "(len(lang)==2): lang = lang+'-'+lang.upper() time.sleep(0.2) cmd = 'pico2wave -l \"%s\"", "found.\" %(SOUNDS_DIR,name) time.sleep(1) i += 1 if (soundfile != None", "Then convert wav files to to 44100 Hz # Note:", "44100 -b 16 -t wav bip.wav synth 0.25 sine 800", "= 'pico2wave -l \"%s\" -w %s \" , %s\"' %(lang,tmpfile,", "(soundfile==None): return (None, True) else: data = soundfile.readframes(frame_count) return (data,", "\"Machine type:\" , m if (m[0:3]=='arm'): use_sound_play = False if", "= None # sound file tts_server = None asr_server =", "voice print 'Volume: %s' % volume self.soundhandle.say(data, voice, volume) rospy.sleep(3)", "= False if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='audio_server') parser.add_argument('-ttsport',", "1 -r 44100 -b 16 -t wav bip.wav synth 0.25", "= socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.settimeout(3) # Bind the", "time.sleep(2) self.audio_rate = 44100 self.periodsize = self.audio_rate / 8 if", "Server Connection from ', client_address except: pass #print \"Listen again", "soundfile = wave.open(SOUNDS_DIR+name+\".wav\", 'rb') #self.Sounds[name] = soundfile except: print \"File", "rospy.sleep(3) elif (use_alsaaudio): cachefile = 'cache'+str(self.idcache) self.idcache = (self.idcache+1)%10 tmpfile", "playwav_pa(self, sfile): # global soundfile # self.streaming = True #", "%l) if (l[0:10]=='sysdefault'): print \"choose \",l self.output_device = l #", "time.sleep(5) rospy.init_node('sound_client', disable_signals=True) use_alsaaudio = False elif (use_alsaaudio): self.init_alsaaudio() else:", "and data!=\"***\"): if data!=\"ASR\": print 'TTS Received [%s]' % data", "help='ASR server port [default: 9002]', default=9002) parser.add_argument('-device', type=str, help='audio device", "data = None if (data!=None and data !=\"\" and data!=\"***\"):", "%d' %(len(data))) if self.aa_stream != None: self.aa_stream.write(data) data = soundfile.readframes(self.periodsize)", "soundfile.setpos(0) # self.stream.start_stream() # while self.stream.is_active(): # time.sleep(1.0) # self.stream.stop_stream()", "is running.', 'en') time.sleep(3) while (self.dorun): self.connect() try: # Receive", "import sox except: print('sox required. Install with: pip install --user", "ros-kinetic-audio-common libasound2') use_sound_play = False #sys.exit(0) try: import sox except:", "percentag [0-100] cmdstr = 'amixer set PCM %d%%' %volperc os.system(cmdstr)", "# dir with sounds soundfile = None # sound file", "# self.stream.start_stream() # while self.stream.is_active(): # time.sleep(1.0) # self.stream.stop_stream() #", "os.system(cmd) except KeyboardInterrupt: print \"Exit\" run = False tts_server.stop() asr_server.stop()", "pyaudio.paContinue) class TTSServer(threading.Thread): def __init__(self, port, output_device): global use_alsaaudio, use_sound_play", "= \"***\" except: data = None if (data!=None and data", "lang = 'en-US' # default language strsay = data[4:] if", "No infrastructure available.') def play(self, name): if (use_alsaaudio): print('Playing %s", "1.0 print 'Saying: %s' % data print 'Voice: %s' %", "soundfile = None i = 0 while (i<3): #((not name", "sox.Transformer() tfm.rate(samplerate=self.audio_rate) tfm.build(tmpfile, ofile) time.sleep(0.2) self.play(cachefile) else: print('Cannot play audio.", "i += 1 if (soundfile != None and use_alsaaudio): #(name", "Install with: pip install --user sox') sys.exit(0) try: import alsaaudio", "self.streaming = False if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='audio_server')", "except socket.timeout: data = \"***\" except: data = None if", "try: time.sleep(3) #if (not tts_server.streaming): # cmd = 'play -n", "False def connect(self): connected = False while (self.dorun and not", "cmdstr = 'amixer set PCM %d%%' %volperc os.system(cmdstr) def run(self):", "'amixer set PCM %d%%' %volperc os.system(cmdstr) def run(self): global asr_server", "print('alsaaudio required. Install with: pip install --user pyalsaaudio') use_alsaaudio =", "sox -n --no-show-progress -G --channels 1 -r 44100 -b 16", "= False def connect(self): connected = False while (self.dorun and", "and (i<3)): try: soundfile = wave.open(SOUNDS_DIR+name+\".wav\", 'rb') #self.Sounds[name] = soundfile", "#self.Sounds[name] = soundfile except: print \"File %s%s.wav not found.\" %(SOUNDS_DIR,name)", "global use_alsaaudio, use_sound_play threading.Thread.__init__(self) # Initialize audio player self.streaming =", "self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.settimeout(3) # Bind", "try: self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device) retry = 0 except", "data = soundfile.readframes(self.periodsize) while (len(data)>0): # print('stream data %d' %(len(data)))", "self.soundhandle == None): self.soundhandle = SoundClient() time.sleep(3) self.setVolume(99) # set", "3 while retry>0: try: self.output_device='default' print(\"Audio device used: %s\" %self.output_device)", "device [default: \\'sysdefault\\']', default='sysdefault') args = parser.parse_args() tts_server = TTSServer(args.ttsport,args.device)", "break finally: print 'TTS Server Connection closed.' # Clean up", "= True while (run): try: time.sleep(3) #if (not tts_server.streaming): #", "None def say(self, data, lang): print 'Say ',data if (use_sound_play):", "soundfile if (soundfile==None): return (None, True) else: data = soundfile.readframes(frame_count)", "may not be played. # alsaaudio examples # https://larsimmisch.github.io/pyalsaaudio/libalsaaudio.html import", "or data==\"\"): break finally: print 'TTS Server Connection closed.' #", "from sound_play.msg import SoundRequest from sound_play.libsoundplay import SoundClient except: print('ROS", "= 44100, #f.getframerate(), # output = True, # stream_callback =", "'voice_kal_diphone' volume = 1.0 print 'Saying: %s' % data print", "libasound2') use_sound_play = False #sys.exit(0) try: import sox except: print('sox", "if (m[0:3]=='arm'): use_sound_play = False if (use_sound_play): os.system('roslaunch sound_play.launch &')", "alsaaudio except: print('alsaaudio required. Install with: pip install --user pyalsaaudio')", "= True self.connection = None # Dictionary of sounds self.Sounds", "the data in small chunks while (self.dorun): try: data =", "asr_server = None def TTS_callback(in_data, frame_count, time_info, status): global soundfile", "# channels = 1, #f.getnchannels(), # rate = 44100, #f.getframerate(),", "(data, pyaudio.paContinue) class TTSServer(threading.Thread): def __init__(self, port, output_device): global use_alsaaudio,", "%s\"' %(lang,tmpfile, data) print cmd os.system(cmd) time.sleep(0.2) # convert samplerate", "print 'TTS Server Connection from ', client_address except: pass #print", "self.stream.close() # self.streaming = False if __name__ == \"__main__\": parser", "None if (data!=None and data !=\"\" and data!=\"***\"): if data!=\"ASR\":", "0.25 sine 800 # sox -n --no-show-progress -G --channels 1", "pp = alsaaudio.pcms() if (self.output_device=='sysdefault'): # select proper sysdefault name", "',data if (use_sound_play): voice = 'voice_kal_diphone' volume = 1.0 print", "output_device self.soundhandle = None m = platform.machine() print \"Machine type:\"", "('', port) self.sock.bind(server_address) self.sock.listen(1) print \"TTS Server running on port", "bh = asr_server.get_asr() self.reply(bh) if bh!='': print('ASR sent [%s]' %bh)", "print('Message not understood: %s' %data) self.reply('ERR') elif (data == None", "volume self.soundhandle.say(data, voice, volume) rospy.sleep(3) elif (use_alsaaudio): cachefile = 'cache'+str(self.idcache)", "# print('stream data %d' %(len(data))) if self.aa_stream != None: self.aa_stream.write(data)", "Exception as e: print(e) retry -= 1 time.sleep(2) if self.aa_stream", "in small chunks while (self.dorun): try: data = self.connection.recv(320) data", "while (run): try: time.sleep(3) #if (not tts_server.streaming): # cmd =", "to 44100 Hz # Note: some initial sound may not", "--user sox') sys.exit(0) try: import alsaaudio except: print('alsaaudio required. Install", "False if (use_sound_play): os.system('roslaunch sound_play.launch &') time.sleep(5) rospy.init_node('sound_client', disable_signals=True) use_alsaaudio", "data!=\"ASR\": print 'TTS Received [%s]' % data if (data.startswith('TTS')): lang", "elif (data == None or data==\"\"): break finally: print 'TTS", "soundfile = sfile # soundfile.setpos(0) # self.stream.start_stream() # while self.stream.is_active():", "None def TTS_callback(in_data, frame_count, time_info, status): global soundfile if (soundfile==None):", "print(\"Audio devices available\") pp = alsaaudio.pcms() if (self.output_device=='sysdefault'): # select", "% volume self.soundhandle.say(data, voice, volume) rospy.sleep(3) elif (use_alsaaudio): cachefile =", "# rate = 44100, #f.getframerate(), # output = True, #", "self.soundhandle = SoundClient() time.sleep(3) self.setVolume(99) # set volume (99% =", "def setVolume(self,volperc): # volume in percentag [0-100] cmdstr = 'amixer", "request') bh = asr_server.get_asr() self.reply(bh) if bh!='': print('ASR sent [%s]'", "% data if (data.startswith('TTS')): lang = 'en-US' # default language", "(use_alsaaudio): self.init_alsaaudio() else: print('Cannot initializa audio interface') # Create a", "data, lang): print 'Say ',data if (use_sound_play): voice = 'voice_kal_diphone'", "self.pa.open(format = 8, #self.pa.get_format_from_width(f.getsampwidth#()), # channels = 1, #f.getnchannels(), #", "SoundClient except: print('ROS package sound_play required.') print('Install with: sudo apt-get", "except: print('sox required. Install with: pip install --user sox') sys.exit(0)", "running.', 'en') time.sleep(3) while (self.dorun): self.connect() try: # Receive the", "args = parser.parse_args() tts_server = TTSServer(args.ttsport,args.device) asr_server = ASRServer(args.asrport) tts_server.start()", "with: pip install --user sox') sys.exit(0) try: import alsaaudio except:", "wav bip.wav synth 0.25 sine 800 # sox -n --no-show-progress", "True self.connection = None # Dictionary of sounds self.Sounds =", "type=int, help='TTS server port [default: 9001]', default=9001) parser.add_argument('-asrport', type=int, help='ASR", "[0-100] cmdstr = 'amixer set PCM %d%%' %volperc os.system(cmdstr) def", "server port [default: 9001]', default=9001) parser.add_argument('-asrport', type=int, help='ASR server port", "print 'Voice: %s' % voice print 'Volume: %s' % volume", "time.sleep(2) self.aa_stream = None def say(self, data, lang): print 'Say", "self.aa_stream = None def say(self, data, lang): print 'Say ',data", "def __init__(self, port, output_device): global use_alsaaudio, use_sound_play threading.Thread.__init__(self) # Initialize", "def reply(self,mstr): if (self.connection != None): try: mstr = mstr.encode('utf-8')", "soundfile # self.streaming = True # self.stream = self.pa.open(format =", "(use_sound_play and self.soundhandle == None): self.soundhandle = SoundClient() time.sleep(3) self.setVolume(99)", "m = platform.machine() print \"Machine type:\" , m if (m[0:3]=='arm'):", "client_address = self.sock.accept() self.connection.settimeout(3) # timeout when listening (exit with", "finally: print 'TTS Server Connection closed.' # Clean up the", "default=9002) parser.add_argument('-device', type=str, help='audio device [default: \\'sysdefault\\']', default='sysdefault') args =", "Voices # pico2wave -l \"it-IT\" -w start.wav \"Bene! Si Parte!\"", "closed.', 'en') time.sleep(2) self.aa_stream = None def say(self, data, lang):", "\" ...\" self.dorun = True self.connection = None # Dictionary", "ofile = \"%s%s.wav\" %(SOUNDS_DIR, cachefile) cmd = 'rm %s %s'", "%s ...' %name) soundfile = None i = 0 while", "#self.pa.get_format_from_width(f.getsampwidth#()), # channels = 1, #f.getnchannels(), # rate = 44100,", "44100 -c1 synth 0.1 sine 50 vol 0.01' # keep", "alsaaudio.pcms() if (self.output_device=='sysdefault'): # select proper sysdefault name for l", "def stop(self): self.dorun = False def connect(self): connected = False", "= None self.say('Audio server has been closed.', 'en') time.sleep(2) self.aa_stream", "self.Sounds): self.playwav_aa(soundfile) print('Play completed.') def playwav_aa(self, soundfile): soundfile.setpos(0) data =", "= None def say(self, data, lang): print 'Say ',data if", "port) self.sock.bind(server_address) self.sock.listen(1) print \"TTS Server running on port \",", "self.play(cachefile) else: print('Cannot play audio. No infrastructure available.') def play(self,", "device break print(\"Audio device used: %s\" %self.output_device) self.aa_stream = None", "and not connected): try: # print 'Waiting for a connection", "global asr_server if (use_sound_play and self.soundhandle == None): self.soundhandle =", "-G --channels 1 -r 44100 -b 16 -t wav bop.wav", "available\") pp = alsaaudio.pcms() if (self.output_device=='sysdefault'): # select proper sysdefault", "1) self.sock.settimeout(3) # Bind the socket to the port server_address", "%s' % voice print 'Volume: %s' % volume self.soundhandle.say(data, voice,", "(data!=None and data !=\"\" and data!=\"***\"): if data!=\"ASR\": print 'TTS", "time.sleep(3) while (self.dorun): self.connect() try: # Receive the data in", "print 'Say ',data if (use_sound_play): voice = 'voice_kal_diphone' volume =", "not understood: %s' %data) self.reply('ERR') elif (data == None or", "None retry = 3 while retry>0: try: self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK,", "Hz - Use audacity or sox to convert audio files.", "<reponame>artigianitecnologici/marrtino_apps<gh_stars>0 # Only PCM 16 bit wav 44100 Hz -", "package sound_play required.') print('Install with: sudo apt-get install ros-kinetic-audio-common libasound2')", "= vd[2] self.say(strsay,lang) self.reply('OK') elif (data==\"ASR\"): #print('asr request') bh =", "lang = 'en-US' elif (len(lang)==2): lang = lang+'-'+lang.upper() time.sleep(0.2) cmd", "lang = vd[1] strsay = vd[2] self.say(strsay,lang) self.reply('OK') elif (data==\"ASR\"):", "# output_device_index = self.output_device) # soundfile = sfile # soundfile.setpos(0)", "with CTRL+C) connected = True print 'TTS Server Connection from", "\"sounds/\" # dir with sounds soundfile = None # sound", "and self.soundhandle == None): self.soundhandle = SoundClient() time.sleep(3) self.setVolume(99) #", "(data == None or data==\"\"): break finally: print 'TTS Server", "wave.open(SOUNDS_DIR+'bip.wav', 'rb') self.idcache = 0 def init_alsaaudio(self): print(\"Audio devices available\")", "# default language strsay = data[4:] if (data[3]=='['): vd =", "tfm = sox.Transformer() tfm.rate(samplerate=self.audio_rate) tfm.build(tmpfile, ofile) time.sleep(0.2) self.play(cachefile) else: print('Cannot", "None # Dictionary of sounds self.Sounds = {} self.Sounds['bip'] =", "%s' %(tmpfile, ofile) os.system(cmd) if (lang=='en'): lang = 'en-US' elif", "= {} self.Sounds['bip'] = wave.open(SOUNDS_DIR+'bip.wav', 'rb') self.idcache = 0 def", "400 # Voices # pico2wave -l \"it-IT\" -w start.wav \"Bene!", "data = soundfile.readframes(frame_count) return (data, pyaudio.paContinue) class TTSServer(threading.Thread): def __init__(self,", "[default: 9001]', default=9001) parser.add_argument('-asrport', type=int, help='ASR server port [default: 9002]',", "TCP/IP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.settimeout(3)", "socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.settimeout(3) #", "self.audio_rate / 8 if self.aa_stream != None: self.aa_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE) self.aa_stream.setchannels(1) self.aa_stream.setrate(self.audio_rate)", "(self.idcache+1)%10 tmpfile = \"/tmp/cache.wav\" ofile = \"%s%s.wav\" %(SOUNDS_DIR, cachefile) cmd", "'en-US' elif (len(lang)==2): lang = lang+'-'+lang.upper() time.sleep(0.2) cmd = 'pico2wave", "'play -n --no-show-progress -r 44100 -c1 synth 0.1 sine 50", "16 -t wav bop.wav synth 0.25 sine 400 # Voices", "self.streaming = True # self.stream = self.pa.open(format = 8, #self.pa.get_format_from_width(f.getsampwidth#()),", "class TTSServer(threading.Thread): def __init__(self, port, output_device): global use_alsaaudio, use_sound_play threading.Thread.__init__(self)", "apt-get install ros-kinetic-audio-common libasound2') use_sound_play = False #sys.exit(0) try: import", "self.output_device = l # choose default device break print(\"Audio device", "# volume in percentag [0-100] cmdstr = 'amixer set PCM", "print('ROS package sound_play required.') print('Install with: sudo apt-get install ros-kinetic-audio-common", "rospy.init_node('sound_client', disable_signals=True) use_alsaaudio = False elif (use_alsaaudio): self.init_alsaaudio() else: print('Cannot", "'en') self.say('Audio server is running.', 'en') time.sleep(3) while (self.dorun): self.connect()", "not connected): try: # print 'Waiting for a connection ...'", "# Then convert wav files to to 44100 Hz #", "except: print('ROS package sound_play required.') print('Install with: sudo apt-get install", "sysdefault name for l in pp: print(' %s' %l) if", "sox to convert audio files. # WAV generation # Synth", "'Waiting for a connection ...' # Wait for a connection", "self.aa_stream.setchannels(1) self.aa_stream.setrate(self.audio_rate) self.aa_stream.setperiodsize(self.periodsize) def stop(self): self.dorun = False def connect(self):", "sys.exit(0) try: import alsaaudio except: print('alsaaudio required. Install with: pip", "%s %s' %(tmpfile, ofile) os.system(cmd) if (lang=='en'): lang = 'en-US'", "self.sock.listen(1) print \"TTS Server running on port \", port, \"", "frame_count, time_info, status): global soundfile if (soundfile==None): return (None, True)", "self.audio_rate = 44100 self.periodsize = self.audio_rate / 8 if self.aa_stream", "\"__main__\": parser = argparse.ArgumentParser(description='audio_server') parser.add_argument('-ttsport', type=int, help='TTS server port [default:", "= 3 while retry>0: try: self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device)", "strsay = vd[2] self.say(strsay,lang) self.reply('OK') elif (data==\"ASR\"): #print('asr request') bh", "pip install --user sox') sys.exit(0) try: import alsaaudio except: print('alsaaudio", "the port server_address = ('', port) self.sock.bind(server_address) self.sock.listen(1) print \"TTS", "-n --no-show-progress -G --channels 1 -r 44100 -b 16 -t", "def TTS_callback(in_data, frame_count, time_info, status): global soundfile if (soundfile==None): return", "argparse import rospy use_sound_play = False use_alsaaudio = True try:", "file tts_server = None asr_server = None def TTS_callback(in_data, frame_count,", "except Exception as e: print(e) retry -= 1 time.sleep(2) self.audio_rate", "self.aa_stream = None retry = 3 while retry>0: try: self.aa_stream", "= False while (self.dorun and not connected): try: # print", "self.periodsize = self.audio_rate / 8 if self.aa_stream != None: self.aa_stream.setformat(alsaaudio.PCM_FORMAT_S16_LE)", "= 'en-US' # default language strsay = data[4:] if (data[3]=='['):", "'Volume: %s' % volume self.soundhandle.say(data, voice, volume) rospy.sleep(3) elif (use_alsaaudio):", "threading.Thread.__init__(self) # Initialize audio player self.streaming = False self.output_device =", "= None # Dictionary of sounds self.Sounds = {} self.Sounds['bip']", "1 time.sleep(2) if self.aa_stream == None: retry = 3 while", "%s' % volume self.soundhandle.say(data, voice, volume) rospy.sleep(3) elif (use_alsaaudio): cachefile", "False if __name__ == \"__main__\": parser = argparse.ArgumentParser(description='audio_server') parser.add_argument('-ttsport', type=int,", "data) print cmd os.system(cmd) time.sleep(0.2) # convert samplerate tfm =", "of sounds self.Sounds = {} self.Sounds['bip'] = wave.open(SOUNDS_DIR+'bip.wav', 'rb') self.idcache", "\",l self.output_device = l # choose default device break print(\"Audio", "self.stream.is_active(): # time.sleep(1.0) # self.stream.stop_stream() # self.stream.close() # self.streaming =", "wav 44100 Hz - Use audacity or sox to convert", "Hz # Note: some initial sound may not be played.", "#print \"Listen again ...\" def reply(self,mstr): if (self.connection != None):", "(not tts_server.streaming): # cmd = 'play -n --no-show-progress -r 44100", "port [default: 9001]', default=9001) parser.add_argument('-asrport', type=int, help='ASR server port [default:", "print('Connection closed') def setVolume(self,volperc): # volume in percentag [0-100] cmdstr", "True try: from sound_play.msg import SoundRequest from sound_play.libsoundplay import SoundClient", "= 'amixer set PCM %d%%' %volperc os.system(cmdstr) def run(self): global", "if (use_sound_play): voice = 'voice_kal_diphone' volume = 1.0 print 'Saying:", "self.Sounds) and (i<3)): try: soundfile = wave.open(SOUNDS_DIR+name+\".wav\", 'rb') #self.Sounds[name] =", "ASRServer(args.asrport) tts_server.start() time.sleep(1) asr_server.start() run = True while (run): try:", "+= 1 if (soundfile != None and use_alsaaudio): #(name in", "alsaaudio examples # https://larsimmisch.github.io/pyalsaaudio/libalsaaudio.html import threading import time import socket", "mstr = mstr.encode('utf-8') self.connection.send(mstr+'\\n\\r') except: print('Connection closed') def setVolume(self,volperc): #", "!= None and use_alsaaudio): #(name in self.Sounds): self.playwav_aa(soundfile) print('Play completed.')", "None): self.soundhandle = SoundClient() time.sleep(3) self.setVolume(99) # set volume (99%", "--channels 1 -r 44100 -b 16 -t wav bop.wav synth", "ofile) time.sleep(0.2) self.play(cachefile) else: print('Cannot play audio. No infrastructure available.')", "synth 0.1 sine 50 vol 0.01' # keep sound alive", "1 time.sleep(2) self.audio_rate = 44100 self.periodsize = self.audio_rate / 8", "Dictionary of sounds self.Sounds = {} self.Sounds['bip'] = wave.open(SOUNDS_DIR+'bip.wav', 'rb')", "= wave.open(SOUNDS_DIR+name+\".wav\", 'rb') #self.Sounds[name] = soundfile except: print \"File %s%s.wav", "type=str, help='audio device [default: \\'sysdefault\\']', default='sysdefault') args = parser.parse_args() tts_server", "tfm.build(tmpfile, ofile) time.sleep(0.2) self.play(cachefile) else: print('Cannot play audio. No infrastructure", "# Receive the data in small chunks while (self.dorun): try:", "os.system('roslaunch sound_play.launch &') time.sleep(5) rospy.init_node('sound_client', disable_signals=True) use_alsaaudio = False elif", "time.sleep(2) if self.aa_stream == None: retry = 3 while retry>0:", "while retry>0: try: self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device) retry =", "= True # self.stream = self.pa.open(format = 8, #self.pa.get_format_from_width(f.getsampwidth#()), #", "True, # stream_callback = TTS_callback, # output_device_index = self.output_device) #", "TTSServer(args.ttsport,args.device) asr_server = ASRServer(args.asrport) tts_server.start() time.sleep(1) asr_server.start() run = True", "-w start.wav \"Bene! Si Parte!\" # Then convert wav files", "time.sleep(1.0) # self.stream.stop_stream() # self.stream.close() # self.streaming = False if", "# Create a TCP/IP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET,", "= 44100 self.periodsize = self.audio_rate / 8 if self.aa_stream !=", "a TCP/IP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)", "platform import re import wave import argparse import rospy use_sound_play", "pico2wave -l \"it-IT\" -w start.wav \"Bene! Si Parte!\" # Then", "port server_address = ('', port) self.sock.bind(server_address) self.sock.listen(1) print \"TTS Server", "self.aa_stream = alsaaudio.PCM(alsaaudio.PCM_PLAYBACK, alsaaudio.PCM_NORMAL, self.output_device) retry = 0 except Exception", "alsaaudio.PCM_NORMAL, self.output_device) retry = 0 except Exception as e: print(e)", "self.aa_stream.setrate(self.audio_rate) self.aa_stream.setperiodsize(self.periodsize) def stop(self): self.dorun = False def connect(self): connected", "in self.Sounds) and (i<3)): try: soundfile = wave.open(SOUNDS_DIR+name+\".wav\", 'rb') #self.Sounds[name]", "[%s]' %bh) elif (data.startswith('SOUND')): self.play(data[6:]) # play this sound self.reply('OK')", "while (i<3): #((not name in self.Sounds) and (i<3)): try: soundfile", "(l[0:10]=='sysdefault'): print \"choose \",l self.output_device = l # choose default", "been closed.', 'en') time.sleep(2) self.aa_stream = None def say(self, data,", "print(\"Audio device used: %s\" %self.output_device) self.aa_stream = None retry =", "'rb') #self.Sounds[name] = soundfile except: print \"File %s%s.wav not found.\"", "'TTS Server Connection closed.' # Clean up the connection if", "else: print('Cannot play audio. No infrastructure available.') def play(self, name):", "audio player self.streaming = False self.output_device = output_device self.soundhandle =", "== \"__main__\": parser = argparse.ArgumentParser(description='audio_server') parser.add_argument('-ttsport', type=int, help='TTS server port", "9002]', default=9002) parser.add_argument('-device', type=str, help='audio device [default: \\'sysdefault\\']', default='sysdefault') args", "True while (run): try: time.sleep(3) #if (not tts_server.streaming): # cmd", "with sounds soundfile = None # sound file tts_server =", "data if (data.startswith('TTS')): lang = 'en-US' # default language strsay", "data==\"\"): break finally: print 'TTS Server Connection closed.' # Clean", "None): try: mstr = mstr.encode('utf-8') self.connection.send(mstr+'\\n\\r') except: print('Connection closed') def", "\"it-IT\" -w start.wav \"Bene! Si Parte!\" # Then convert wav", "-= 1 time.sleep(2) if self.aa_stream == None: retry = 3" ]
[ "C]): the `T` video frames audio(Tensor[K, L]): the audio frames,", "from .utils import list_dir from .folder import make_dataset from .vision", "for i in range(len(classes))} self.samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file=None)", "to handle clip creation. Args: root (string): Root directory of", "elements from video 2. Note that we drop clips which", "and returns a transformed version. Returns: video (Tensor[T, H, W,", "`Kinetics-400 <https://deepmind.com/research/open-source/open-source-datasets/kinetics/>`_ dataset. Kinetics-400 is an action recognition video dataset.", "handle clip creation. Args: root (string): Root directory of the", "the `T` video frames audio(Tensor[K, L]): the audio frames, where", "Kinetics400(VisionDataset): \"\"\" `Kinetics-400 <https://deepmind.com/research/open-source/open-source-datasets/kinetics/>`_ dataset. Kinetics-400 is an action recognition", "x in self.samples] self.video_clips = VideoClips( video_list, frames_per_clip, step_between_clips, frame_rate,", "= [x[0] for x in self.samples] self.video_clips = VideoClips( video_list,", "10 and 15 frames respectively, if ``frames_per_clip=5`` and ``step_between_clips=5``, the", "To give an example, for 2 videos with 10 and", "be (2 + 3) = 5, where the first two", "dataset. This dataset consider every video as a collection of", "elements will come from video 1, and the next three", "is_valid_file=None) self.classes = classes video_list = [x[0] for x in", "uses a VideoClips object to handle clip creation. Args: root", "list_dir from .folder import make_dataset from .vision import VisionDataset class", "and 15 frames respectively, if ``frames_per_clip=5`` and ``step_between_clips=5``, the dataset", "(int): class of the video clip \"\"\" def __init__(self, root,", "super(Kinetics400, self).__init__(root) extensions = ('avi',) classes = list(sorted(list_dir(root))) class_to_idx =", "and `L` is the number of points label (int): class", "i in range(len(classes))} self.samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file=None) self.classes", "channels and `L` is the number of points label (int):", "by ``frames_per_clip``, where the step in frames between each clip", "not have exactly ``frames_per_clip`` elements, so not all frames in", "= transform def __len__(self): return self.video_clips.num_clips() def __getitem__(self, idx): video,", "the audio frames, where `K` is the number of channels", "__getitem__(self, idx): video, audio, info, video_idx = self.video_clips.get_clip(idx) label =", ".folder import make_dataset from .vision import VisionDataset class Kinetics400(VisionDataset): \"\"\"", "= classes video_list = [x[0] for x in self.samples] self.video_clips", "so not all frames in a video might be present.", "``frames_per_clip`` elements, so not all frames in a video might", "self.video_clips = VideoClips( video_list, frames_per_clip, step_between_clips, frame_rate, _precomputed_metadata, ) self.transform", "present. Internally, it uses a VideoClips object to handle clip", "frames in a clip step_between_clips (int): number of frames between", "video_idx = self.video_clips.get_clip(idx) label = self.samples[video_idx][1] if self.transform is not", "clip step_between_clips (int): number of frames between each clip transform", "def __len__(self): return self.video_clips.num_clips() def __getitem__(self, idx): video, audio, info,", "an example, for 2 videos with 10 and 15 frames", "extensions = ('avi',) classes = list(sorted(list_dir(root))) class_to_idx = {classes[i]: i", "action recognition video dataset. This dataset consider every video as", "creation. Args: root (string): Root directory of the Kinetics-400 Dataset.", "video 1, and the next three elements from video 2.", "import list_dir from .folder import make_dataset from .vision import VisionDataset", "which do not have exactly ``frames_per_clip`` elements, so not all", "label (int): class of the video clip \"\"\" def __init__(self,", "H, W, C]): the `T` video frames audio(Tensor[K, L]): the", "the video clip \"\"\" def __init__(self, root, frames_per_clip, step_between_clips=1, frame_rate=None,", "frames between each clip is given by ``step_between_clips``. To give", "__init__(self, root, frames_per_clip, step_between_clips=1, frame_rate=None, extensions=('avi',), transform=None, _precomputed_metadata=None): super(Kinetics400, self).__init__(root)", "extensions, is_valid_file=None) self.classes = classes video_list = [x[0] for x", "``step_between_clips``. To give an example, for 2 videos with 10", "self.samples[video_idx][1] if self.transform is not None: video = self.transform(video) return", "version. Returns: video (Tensor[T, H, W, C]): the `T` video", "transform def __len__(self): return self.video_clips.num_clips() def __getitem__(self, idx): video, audio,", "for x in self.samples] self.video_clips = VideoClips( video_list, frames_per_clip, step_between_clips,", "if self.transform is not None: video = self.transform(video) return video,", "recognition video dataset. This dataset consider every video as a", "import VisionDataset class Kinetics400(VisionDataset): \"\"\" `Kinetics-400 <https://deepmind.com/research/open-source/open-source-datasets/kinetics/>`_ dataset. Kinetics-400 is", "frames_per_clip, step_between_clips=1, frame_rate=None, extensions=('avi',), transform=None, _precomputed_metadata=None): super(Kinetics400, self).__init__(root) extensions =", "= self.video_clips.get_clip(idx) label = self.samples[video_idx][1] if self.transform is not None:", "the number of channels and `L` is the number of", "{classes[i]: i for i in range(len(classes))} self.samples = make_dataset(self.root, class_to_idx,", "in self.samples] self.video_clips = VideoClips( video_list, frames_per_clip, step_between_clips, frame_rate, _precomputed_metadata,", "self.classes = classes video_list = [x[0] for x in self.samples]", "[x[0] for x in self.samples] self.video_clips = VideoClips( video_list, frames_per_clip,", "from video 1, and the next three elements from video", "clip transform (callable, optional): A function/transform that takes in a", "number of points label (int): class of the video clip", "of channels and `L` is the number of points label", "videos with 10 and 15 frames respectively, if ``frames_per_clip=5`` and", "+ 3) = 5, where the first two elements will", "might be present. Internally, it uses a VideoClips object to", "exactly ``frames_per_clip`` elements, so not all frames in a video", "__len__(self): return self.video_clips.num_clips() def __getitem__(self, idx): video, audio, info, video_idx", "the first two elements will come from video 1, and", "= VideoClips( video_list, frames_per_clip, step_between_clips, frame_rate, _precomputed_metadata, ) self.transform =", "respectively, if ``frames_per_clip=5`` and ``step_between_clips=5``, the dataset size will be", "number of frames in a clip step_between_clips (int): number of", "of points label (int): class of the video clip \"\"\"", "of fixed size, specified by ``frames_per_clip``, where the step in", "Dataset. frames_per_clip (int): number of frames in a clip step_between_clips", "frame_rate=None, extensions=('avi',), transform=None, _precomputed_metadata=None): super(Kinetics400, self).__init__(root) extensions = ('avi',) classes", "from .vision import VisionDataset class Kinetics400(VisionDataset): \"\"\" `Kinetics-400 <https://deepmind.com/research/open-source/open-source-datasets/kinetics/>`_ dataset.", "(int): number of frames between each clip transform (callable, optional):", "in a TxHxWxC video and returns a transformed version. Returns:", "in range(len(classes))} self.samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file=None) self.classes =", "each clip transform (callable, optional): A function/transform that takes in", "(string): Root directory of the Kinetics-400 Dataset. frames_per_clip (int): number", "every video as a collection of video clips of fixed", "This dataset consider every video as a collection of video", "specified by ``frames_per_clip``, where the step in frames between each", "`K` is the number of channels and `L` is the", "class of the video clip \"\"\" def __init__(self, root, frames_per_clip,", "video (Tensor[T, H, W, C]): the `T` video frames audio(Tensor[K,", "step_between_clips, frame_rate, _precomputed_metadata, ) self.transform = transform def __len__(self): return", "drop clips which do not have exactly ``frames_per_clip`` elements, so", "``step_between_clips=5``, the dataset size will be (2 + 3) =", "is not None: video = self.transform(video) return video, audio, label", "video clips of fixed size, specified by ``frames_per_clip``, where the", "2. Note that we drop clips which do not have", "Internally, it uses a VideoClips object to handle clip creation.", "video might be present. Internally, it uses a VideoClips object", "fixed size, specified by ``frames_per_clip``, where the step in frames", "directory of the Kinetics-400 Dataset. frames_per_clip (int): number of frames", "self.samples] self.video_clips = VideoClips( video_list, frames_per_clip, step_between_clips, frame_rate, _precomputed_metadata, )", "list(sorted(list_dir(root))) class_to_idx = {classes[i]: i for i in range(len(classes))} self.samples", "the dataset size will be (2 + 3) = 5,", "_precomputed_metadata=None): super(Kinetics400, self).__init__(root) extensions = ('avi',) classes = list(sorted(list_dir(root))) class_to_idx", "next three elements from video 2. Note that we drop", "= self.samples[video_idx][1] if self.transform is not None: video = self.transform(video)", "frames, where `K` is the number of channels and `L`", "frame_rate, _precomputed_metadata, ) self.transform = transform def __len__(self): return self.video_clips.num_clips()", "_precomputed_metadata, ) self.transform = transform def __len__(self): return self.video_clips.num_clips() def", "of frames between each clip transform (callable, optional): A function/transform", "not all frames in a video might be present. Internally,", "and the next three elements from video 2. Note that", "audio frames, where `K` is the number of channels and", "transform (callable, optional): A function/transform that takes in a TxHxWxC", "all frames in a video might be present. Internally, it", "two elements will come from video 1, and the next", "classes = list(sorted(list_dir(root))) class_to_idx = {classes[i]: i for i in", "step_between_clips=1, frame_rate=None, extensions=('avi',), transform=None, _precomputed_metadata=None): super(Kinetics400, self).__init__(root) extensions = ('avi',)", ") self.transform = transform def __len__(self): return self.video_clips.num_clips() def __getitem__(self,", "class Kinetics400(VisionDataset): \"\"\" `Kinetics-400 <https://deepmind.com/research/open-source/open-source-datasets/kinetics/>`_ dataset. Kinetics-400 is an action", "given by ``step_between_clips``. To give an example, for 2 videos", "= ('avi',) classes = list(sorted(list_dir(root))) class_to_idx = {classes[i]: i for", "clips which do not have exactly ``frames_per_clip`` elements, so not", "frames in a video might be present. Internally, it uses", "`T` video frames audio(Tensor[K, L]): the audio frames, where `K`", "a transformed version. Returns: video (Tensor[T, H, W, C]): the", "\"\"\" def __init__(self, root, frames_per_clip, step_between_clips=1, frame_rate=None, extensions=('avi',), transform=None, _precomputed_metadata=None):", "come from video 1, and the next three elements from", "and ``step_between_clips=5``, the dataset size will be (2 + 3)", "is the number of points label (int): class of the", "a video might be present. Internally, it uses a VideoClips", "the number of points label (int): class of the video", "returns a transformed version. Returns: video (Tensor[T, H, W, C]):", "from .video_utils import VideoClips from .utils import list_dir from .folder", "VideoClips from .utils import list_dir from .folder import make_dataset from", "step_between_clips (int): number of frames between each clip transform (callable,", "TxHxWxC video and returns a transformed version. Returns: video (Tensor[T,", "W, C]): the `T` video frames audio(Tensor[K, L]): the audio", "in a video might be present. Internally, it uses a", "Kinetics-400 is an action recognition video dataset. This dataset consider", "frames audio(Tensor[K, L]): the audio frames, where `K` is the", "first two elements will come from video 1, and the", "with 10 and 15 frames respectively, if ``frames_per_clip=5`` and ``step_between_clips=5``,", "clip is given by ``step_between_clips``. To give an example, for", "3) = 5, where the first two elements will come", "extensions=('avi',), transform=None, _precomputed_metadata=None): super(Kinetics400, self).__init__(root) extensions = ('avi',) classes =", "range(len(classes))} self.samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file=None) self.classes = classes", "is given by ``step_between_clips``. To give an example, for 2", "video_list, frames_per_clip, step_between_clips, frame_rate, _precomputed_metadata, ) self.transform = transform def", "dataset consider every video as a collection of video clips", "a collection of video clips of fixed size, specified by", "an action recognition video dataset. This dataset consider every video", "Note that we drop clips which do not have exactly", "it uses a VideoClips object to handle clip creation. Args:", "A function/transform that takes in a TxHxWxC video and returns", "video as a collection of video clips of fixed size,", "Returns: video (Tensor[T, H, W, C]): the `T` video frames", "video, audio, info, video_idx = self.video_clips.get_clip(idx) label = self.samples[video_idx][1] if", "in a clip step_between_clips (int): number of frames between each", "consider every video as a collection of video clips of", "clips of fixed size, specified by ``frames_per_clip``, where the step", "will come from video 1, and the next three elements", "be present. Internally, it uses a VideoClips object to handle", "15 frames respectively, if ``frames_per_clip=5`` and ``step_between_clips=5``, the dataset size", "if ``frames_per_clip=5`` and ``step_between_clips=5``, the dataset size will be (2", "of the video clip \"\"\" def __init__(self, root, frames_per_clip, step_between_clips=1,", "transform=None, _precomputed_metadata=None): super(Kinetics400, self).__init__(root) extensions = ('avi',) classes = list(sorted(list_dir(root)))", "``frames_per_clip=5`` and ``step_between_clips=5``, the dataset size will be (2 +", "size will be (2 + 3) = 5, where the", "\"\"\" `Kinetics-400 <https://deepmind.com/research/open-source/open-source-datasets/kinetics/>`_ dataset. Kinetics-400 is an action recognition video", "frames between each clip transform (callable, optional): A function/transform that", "dataset size will be (2 + 3) = 5, where", "have exactly ``frames_per_clip`` elements, so not all frames in a", "``frames_per_clip``, where the step in frames between each clip is", "by ``step_between_clips``. To give an example, for 2 videos with", "dataset. Kinetics-400 is an action recognition video dataset. This dataset", ".vision import VisionDataset class Kinetics400(VisionDataset): \"\"\" `Kinetics-400 <https://deepmind.com/research/open-source/open-source-datasets/kinetics/>`_ dataset. Kinetics-400", "self).__init__(root) extensions = ('avi',) classes = list(sorted(list_dir(root))) class_to_idx = {classes[i]:", "VideoClips( video_list, frames_per_clip, step_between_clips, frame_rate, _precomputed_metadata, ) self.transform = transform", "in frames between each clip is given by ``step_between_clips``. To", "L]): the audio frames, where `K` is the number of", "self.transform = transform def __len__(self): return self.video_clips.num_clips() def __getitem__(self, idx):", "info, video_idx = self.video_clips.get_clip(idx) label = self.samples[video_idx][1] if self.transform is", "(callable, optional): A function/transform that takes in a TxHxWxC video", "clip creation. Args: root (string): Root directory of the Kinetics-400", "of video clips of fixed size, specified by ``frames_per_clip``, where", "(Tensor[T, H, W, C]): the `T` video frames audio(Tensor[K, L]):", "example, for 2 videos with 10 and 15 frames respectively,", "class_to_idx, extensions, is_valid_file=None) self.classes = classes video_list = [x[0] for", "we drop clips which do not have exactly ``frames_per_clip`` elements,", "frames_per_clip (int): number of frames in a clip step_between_clips (int):", "points label (int): class of the video clip \"\"\" def", "frames_per_clip, step_between_clips, frame_rate, _precomputed_metadata, ) self.transform = transform def __len__(self):", "return self.video_clips.num_clips() def __getitem__(self, idx): video, audio, info, video_idx =", "= make_dataset(self.root, class_to_idx, extensions, is_valid_file=None) self.classes = classes video_list =", "the step in frames between each clip is given by", "2 videos with 10 and 15 frames respectively, if ``frames_per_clip=5``", "from .folder import make_dataset from .vision import VisionDataset class Kinetics400(VisionDataset):", "def __init__(self, root, frames_per_clip, step_between_clips=1, frame_rate=None, extensions=('avi',), transform=None, _precomputed_metadata=None): super(Kinetics400,", "optional): A function/transform that takes in a TxHxWxC video and", "`L` is the number of points label (int): class of", "between each clip is given by ``step_between_clips``. To give an", "collection of video clips of fixed size, specified by ``frames_per_clip``,", "import VideoClips from .utils import list_dir from .folder import make_dataset", "do not have exactly ``frames_per_clip`` elements, so not all frames", "from video 2. Note that we drop clips which do", "label = self.samples[video_idx][1] if self.transform is not None: video =", "video 2. Note that we drop clips which do not", "where the step in frames between each clip is given", "number of frames between each clip transform (callable, optional): A", "will be (2 + 3) = 5, where the first", "classes video_list = [x[0] for x in self.samples] self.video_clips =", "clip \"\"\" def __init__(self, root, frames_per_clip, step_between_clips=1, frame_rate=None, extensions=('avi',), transform=None,", "that we drop clips which do not have exactly ``frames_per_clip``", "VisionDataset class Kinetics400(VisionDataset): \"\"\" `Kinetics-400 <https://deepmind.com/research/open-source/open-source-datasets/kinetics/>`_ dataset. Kinetics-400 is an", "root (string): Root directory of the Kinetics-400 Dataset. frames_per_clip (int):", "= {classes[i]: i for i in range(len(classes))} self.samples = make_dataset(self.root,", "import make_dataset from .vision import VisionDataset class Kinetics400(VisionDataset): \"\"\" `Kinetics-400", "the Kinetics-400 Dataset. frames_per_clip (int): number of frames in a", "self.transform is not None: video = self.transform(video) return video, audio,", "is the number of channels and `L` is the number", "give an example, for 2 videos with 10 and 15", "step in frames between each clip is given by ``step_between_clips``.", "<https://deepmind.com/research/open-source/open-source-datasets/kinetics/>`_ dataset. Kinetics-400 is an action recognition video dataset. This", "elements, so not all frames in a video might be", "where the first two elements will come from video 1,", "a VideoClips object to handle clip creation. Args: root (string):", "VideoClips object to handle clip creation. Args: root (string): Root", "Root directory of the Kinetics-400 Dataset. frames_per_clip (int): number of", "a clip step_between_clips (int): number of frames between each clip", "function/transform that takes in a TxHxWxC video and returns a", "video and returns a transformed version. Returns: video (Tensor[T, H,", "1, and the next three elements from video 2. Note", ".utils import list_dir from .folder import make_dataset from .vision import", "of frames in a clip step_between_clips (int): number of frames", "video clip \"\"\" def __init__(self, root, frames_per_clip, step_between_clips=1, frame_rate=None, extensions=('avi',),", "i for i in range(len(classes))} self.samples = make_dataset(self.root, class_to_idx, extensions,", "(2 + 3) = 5, where the first two elements", "that takes in a TxHxWxC video and returns a transformed", "video_list = [x[0] for x in self.samples] self.video_clips = VideoClips(", "each clip is given by ``step_between_clips``. To give an example,", "self.video_clips.get_clip(idx) label = self.samples[video_idx][1] if self.transform is not None: video", "the next three elements from video 2. Note that we", "make_dataset(self.root, class_to_idx, extensions, is_valid_file=None) self.classes = classes video_list = [x[0]", "for 2 videos with 10 and 15 frames respectively, if", "Kinetics-400 Dataset. frames_per_clip (int): number of frames in a clip", "as a collection of video clips of fixed size, specified", "make_dataset from .vision import VisionDataset class Kinetics400(VisionDataset): \"\"\" `Kinetics-400 <https://deepmind.com/research/open-source/open-source-datasets/kinetics/>`_", "object to handle clip creation. Args: root (string): Root directory", "of the Kinetics-400 Dataset. frames_per_clip (int): number of frames in", "class_to_idx = {classes[i]: i for i in range(len(classes))} self.samples =", "frames respectively, if ``frames_per_clip=5`` and ``step_between_clips=5``, the dataset size will", "takes in a TxHxWxC video and returns a transformed version.", "idx): video, audio, info, video_idx = self.video_clips.get_clip(idx) label = self.samples[video_idx][1]", "def __getitem__(self, idx): video, audio, info, video_idx = self.video_clips.get_clip(idx) label", "is an action recognition video dataset. This dataset consider every", "('avi',) classes = list(sorted(list_dir(root))) class_to_idx = {classes[i]: i for i", "Args: root (string): Root directory of the Kinetics-400 Dataset. frames_per_clip", "5, where the first two elements will come from video", "transformed version. Returns: video (Tensor[T, H, W, C]): the `T`", "where `K` is the number of channels and `L` is", ".video_utils import VideoClips from .utils import list_dir from .folder import", "self.samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file=None) self.classes = classes video_list", "= 5, where the first two elements will come from", "video dataset. This dataset consider every video as a collection", "(int): number of frames in a clip step_between_clips (int): number", "a TxHxWxC video and returns a transformed version. Returns: video", "self.video_clips.num_clips() def __getitem__(self, idx): video, audio, info, video_idx = self.video_clips.get_clip(idx)", "audio, info, video_idx = self.video_clips.get_clip(idx) label = self.samples[video_idx][1] if self.transform", "audio(Tensor[K, L]): the audio frames, where `K` is the number", "between each clip transform (callable, optional): A function/transform that takes", "number of channels and `L` is the number of points", "size, specified by ``frames_per_clip``, where the step in frames between", "video frames audio(Tensor[K, L]): the audio frames, where `K` is", "= list(sorted(list_dir(root))) class_to_idx = {classes[i]: i for i in range(len(classes))}", "root, frames_per_clip, step_between_clips=1, frame_rate=None, extensions=('avi',), transform=None, _precomputed_metadata=None): super(Kinetics400, self).__init__(root) extensions", "three elements from video 2. Note that we drop clips" ]
[ ".html only self.out_suffix = '.html' # self.config.html_style = 'traditional.css' def", "item = u' ' * 4 * indentlevel + item", "+ '</section>') elif isinstance(node, nodes.list_item): for subnode in node: parts.extend(self.write_toc(subnode,", "= False supported_image_types = ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg'] # don't", "<file>%(outname)s.qch</file> </register> </docFiles> </QHelpCollectionProject> ''' # Qt Help Project (.qhp)", "see AUTHORS. :license: BSD, see LICENSE for details. \"\"\" import", "parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, addnodes.compact_paragraph): for subnode in node: parts.extend(self.write_toc(subnode,", "than one successive dot, or leading/trailing # dots, are also", "htmlescape(self.config.html_title), 'version': htmlescape(self.config.version), 'project': htmlescape(self.config.project), 'namespace': htmlescape(nspace), 'masterdoc': htmlescape(self.config.master_doc), 'sections':", "for subnode in node.children[1]: parts.extend(self.write_toc(subnode, indentlevel+1)) parts.append(' '*4*indentlevel + '</section>')", "dirs, files in os.walk(outdir): resourcedir = root.startswith(staticdir) or \\ root.startswith(imagesdir)", "'utf-8') try: f.write(collection_template % { 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_short_title), 'homepage':", "contain various other information for customizing Qt Assistant. collection_template =", "= node.children[0][0] link = refnode['refuri'] title = htmlescape(refnode.astext()).replace('\"', '&quot;') item", "% {'title': title, 'ref': link} item = u' ' *", "def build_keywords(self, title, refs, subitems): keywords = [] title =", "def handle_finish(self): self.build_qhp(self.outdir, self.config.qthelp_basename) def build_qhp(self, outdir, outname): self.info('writing project", "outdir.endswith(os.sep): outdir += os.sep olen = len(outdir) projectfiles = []", "( # title, i, ref)) # item.encode('ascii', 'xmlcharrefreplace') # keywords.append(item)", "a Unicode string, not a bytestring parts = [] if", "keywords, 'files': projectfiles}) finally: f.close() homepage = 'qthelp://' + posixpath.join(", "Assistant. collection_template = u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?> <QHelpCollectionProject version=\"1.0\">", "isinstance(node, nodes.reference): link = node['refuri'] title = htmlescape(node.astext()).replace('\"', '&quot;') item", "the input file for the help generator. # It contains", "'traditional.css' def handle_finish(self): self.build_qhp(self.outdir, self.config.qthelp_basename) def build_qhp(self, outdir, outname): self.info('writing", "outname): self.info('writing project file...') # sections tocdoc = self.env.get_and_resolve_doctree(self.config.master_doc, self,", "# This is the input file for the help generator.", "* indentlevel + item parts.append(item.encode('ascii', 'xmlcharrefreplace')) elif isinstance(node, nodes.bullet_list): for", "supported_image_types = ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg'] # don't add links", "<filterAttribute>%(version)s</filterAttribute> </customFilter> <filterSection> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> <toc> <section title=\"%(title)s\" ref=\"%(masterdoc)s.html\"> %(sections)s", "= section_template % {'title': indexcls.localname, 'ref': '%s.html' % indexname} sections.append('", "'<keyword name=\"%s\" ref=\"%s\"/>' % (name, ref[1]) item.encode('ascii', 'xmlcharrefreplace') return item", "title = htmlescape(title) # if len(refs) == 0: # XXX", "try: f.write(project_template % { 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_title), 'version': htmlescape(self.config.version),", "It contains references to compressed help files which should be", "root, dirs, files in os.walk(outdir): resourcedir = root.startswith(staticdir) or \\", "dots, are also forbidden nspace = 'org.sphinx.%s.%s' % (outname, self.config.version)", "if not isinstance(node, nodes.list_item): return False if len(node.children) != 2:", "of contents, indices and references to the # actual documentation", "# it seems that the \"namespace\" may not contain non-alphanumeric", "class QtHelpBuilder(StandaloneHTMLBuilder): \"\"\" Builder that also outputs Qt help project,", "ref[1]) item.encode('ascii', 'xmlcharrefreplace') return item def build_keywords(self, title, refs, subitems):", "joining them new_sections = [] for section in sections: if", "'ref': '%s.html' % indexname} sections.append(' ' * 4 * 4", "see LICENSE for details. \"\"\" import os import re import", "finally: f.close() homepage = 'qthelp://' + posixpath.join( nspace, 'doc', self.get_target_uri(self.config.master_doc))", "if self.isdocnode(node): refnode = node.children[0][0] link = refnode['refuri'] title =", "the input file for the help collection generator. # It", "+ posixpath.join( nspace, 'doc', self.get_target_uri(self.config.master_doc)) startpage = 'qthelp://' + posixpath.join(nspace,", "that also outputs Qt help project, contents and index files.", "utf-8 -*- \"\"\" sphinx.builders.qthelp ~~~~~~~~~~~~~~~~~~~~~~ Build input files for the", "section_template = '<section title=\"%(title)s\" ref=\"%(ref)s\"/>' file_template = ' '*12 +", "title=\"%(title)s\" ref=\"%(ref)s\">' % \\ {'title': title, 'ref': link} parts.append(' '*4*indentlevel", "fn.endswith('.js')) or \\ fn.endswith('.html'): filename = path.join(root, fn)[olen:] projectfiles.append(file_template %", "* 4 * indentlevel + item parts.append(item.encode('ascii', 'xmlcharrefreplace')) elif isinstance(node,", "0: # XXX # write_param('See Also', title) if len(refs) ==", "subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) return parts def keyword_item(self, name,", "refnode = node.children[0][0] link = refnode['refuri'] title = htmlescape(refnode.astext()).replace('\"', '&quot;')", "keyword_item(self, name, ref): matchobj = _idpattern.match(name) if matchobj: groupdict =", "subitems: for subitem in subitems: keywords.extend(self.build_keywords(subitem[0], subitem[1], [])) return keywords", "[] title = htmlescape(title) # if len(refs) == 0: #", "the documentation. project_template = u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?> <QtHelpProject", "'toctree' in node sections = [] for node in tocdoc.traverse(istoctree):", "</QtHelpProject> ''' section_template = '<section title=\"%(title)s\" ref=\"%(ref)s\"/>' file_template = '", "nodes.bullet_list): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, addnodes.compact_paragraph):", "= re.compile( r'(?P<title>.+) (\\((class in )?(?P<id>[\\w\\.]+)( (?P<descr>\\w+))?\\))$') # Qt Help", "<filterAttribute>%(version)s</filterAttribute> <toc> <section title=\"%(title)s\" ref=\"%(masterdoc)s.html\"> %(sections)s </section> </toc> <keywords> %(keywords)s", "<files> %(files)s </files> </filterSection> </QtHelpProject> ''' section_template = '<section title=\"%(title)s\"", "fn in files: if (resourcedir and not fn.endswith('.js')) or \\", "parts.extend(self.write_toc(subnode, indentlevel)) return parts def keyword_item(self, name, ref): matchobj =", "# In addition it defines a unique namespace for the", "return item def build_keywords(self, title, refs, subitems): keywords = []", "projectfiles = '\\n'.join(projectfiles) # it seems that the \"namespace\" may", "+ item) # sections may be unicode strings or byte", "return True def write_toc(self, node, indentlevel=4): # XXX this should", "'*12 + '<keyword name=\"%s\" id=\"%s\" ref=\"%s\"/>' % ( name, id,", "elif isinstance(node, nodes.bullet_list): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif", "if id: item = ' '*12 + '<keyword name=\"%s\" id=\"%s\"", "= [] for section in sections: if not isinstance(section, text_type):", "if subitems: for subitem in subitems: keywords.extend(self.build_keywords(subitem[0], subitem[1], [])) return", "which should be # included in the collection. # It", "index files. \"\"\" name = 'qthelp' # don't copy the", "# item.encode('ascii', 'xmlcharrefreplace') # keywords.append(item) keywords.append(self.keyword_item(title, ref)) if subitems: for", "</register> </docFiles> </QHelpCollectionProject> ''' # Qt Help Project (.qhp) #", "item.encode('ascii', 'xmlcharrefreplace') # keywords.append(item) keywords.append(self.keyword_item(title, ref)) if subitems: for subitem", "that the \"namespace\" may not contain non-alphanumeric # characters, and", "False if not isinstance(node.children[0], addnodes.compact_paragraph): return False if not isinstance(node.children[0][0],", "= 'traditional.css' def handle_finish(self): self.build_qhp(self.outdir, self.config.qthelp_basename) def build_qhp(self, outdir, outname):", "isinstance(node, nodes.bullet_list): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node,", "AUTHORS. :license: BSD, see LICENSE for details. \"\"\" import os", "title, i, ref)) # item.encode('ascii', 'xmlcharrefreplace') # keywords.append(item) keywords.append(self.keyword_item(title, ref))", "indentlevel)) elif isinstance(node, nodes.reference): link = node['refuri'] title = htmlescape(node.astext()).replace('\"',", "os.walk(outdir): resourcedir = root.startswith(staticdir) or \\ root.startswith(imagesdir) for fn in", "make sure # they are all unicode strings before joining", "nspace).strip('.') nspace = nspace.lower() # write the project file f", "item = section_template % {'title': title, 'ref': link} item =", "refs, subitems): keywords = [] title = htmlescape(title) # if", "or \\ root.startswith(imagesdir) for fn in files: if (resourcedir and", "'masterdoc': htmlescape(self.config.master_doc), 'sections': sections, 'keywords': keywords, 'files': projectfiles}) finally: f.close()", "project file...') f = codecs.open(path.join(outdir, outname+'.qhcp'), 'w', 'utf-8') try: f.write(collection_template", "% ( name, id, ref[1]) else: item = ' '*12", "= [] index = self.env.create_index(self, group_entries=False) for (key, group) in", "Project (.qhp) # This is the input file for the", "for title, (refs, subitems, key_) in group: keywords.extend(self.build_keywords(title, refs, subitems))", "htmlescape(startpage)}) finally: f.close() def isdocnode(self, node): if not isinstance(node, nodes.list_item):", "if not isinstance(node.children[1], nodes.bullet_list): return False return True def write_toc(self,", "more than one successive dot, or leading/trailing # dots, are", "else: id = None if id: item = ' '*12", "name = 'qthelp' # don't copy the reST source copysource", "<QHelpCollectionProject version=\"1.0\"> <assistant> <title>%(title)s</title> <homePage>%(homepage)s</homePage> <startPage>%(startpage)s</startPage> </assistant> <docFiles> <generate> <file>", "leading/trailing # dots, are also forbidden nspace = 'org.sphinx.%s.%s' %", "htmlescape(self.config.version), 'project': htmlescape(self.config.project), 'namespace': htmlescape(nspace), 'masterdoc': htmlescape(self.config.master_doc), 'sections': sections, 'keywords':", "{ 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_short_title), 'homepage': htmlescape(homepage), 'startpage': htmlescape(startpage)}) finally:", "'&quot;') item = section_template % {'title': title, 'ref': link} item", "the \"namespace\" may not contain non-alphanumeric # characters, and more", "in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, addnodes.compact_paragraph): for subnode in", "re.sub('[^a-zA-Z0-9.]', '', nspace) nspace = re.sub(r'\\.+', '.', nspace).strip('.') nspace =", "nodes.reference): link = node['refuri'] title = htmlescape(node.astext()).replace('\"', '&quot;') item =", "(refs, subitems, key_) in group: keywords.extend(self.build_keywords(title, refs, subitems)) keywords =", "new_sections = [] for section in sections: if not isinstance(section,", "parts.append(item.encode('ascii', 'xmlcharrefreplace')) elif isinstance(node, nodes.bullet_list): for subnode in node: parts.extend(self.write_toc(subnode,", "node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, nodes.reference): link = node['refuri'] title", "indexname, indexcls, content, collapse in self.domain_indices: item = section_template %", "import htmlescape _idpattern = re.compile( r'(?P<title>.+) (\\((class in )?(?P<id>[\\w\\.]+)( (?P<descr>\\w+))?\\))$')", "if not isinstance(node.children[0][0], nodes.reference): return False if not isinstance(node.children[1], nodes.bullet_list):", "1: for i, ref in enumerate(refs): # XXX # item", "<virtualFolder>doc</virtualFolder> <customFilter name=\"%(project)s %(version)s\"> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> </customFilter> <filterSection> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute>", "= 'qthelp://' + posixpath.join(nspace, 'doc', 'index.html') self.info('writing collection project file...')", "'xmlcharrefreplace')) elif isinstance(node, nodes.bullet_list): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel))", "item = (' '*12 + # '<keyword name=\"%s [%d]\" ref=\"%s\"/>'", "and not fn.endswith('.js')) or \\ fn.endswith('.html'): filename = path.join(root, fn)[olen:]", "> 1: for i, ref in enumerate(refs): # XXX #", "files (*.html). # In addition it defines a unique namespace", "False supported_image_types = ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg'] # don't add", "= 'qthelp' # don't copy the reST source copysource =", "documentation files (*.html). # In addition it defines a unique", "<QtHelpProject version=\"1.0\"> <namespace>%(namespace)s</namespace> <virtualFolder>doc</virtualFolder> <customFilter name=\"%(project)s %(version)s\"> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> </customFilter>", "u' ' * 4 * indentlevel + item parts.append(item.encode('ascii', 'xmlcharrefreplace'))", "node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, addnodes.compact_paragraph): for subnode in node:", "# XXX # item = (' '*12 + # '<keyword", "''' # Qt Help Project (.qhp) # This is the", "(resourcedir and not fn.endswith('.js')) or \\ fn.endswith('.html'): filename = path.join(root,", "re import codecs import posixpath from os import path from", "sections = [] for node in tocdoc.traverse(istoctree): sections.extend(self.write_toc(node)) for indexname,", "sections.extend(self.write_toc(node)) for indexname, indexcls, content, collapse in self.domain_indices: item =", "startpage = 'qthelp://' + posixpath.join(nspace, 'doc', 'index.html') self.info('writing collection project", "groupdict = matchobj.groupdict() shortname = groupdict['title'] id = groupdict.get('id') #", "[%d]\" ref=\"%s\"/>' % ( # title, i, ref)) # item.encode('ascii',", "link = node['refuri'] title = htmlescape(node.astext()).replace('\"', '&quot;') item = section_template", "<startPage>%(startpage)s</startPage> </assistant> <docFiles> <generate> <file> <input>%(outname)s.qhp</input> <output>%(outname)s.qch</output> </file> </generate> <register>", "htmlescape(node.astext()).replace('\"', '&quot;') item = section_template % {'title': title, 'ref': link}", "= _idpattern.match(name) if matchobj: groupdict = matchobj.groupdict() shortname = groupdict['title']", "by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE", "for customizing Qt Assistant. collection_template = u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\"", "references to the # actual documentation files (*.html). # In", "codecs.open(path.join(outdir, outname+'.qhp'), 'w', 'utf-8') try: f.write(project_template % { 'outname': htmlescape(outname),", "os import re import codecs import posixpath from os import", "in sections: if not isinstance(section, text_type): new_sections.append(force_decode(section, None)) else: new_sections.append(section)", "collection project file...') f = codecs.open(path.join(outdir, outname+'.qhcp'), 'w', 'utf-8') try:", "for (key, group) in index: for title, (refs, subitems, key_)", "refs[0])) elif len(refs) > 1: for i, ref in enumerate(refs):", "f = codecs.open(path.join(outdir, outname+'.qhp'), 'w', 'utf-8') try: f.write(project_template % {", "% {'filename': htmlescape(filename)}) projectfiles = '\\n'.join(projectfiles) # it seems that", "team, see AUTHORS. :license: BSD, see LICENSE for details. \"\"\"", "[] for section in sections: if not isinstance(section, text_type): new_sections.append(force_decode(section,", "have to make sure # they are all unicode strings", "htmlescape(self.config.project), 'namespace': htmlescape(nspace), 'masterdoc': htmlescape(self.config.master_doc), 'sections': sections, 'keywords': keywords, 'files':", "from six import text_type from docutils import nodes from sphinx", "+= os.sep olen = len(outdir) projectfiles = [] staticdir =", "for section in sections: if not isinstance(section, text_type): new_sections.append(force_decode(section, None))", "XXX this should return a Unicode string, not a bytestring", "strings before joining them new_sections = [] for section in", "len(node.children) != 2: return False if not isinstance(node.children[0], addnodes.compact_paragraph): return", "subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, addnodes.compact_paragraph): for subnode", "self.out_suffix = '.html' # self.config.html_style = 'traditional.css' def handle_finish(self): self.build_qhp(self.outdir,", "u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?> <QtHelpProject version=\"1.0\"> <namespace>%(namespace)s</namespace> <virtualFolder>doc</virtualFolder> <customFilter", "{'filename': htmlescape(filename)}) projectfiles = '\\n'.join(projectfiles) # it seems that the", "name=\"%s\" id=\"%s\" ref=\"%s\"/>' % ( name, id, ref[1]) else: item", "= '<section title=\"%(title)s\" ref=\"%(ref)s\"/>' file_template = ' '*12 + '<file>%(filename)s</file>'", "_idpattern = re.compile( r'(?P<title>.+) (\\((class in )?(?P<id>[\\w\\.]+)( (?P<descr>\\w+))?\\))$') # Qt", "and references to the # actual documentation files (*.html). #", "<namespace>%(namespace)s</namespace> <virtualFolder>doc</virtualFolder> <customFilter name=\"%(project)s %(version)s\"> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> </customFilter> <filterSection> <filterAttribute>%(outname)s</filterAttribute>", "os import path from six import text_type from docutils import", "'<section title=\"%(title)s\" ref=\"%(ref)s\"/>' file_template = ' '*12 + '<file>%(filename)s</file>' class", "index = self.env.create_index(self, group_entries=False) for (key, group) in index: for", "# write the project file f = codecs.open(path.join(outdir, outname+'.qhp'), 'w',", "'project': htmlescape(self.config.project), 'namespace': htmlescape(nspace), 'masterdoc': htmlescape(self.config.master_doc), 'sections': sections, 'keywords': keywords,", "sphinx.builders.qthelp ~~~~~~~~~~~~~~~~~~~~~~ Build input files for the Qt collection generator.", "<docFiles> <generate> <file> <input>%(outname)s.qhp</input> <output>%(outname)s.qch</output> </file> </generate> <register> <file>%(outname)s.qch</file> </register>", "# Is the input file for the help collection generator.", "matchobj: groupdict = matchobj.groupdict() shortname = groupdict['title'] id = groupdict.get('id')", "keywords = [] index = self.env.create_index(self, group_entries=False) for (key, group)", "os.sep olen = len(outdir) projectfiles = [] staticdir = path.join(outdir,", "be # included in the collection. # It may contain", "refs, subitems)) keywords = u'\\n'.join(keywords) # files if not outdir.endswith(os.sep):", "%(files)s </files> </filterSection> </QtHelpProject> ''' section_template = '<section title=\"%(title)s\" ref=\"%(ref)s\"/>'", "# they are all unicode strings before joining them new_sections", "unicode strings or byte strings, we have to make sure", "'w', 'utf-8') try: f.write(project_template % { 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_title),", "%(version)s\"> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> </customFilter> <filterSection> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> <toc> <section title=\"%(title)s\"", "'.', nspace).strip('.') nspace = nspace.lower() # write the project file", "it seems that the \"namespace\" may not contain non-alphanumeric #", "'<keyword name=\"%s [%d]\" ref=\"%s\"/>' % ( # title, i, ref))", "<filterSection> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> <toc> <section title=\"%(title)s\" ref=\"%(masterdoc)s.html\"> %(sections)s </section> </toc>", "def init(self): StandaloneHTMLBuilder.init(self) # the output files for HTML help", "new_sections.append(force_decode(section, None)) else: new_sections.append(section) sections = u'\\n'.join(new_sections) # keywords keywords", "import text_type from docutils import nodes from sphinx import addnodes", "version=\"1.0\" encoding=\"utf-8\" ?> <QtHelpProject version=\"1.0\"> <namespace>%(namespace)s</namespace> <virtualFolder>doc</virtualFolder> <customFilter name=\"%(project)s %(version)s\">", "# characters, and more than one successive dot, or leading/trailing", "key_) in group: keywords.extend(self.build_keywords(title, refs, subitems)) keywords = u'\\n'.join(keywords) #", "new_sections.append(section) sections = u'\\n'.join(new_sections) # keywords keywords = [] index", "parts.append(' '*4*indentlevel + '</section>') elif isinstance(node, nodes.list_item): for subnode in", "path from six import text_type from docutils import nodes from", "title, (refs, subitems, key_) in group: keywords.extend(self.build_keywords(title, refs, subitems)) keywords", "self, prune_toctrees=False) def istoctree(node): return isinstance(node, addnodes.compact_paragraph) and \\ 'toctree'", "output files for HTML help must be .html only self.out_suffix", "also forbidden nspace = 'org.sphinx.%s.%s' % (outname, self.config.version) nspace =", "</customFilter> <filterSection> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> <toc> <section title=\"%(title)s\" ref=\"%(masterdoc)s.html\"> %(sections)s </section>", "in group: keywords.extend(self.build_keywords(title, refs, subitems)) keywords = u'\\n'.join(keywords) # files", "'&quot;') item = '<section title=\"%(title)s\" ref=\"%(ref)s\">' % \\ {'title': title,", "+ '<file>%(filename)s</file>' class QtHelpBuilder(StandaloneHTMLBuilder): \"\"\" Builder that also outputs Qt", "groupdict.get('descr') if shortname.endswith('()'): shortname = shortname[:-2] id = '%s.%s' %", "item def build_keywords(self, title, refs, subitems): keywords = [] title", "only self.out_suffix = '.html' # self.config.html_style = 'traditional.css' def handle_finish(self):", "'image/jpeg'] # don't add links add_permalinks = False # don't", "and more than one successive dot, or leading/trailing # dots,", "all unicode strings before joining them new_sections = [] for", "'*12 + '<file>%(filename)s</file>' class QtHelpBuilder(StandaloneHTMLBuilder): \"\"\" Builder that also outputs", "= len(outdir) projectfiles = [] staticdir = path.join(outdir, '_static') imagesdir", "= root.startswith(staticdir) or \\ root.startswith(imagesdir) for fn in files: if", "# descr = groupdict.get('descr') if shortname.endswith('()'): shortname = shortname[:-2] id", "not isinstance(node.children[0][0], nodes.reference): return False if not isinstance(node.children[1], nodes.bullet_list): return", "strings or byte strings, we have to make sure #", "indentlevel+1)) parts.append(' '*4*indentlevel + '</section>') elif isinstance(node, nodes.list_item): for subnode", "</assistant> <docFiles> <generate> <file> <input>%(outname)s.qhp</input> <output>%(outname)s.qch</output> </file> </generate> <register> <file>%(outname)s.qch</file>", "for details. \"\"\" import os import re import codecs import", "sphinx import addnodes from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.util import", "id, ref[1]) else: item = ' '*12 + '<keyword name=\"%s\"", "# write_param('See Also', title) if len(refs) == 1: keywords.append(self.keyword_item(title, refs[0]))", "content, collapse in self.domain_indices: item = section_template % {'title': indexcls.localname,", "ref): matchobj = _idpattern.match(name) if matchobj: groupdict = matchobj.groupdict() shortname", "* 4 + item) # sections may be unicode strings", "['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg'] # don't add links add_permalinks =", "projectfiles}) finally: f.close() homepage = 'qthelp://' + posixpath.join( nspace, 'doc',", "if (resourcedir and not fn.endswith('.js')) or \\ fn.endswith('.html'): filename =", "references to compressed help files which should be # included", "node.children[1]: parts.extend(self.write_toc(subnode, indentlevel+1)) parts.append(' '*4*indentlevel + '</section>') elif isinstance(node, nodes.list_item):", "file f = codecs.open(path.join(outdir, outname+'.qhp'), 'w', 'utf-8') try: f.write(project_template %", "= groupdict.get('descr') if shortname.endswith('()'): shortname = shortname[:-2] id = '%s.%s'", "Build input files for the Qt collection generator. :copyright: Copyright", "in tocdoc.traverse(istoctree): sections.extend(self.write_toc(node)) for indexname, indexcls, content, collapse in self.domain_indices:", "keywords.append(self.keyword_item(title, ref)) if subitems: for subitem in subitems: keywords.extend(self.build_keywords(subitem[0], subitem[1],", "node.children[0][0] link = refnode['refuri'] title = htmlescape(refnode.astext()).replace('\"', '&quot;') item =", "</keywords> <files> %(files)s </files> </filterSection> </QtHelpProject> ''' section_template = '<section", "elif isinstance(node, addnodes.compact_paragraph): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) return", "for root, dirs, files in os.walk(outdir): resourcedir = root.startswith(staticdir) or", "def build_qhp(self, outdir, outname): self.info('writing project file...') # sections tocdoc", "False return True def write_toc(self, node, indentlevel=4): # XXX this", "False if not isinstance(node.children[1], nodes.bullet_list): return False return True def", "nodes.list_item): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, nodes.reference):", "for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, nodes.reference): link", "parts def keyword_item(self, name, ref): matchobj = _idpattern.match(name) if matchobj:", "'xmlcharrefreplace') return item def build_keywords(self, title, refs, subitems): keywords =", "= 'qthelp://' + posixpath.join( nspace, 'doc', self.get_target_uri(self.config.master_doc)) startpage = 'qthelp://'", "XXX # item = (' '*12 + # '<keyword name=\"%s", "may contain various other information for customizing Qt Assistant. collection_template", "</docFiles> </QHelpCollectionProject> ''' # Qt Help Project (.qhp) # This", "for node in tocdoc.traverse(istoctree): sections.extend(self.write_toc(node)) for indexname, indexcls, content, collapse", "for indexname, indexcls, content, collapse in self.domain_indices: item = section_template", "addnodes.compact_paragraph): return False if not isinstance(node.children[0][0], nodes.reference): return False if", "in enumerate(refs): # XXX # item = (' '*12 +", "import force_decode from sphinx.util.pycompat import htmlescape _idpattern = re.compile( r'(?P<title>.+)", "addition it defines a unique namespace for the documentation. project_template", "staticdir = path.join(outdir, '_static') imagesdir = path.join(outdir, self.imagedir) for root,", "# XXX # write_param('See Also', title) if len(refs) == 1:", "<filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> </customFilter> <filterSection> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> <toc> <section title=\"%(title)s\" ref=\"%(masterdoc)s.html\">", "= (' '*12 + # '<keyword name=\"%s [%d]\" ref=\"%s\"/>' %", "path.join(outdir, '_static') imagesdir = path.join(outdir, self.imagedir) for root, dirs, files", "title, 'ref': link} parts.append(' '*4*indentlevel + item) for subnode in", "htmlescape(nspace), 'masterdoc': htmlescape(self.config.master_doc), 'sections': sections, 'keywords': keywords, 'files': projectfiles}) finally:", "file_template = ' '*12 + '<file>%(filename)s</file>' class QtHelpBuilder(StandaloneHTMLBuilder): \"\"\" Builder", "\\ {'title': title, 'ref': link} parts.append(' '*4*indentlevel + item) for", "''' section_template = '<section title=\"%(title)s\" ref=\"%(ref)s\"/>' file_template = ' '*12", "also outputs Qt help project, contents and index files. \"\"\"", "outdir, outname): self.info('writing project file...') # sections tocdoc = self.env.get_and_resolve_doctree(self.config.master_doc,", "id=\"%s\" ref=\"%s\"/>' % ( name, id, ref[1]) else: item =", "'title': htmlescape(self.config.html_title), 'version': htmlescape(self.config.version), 'project': htmlescape(self.config.project), 'namespace': htmlescape(nspace), 'masterdoc': htmlescape(self.config.master_doc),", "False if len(node.children) != 2: return False if not isinstance(node.children[0],", "posixpath.join( nspace, 'doc', self.get_target_uri(self.config.master_doc)) startpage = 'qthelp://' + posixpath.join(nspace, 'doc',", "encoding=\"utf-8\" ?> <QtHelpProject version=\"1.0\"> <namespace>%(namespace)s</namespace> <virtualFolder>doc</virtualFolder> <customFilter name=\"%(project)s %(version)s\"> <filterAttribute>%(outname)s</filterAttribute>", "= ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg'] # don't add links add_permalinks", "# files if not outdir.endswith(os.sep): outdir += os.sep olen =", "ref[1]) else: item = ' '*12 + '<keyword name=\"%s\" ref=\"%s\"/>'", "f.write(collection_template % { 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_short_title), 'homepage': htmlescape(homepage), 'startpage':", "'_static') imagesdir = path.join(outdir, self.imagedir) for root, dirs, files in", "keywords.append(self.keyword_item(title, refs[0])) elif len(refs) > 1: for i, ref in", "subitems)) keywords = u'\\n'.join(keywords) # files if not outdir.endswith(os.sep): outdir", "title=\"%(title)s\" ref=\"%(masterdoc)s.html\"> %(sections)s </section> </toc> <keywords> %(keywords)s </keywords> <files> %(files)s", "isinstance(node, nodes.list_item): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node,", "name=\"%s [%d]\" ref=\"%s\"/>' % ( # title, i, ref)) #", "'\\n'.join(projectfiles) # it seems that the \"namespace\" may not contain", "It contains the table of contents, indices and references to", "* 4 * 4 + item) # sections may be", "one successive dot, or leading/trailing # dots, are also forbidden", "if not isinstance(node.children[0], addnodes.compact_paragraph): return False if not isinstance(node.children[0][0], nodes.reference):", "# -*- coding: utf-8 -*- \"\"\" sphinx.builders.qthelp ~~~~~~~~~~~~~~~~~~~~~~ Build input", "the # actual documentation files (*.html). # In addition it", "isinstance(node.children[0][0], nodes.reference): return False if not isinstance(node.children[1], nodes.bullet_list): return False", "return False return True def write_toc(self, node, indentlevel=4): # XXX", "BSD, see LICENSE for details. \"\"\" import os import re", "Qt Assistant. collection_template = u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?> <QHelpCollectionProject", "matchobj.groupdict() shortname = groupdict['title'] id = groupdict.get('id') # descr =", "collection_template = u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?> <QHelpCollectionProject version=\"1.0\"> <assistant>", "\"namespace\" may not contain non-alphanumeric # characters, and more than", "isinstance(node, addnodes.compact_paragraph) and \\ 'toctree' in node sections = []", "Builder that also outputs Qt help project, contents and index", "shortname) else: id = None if id: item = '", "None if id: item = ' '*12 + '<keyword name=\"%s\"", "outname+'.qhcp'), 'w', 'utf-8') try: f.write(collection_template % { 'outname': htmlescape(outname), 'title':", "<output>%(outname)s.qch</output> </file> </generate> <register> <file>%(outname)s.qch</file> </register> </docFiles> </QHelpCollectionProject> ''' #", "= htmlescape(title) # if len(refs) == 0: # XXX #", "ref=\"%(ref)s\"/>' file_template = ' '*12 + '<file>%(filename)s</file>' class QtHelpBuilder(StandaloneHTMLBuilder): \"\"\"", "in self.domain_indices: item = section_template % {'title': indexcls.localname, 'ref': '%s.html'", "'index.html') self.info('writing collection project file...') f = codecs.open(path.join(outdir, outname+'.qhcp'), 'w',", "nodes.bullet_list): return False return True def write_toc(self, node, indentlevel=4): #", "subnode in node.children[1]: parts.extend(self.write_toc(subnode, indentlevel+1)) parts.append(' '*4*indentlevel + '</section>') elif", "subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, nodes.reference): link =", "'doc', self.get_target_uri(self.config.master_doc)) startpage = 'qthelp://' + posixpath.join(nspace, 'doc', 'index.html') self.info('writing", "indentlevel)) return parts def keyword_item(self, name, ref): matchobj = _idpattern.match(name)", "node): if not isinstance(node, nodes.list_item): return False if len(node.children) !=", "Collection Project (.qhcp). # Is the input file for the", "= self.env.create_index(self, group_entries=False) for (key, group) in index: for title,", "Qt collection generator. :copyright: Copyright 2007-2016 by the Sphinx team,", "links add_permalinks = False # don't add sidebar etc. embedded", ")?(?P<id>[\\w\\.]+)( (?P<descr>\\w+))?\\))$') # Qt Help Collection Project (.qhcp). # Is", "may not contain non-alphanumeric # characters, and more than one", "'title': htmlescape(self.config.html_short_title), 'homepage': htmlescape(homepage), 'startpage': htmlescape(startpage)}) finally: f.close() def isdocnode(self,", "' * 4 * indentlevel + item parts.append(item.encode('ascii', 'xmlcharrefreplace')) elif", "self.config.html_style = 'traditional.css' def handle_finish(self): self.build_qhp(self.outdir, self.config.qthelp_basename) def build_qhp(self, outdir,", "= '\\n'.join(projectfiles) # it seems that the \"namespace\" may not", "<filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> <toc> <section title=\"%(title)s\" ref=\"%(masterdoc)s.html\"> %(sections)s </section> </toc> <keywords>", "seems that the \"namespace\" may not contain non-alphanumeric # characters,", "f.write(project_template % { 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_title), 'version': htmlescape(self.config.version), 'project':", "</file> </generate> <register> <file>%(outname)s.qch</file> </register> </docFiles> </QHelpCollectionProject> ''' # Qt", "path.join(root, fn)[olen:] projectfiles.append(file_template % {'filename': htmlescape(filename)}) projectfiles = '\\n'.join(projectfiles) #", "addnodes from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.util import force_decode from", "%(keywords)s </keywords> <files> %(files)s </files> </filterSection> </QtHelpProject> ''' section_template =", "the collection. # It may contain various other information for", "section_template % {'title': indexcls.localname, 'ref': '%s.html' % indexname} sections.append(' '", "[] index = self.env.create_index(self, group_entries=False) for (key, group) in index:", "collection generator. # It contains references to compressed help files", "write_toc(self, node, indentlevel=4): # XXX this should return a Unicode", "don't add links add_permalinks = False # don't add sidebar", "= u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?> <QHelpCollectionProject version=\"1.0\"> <assistant> <title>%(title)s</title>", "are all unicode strings before joining them new_sections = []", "ref in enumerate(refs): # XXX # item = (' '*12", "project file f = codecs.open(path.join(outdir, outname+'.qhp'), 'w', 'utf-8') try: f.write(project_template", "codecs.open(path.join(outdir, outname+'.qhcp'), 'w', 'utf-8') try: f.write(collection_template % { 'outname': htmlescape(outname),", "= groupdict['title'] id = groupdict.get('id') # descr = groupdict.get('descr') if", "documentation. project_template = u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?> <QtHelpProject version=\"1.0\">", "to the # actual documentation files (*.html). # In addition", "return False if not isinstance(node.children[1], nodes.bullet_list): return False return True", "-*- \"\"\" sphinx.builders.qthelp ~~~~~~~~~~~~~~~~~~~~~~ Build input files for the Qt", "# don't copy the reST source copysource = False supported_image_types", "projectfiles = [] staticdir = path.join(outdir, '_static') imagesdir = path.join(outdir,", "from os import path from six import text_type from docutils", "unicode strings before joining them new_sections = [] for section", "'utf-8') try: f.write(project_template % { 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_title), 'version':", "htmlescape(outname), 'title': htmlescape(self.config.html_title), 'version': htmlescape(self.config.version), 'project': htmlescape(self.config.project), 'namespace': htmlescape(nspace), 'masterdoc':", "Qt Help Collection Project (.qhcp). # Is the input file", "( name, id, ref[1]) else: item = ' '*12 +", "' '*12 + '<keyword name=\"%s\" ref=\"%s\"/>' % (name, ref[1]) item.encode('ascii',", "text_type): new_sections.append(force_decode(section, None)) else: new_sections.append(section) sections = u'\\n'.join(new_sections) # keywords", "contains the table of contents, indices and references to the", "<input>%(outname)s.qhp</input> <output>%(outname)s.qch</output> </file> </generate> <register> <file>%(outname)s.qch</file> </register> </docFiles> </QHelpCollectionProject> '''", "help collection generator. # It contains references to compressed help", "u'\\n'.join(new_sections) # keywords keywords = [] index = self.env.create_index(self, group_entries=False)", "defines a unique namespace for the documentation. project_template = u'''\\", "(?P<descr>\\w+))?\\))$') # Qt Help Collection Project (.qhcp). # Is the", "Project (.qhcp). # Is the input file for the help", "olen = len(outdir) projectfiles = [] staticdir = path.join(outdir, '_static')", "isinstance(node, addnodes.compact_paragraph): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) return parts", "import StandaloneHTMLBuilder from sphinx.util import force_decode from sphinx.util.pycompat import htmlescape", "% \\ {'title': title, 'ref': link} parts.append(' '*4*indentlevel + item)", "def istoctree(node): return isinstance(node, addnodes.compact_paragraph) and \\ 'toctree' in node", "section_template % {'title': title, 'ref': link} item = u' '", "Also', title) if len(refs) == 1: keywords.append(self.keyword_item(title, refs[0])) elif len(refs)", "may be unicode strings or byte strings, we have to", "successive dot, or leading/trailing # dots, are also forbidden nspace", "keywords.extend(self.build_keywords(title, refs, subitems)) keywords = u'\\n'.join(keywords) # files if not", "in )?(?P<id>[\\w\\.]+)( (?P<descr>\\w+))?\\))$') # Qt Help Collection Project (.qhcp). #", "files: if (resourcedir and not fn.endswith('.js')) or \\ fn.endswith('.html'): filename", "% { 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_short_title), 'homepage': htmlescape(homepage), 'startpage': htmlescape(startpage)})", "# item = (' '*12 + # '<keyword name=\"%s [%d]\"", "write_param('See Also', title) if len(refs) == 1: keywords.append(self.keyword_item(title, refs[0])) elif", "title, 'ref': link} item = u' ' * 4 *", "'startpage': htmlescape(startpage)}) finally: f.close() def isdocnode(self, node): if not isinstance(node,", "htmlescape(self.config.master_doc), 'sections': sections, 'keywords': keywords, 'files': projectfiles}) finally: f.close() homepage", "True def write_toc(self, node, indentlevel=4): # XXX this should return", "from sphinx.util import force_decode from sphinx.util.pycompat import htmlescape _idpattern =", "a bytestring parts = [] if self.isdocnode(node): refnode = node.children[0][0]", "ref=\"%(ref)s\">' % \\ {'title': title, 'ref': link} parts.append(' '*4*indentlevel +", "don't add sidebar etc. embedded = True def init(self): StandaloneHTMLBuilder.init(self)", "# Qt Help Collection Project (.qhcp). # Is the input", "version=\"1.0\" encoding=\"utf-8\" ?> <QHelpCollectionProject version=\"1.0\"> <assistant> <title>%(title)s</title> <homePage>%(homepage)s</homePage> <startPage>%(startpage)s</startPage> </assistant>", "'outname': htmlescape(outname), 'title': htmlescape(self.config.html_short_title), 'homepage': htmlescape(homepage), 'startpage': htmlescape(startpage)}) finally: f.close()", "add links add_permalinks = False # don't add sidebar etc.", "= ' '*12 + '<file>%(filename)s</file>' class QtHelpBuilder(StandaloneHTMLBuilder): \"\"\" Builder that", "sections: if not isinstance(section, text_type): new_sections.append(force_decode(section, None)) else: new_sections.append(section) sections", "string, not a bytestring parts = [] if self.isdocnode(node): refnode", "self.env.create_index(self, group_entries=False) for (key, group) in index: for title, (refs,", "files for HTML help must be .html only self.out_suffix =", "six import text_type from docutils import nodes from sphinx import", "outputs Qt help project, contents and index files. \"\"\" name", "imagesdir = path.join(outdir, self.imagedir) for root, dirs, files in os.walk(outdir):", "in node.children[1]: parts.extend(self.write_toc(subnode, indentlevel+1)) parts.append(' '*4*indentlevel + '</section>') elif isinstance(node,", "ref=\"%s\"/>' % ( # title, i, ref)) # item.encode('ascii', 'xmlcharrefreplace')", "title = htmlescape(node.astext()).replace('\"', '&quot;') item = section_template % {'title': title,", "'.html' # self.config.html_style = 'traditional.css' def handle_finish(self): self.build_qhp(self.outdir, self.config.qthelp_basename) def", "node['refuri'] title = htmlescape(node.astext()).replace('\"', '&quot;') item = section_template % {'title':", "project, contents and index files. \"\"\" name = 'qthelp' #", "# Qt Help Project (.qhp) # This is the input", "project_template = u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?> <QtHelpProject version=\"1.0\"> <namespace>%(namespace)s</namespace>", "len(refs) == 1: keywords.append(self.keyword_item(title, refs[0])) elif len(refs) > 1: for", "enumerate(refs): # XXX # item = (' '*12 + #", "indexname} sections.append(' ' * 4 * 4 + item) #", "fn.endswith('.html'): filename = path.join(root, fn)[olen:] projectfiles.append(file_template % {'filename': htmlescape(filename)}) projectfiles", "(name, ref[1]) item.encode('ascii', 'xmlcharrefreplace') return item def build_keywords(self, title, refs,", "% { 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_title), 'version': htmlescape(self.config.version), 'project': htmlescape(self.config.project),", ":license: BSD, see LICENSE for details. \"\"\" import os import", "groupdict['title'] id = groupdict.get('id') # descr = groupdict.get('descr') if shortname.endswith('()'):", "XXX # write_param('See Also', title) if len(refs) == 1: keywords.append(self.keyword_item(title,", "u'\\n'.join(keywords) # files if not outdir.endswith(os.sep): outdir += os.sep olen", "% (id, shortname) else: id = None if id: item", "sections = u'\\n'.join(new_sections) # keywords keywords = [] index =", "help files which should be # included in the collection.", "item = ' '*12 + '<keyword name=\"%s\" ref=\"%s\"/>' % (name,", "None)) else: new_sections.append(section) sections = u'\\n'.join(new_sections) # keywords keywords =", "root.startswith(staticdir) or \\ root.startswith(imagesdir) for fn in files: if (resourcedir", "details. \"\"\" import os import re import codecs import posixpath", "the table of contents, indices and references to the #", "help project, contents and index files. \"\"\" name = 'qthelp'", "% {'title': indexcls.localname, 'ref': '%s.html' % indexname} sections.append(' ' *", "nspace) nspace = re.sub(r'\\.+', '.', nspace).strip('.') nspace = nspace.lower() #", "= [] for node in tocdoc.traverse(istoctree): sections.extend(self.write_toc(node)) for indexname, indexcls,", "nspace = 'org.sphinx.%s.%s' % (outname, self.config.version) nspace = re.sub('[^a-zA-Z0-9.]', '',", "in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, nodes.reference): link = node['refuri']", "(key, group) in index: for title, (refs, subitems, key_) in", "item.encode('ascii', 'xmlcharrefreplace') return item def build_keywords(self, title, refs, subitems): keywords", "QtHelpBuilder(StandaloneHTMLBuilder): \"\"\" Builder that also outputs Qt help project, contents", "to make sure # they are all unicode strings before", "-*- coding: utf-8 -*- \"\"\" sphinx.builders.qthelp ~~~~~~~~~~~~~~~~~~~~~~ Build input files", "if matchobj: groupdict = matchobj.groupdict() shortname = groupdict['title'] id =", "not isinstance(section, text_type): new_sections.append(force_decode(section, None)) else: new_sections.append(section) sections = u'\\n'.join(new_sections)", "= htmlescape(node.astext()).replace('\"', '&quot;') item = section_template % {'title': title, 'ref':", "elif isinstance(node, nodes.list_item): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif", "# '<keyword name=\"%s [%d]\" ref=\"%s\"/>' % ( # title, i,", "posixpath.join(nspace, 'doc', 'index.html') self.info('writing collection project file...') f = codecs.open(path.join(outdir,", "not a bytestring parts = [] if self.isdocnode(node): refnode =", "should be # included in the collection. # It may", "Unicode string, not a bytestring parts = [] if self.isdocnode(node):", "in the collection. # It may contain various other information", "it defines a unique namespace for the documentation. project_template =", "if shortname.endswith('()'): shortname = shortname[:-2] id = '%s.%s' % (id,", "or byte strings, we have to make sure # they", "False # don't add sidebar etc. embedded = True def", "= [] if self.isdocnode(node): refnode = node.children[0][0] link = refnode['refuri']", "(id, shortname) else: id = None if id: item =", "?> <QHelpCollectionProject version=\"1.0\"> <assistant> <title>%(title)s</title> <homePage>%(homepage)s</homePage> <startPage>%(startpage)s</startPage> </assistant> <docFiles> <generate>", "indentlevel)) elif isinstance(node, addnodes.compact_paragraph): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel))", "build_qhp(self, outdir, outname): self.info('writing project file...') # sections tocdoc =", "StandaloneHTMLBuilder.init(self) # the output files for HTML help must be", "name, id, ref[1]) else: item = ' '*12 + '<keyword", "# sections tocdoc = self.env.get_and_resolve_doctree(self.config.master_doc, self, prune_toctrees=False) def istoctree(node): return", "# keywords keywords = [] index = self.env.create_index(self, group_entries=False) for", "fn)[olen:] projectfiles.append(file_template % {'filename': htmlescape(filename)}) projectfiles = '\\n'.join(projectfiles) # it", "(.qhp) # This is the input file for the help", "Help Collection Project (.qhcp). # Is the input file for", "# XXX this should return a Unicode string, not a", "sphinx.builders.html import StandaloneHTMLBuilder from sphinx.util import force_decode from sphinx.util.pycompat import", "= '.html' # self.config.html_style = 'traditional.css' def handle_finish(self): self.build_qhp(self.outdir, self.config.qthelp_basename)", "'*12 + '<keyword name=\"%s\" ref=\"%s\"/>' % (name, ref[1]) item.encode('ascii', 'xmlcharrefreplace')", "= path.join(root, fn)[olen:] projectfiles.append(file_template % {'filename': htmlescape(filename)}) projectfiles = '\\n'.join(projectfiles)", "finally: f.close() def isdocnode(self, node): if not isinstance(node, nodes.list_item): return", "Help Project (.qhp) # This is the input file for", "descr = groupdict.get('descr') if shortname.endswith('()'): shortname = shortname[:-2] id =", "<register> <file>%(outname)s.qch</file> </register> </docFiles> </QHelpCollectionProject> ''' # Qt Help Project", "self.build_qhp(self.outdir, self.config.qthelp_basename) def build_qhp(self, outdir, outname): self.info('writing project file...') #", "if len(refs) == 0: # XXX # write_param('See Also', title)", "# keywords.append(item) keywords.append(self.keyword_item(title, ref)) if subitems: for subitem in subitems:", "contains references to compressed help files which should be #", "'<section title=\"%(title)s\" ref=\"%(ref)s\">' % \\ {'title': title, 'ref': link} parts.append('", "# if len(refs) == 0: # XXX # write_param('See Also',", "\"\"\" name = 'qthelp' # don't copy the reST source", "keywords = u'\\n'.join(keywords) # files if not outdir.endswith(os.sep): outdir +=", "f.close() def isdocnode(self, node): if not isinstance(node, nodes.list_item): return False", "isdocnode(self, node): if not isinstance(node, nodes.list_item): return False if len(node.children)", "import codecs import posixpath from os import path from six", "4 * 4 + item) # sections may be unicode", "item parts.append(item.encode('ascii', 'xmlcharrefreplace')) elif isinstance(node, nodes.bullet_list): for subnode in node:", "== 1: keywords.append(self.keyword_item(title, refs[0])) elif len(refs) > 1: for i,", "addnodes.compact_paragraph) and \\ 'toctree' in node sections = [] for", "keywords keywords = [] index = self.env.create_index(self, group_entries=False) for (key,", "~~~~~~~~~~~~~~~~~~~~~~ Build input files for the Qt collection generator. :copyright:", "handle_finish(self): self.build_qhp(self.outdir, self.config.qthelp_basename) def build_qhp(self, outdir, outname): self.info('writing project file...')", "filename = path.join(root, fn)[olen:] projectfiles.append(file_template % {'filename': htmlescape(filename)}) projectfiles =", "\"\"\" Builder that also outputs Qt help project, contents and", "{'title': indexcls.localname, 'ref': '%s.html' % indexname} sections.append(' ' * 4", "compressed help files which should be # included in the", "= self.env.get_and_resolve_doctree(self.config.master_doc, self, prune_toctrees=False) def istoctree(node): return isinstance(node, addnodes.compact_paragraph) and", "this should return a Unicode string, not a bytestring parts", "# included in the collection. # It may contain various", "= ' '*12 + '<keyword name=\"%s\" id=\"%s\" ref=\"%s\"/>' % (", "# sections may be unicode strings or byte strings, we", "and \\ 'toctree' in node sections = [] for node", "'qthelp://' + posixpath.join(nspace, 'doc', 'index.html') self.info('writing collection project file...') f", "self.imagedir) for root, dirs, files in os.walk(outdir): resourcedir = root.startswith(staticdir)", "for fn in files: if (resourcedir and not fn.endswith('.js')) or", "import path from six import text_type from docutils import nodes", "StandaloneHTMLBuilder from sphinx.util import force_decode from sphinx.util.pycompat import htmlescape _idpattern", "ref)) if subitems: for subitem in subitems: keywords.extend(self.build_keywords(subitem[0], subitem[1], []))", "init(self): StandaloneHTMLBuilder.init(self) # the output files for HTML help must", "{'title': title, 'ref': link} item = u' ' * 4", "' '*12 + '<keyword name=\"%s\" id=\"%s\" ref=\"%s\"/>' % ( name,", "Is the input file for the help collection generator. #", "version=\"1.0\"> <namespace>%(namespace)s</namespace> <virtualFolder>doc</virtualFolder> <customFilter name=\"%(project)s %(version)s\"> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> </customFilter> <filterSection>", "id = '%s.%s' % (id, shortname) else: id = None", "return parts def keyword_item(self, name, ref): matchobj = _idpattern.match(name) if", "This is the input file for the help generator. #", "sections may be unicode strings or byte strings, we have", "the project file f = codecs.open(path.join(outdir, outname+'.qhp'), 'w', 'utf-8') try:", "parts.append(' '*4*indentlevel + item) for subnode in node.children[1]: parts.extend(self.write_toc(subnode, indentlevel+1))", ":copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. :license:", "<customFilter name=\"%(project)s %(version)s\"> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> </customFilter> <filterSection> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> <toc>", "htmlescape(homepage), 'startpage': htmlescape(startpage)}) finally: f.close() def isdocnode(self, node): if not", "various other information for customizing Qt Assistant. collection_template = u'''\\", "don't copy the reST source copysource = False supported_image_types =", "customizing Qt Assistant. collection_template = u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?>", "f.close() homepage = 'qthelp://' + posixpath.join( nspace, 'doc', self.get_target_uri(self.config.master_doc)) startpage", "4 + item) # sections may be unicode strings or", "them new_sections = [] for section in sections: if not", "input file for the help generator. # It contains the", "isinstance(node.children[0], addnodes.compact_paragraph): return False if not isinstance(node.children[0][0], nodes.reference): return False", "elif len(refs) > 1: for i, ref in enumerate(refs): #", "be unicode strings or byte strings, we have to make", "= u' ' * 4 * indentlevel + item parts.append(item.encode('ascii',", "force_decode from sphinx.util.pycompat import htmlescape _idpattern = re.compile( r'(?P<title>.+) (\\((class", "= codecs.open(path.join(outdir, outname+'.qhp'), 'w', 'utf-8') try: f.write(project_template % { 'outname':", "r'(?P<title>.+) (\\((class in )?(?P<id>[\\w\\.]+)( (?P<descr>\\w+))?\\))$') # Qt Help Collection Project", "f = codecs.open(path.join(outdir, outname+'.qhcp'), 'w', 'utf-8') try: f.write(collection_template % {", "self.get_target_uri(self.config.master_doc)) startpage = 'qthelp://' + posixpath.join(nspace, 'doc', 'index.html') self.info('writing collection", "add sidebar etc. embedded = True def init(self): StandaloneHTMLBuilder.init(self) #", "self.config.qthelp_basename) def build_qhp(self, outdir, outname): self.info('writing project file...') # sections", "item = ' '*12 + '<keyword name=\"%s\" id=\"%s\" ref=\"%s\"/>' %", "'xmlcharrefreplace') # keywords.append(item) keywords.append(self.keyword_item(title, ref)) if subitems: for subitem in", "def isdocnode(self, node): if not isinstance(node, nodes.list_item): return False if", "or \\ fn.endswith('.html'): filename = path.join(root, fn)[olen:] projectfiles.append(file_template % {'filename':", "self.config.version) nspace = re.sub('[^a-zA-Z0-9.]', '', nspace) nspace = re.sub(r'\\.+', '.',", "self.isdocnode(node): refnode = node.children[0][0] link = refnode['refuri'] title = htmlescape(refnode.astext()).replace('\"',", "write the project file f = codecs.open(path.join(outdir, outname+'.qhp'), 'w', 'utf-8')", "else: item = ' '*12 + '<keyword name=\"%s\" ref=\"%s\"/>' %", "outname+'.qhp'), 'w', 'utf-8') try: f.write(project_template % { 'outname': htmlescape(outname), 'title':", "'sections': sections, 'keywords': keywords, 'files': projectfiles}) finally: f.close() homepage =", "'outname': htmlescape(outname), 'title': htmlescape(self.config.html_title), 'version': htmlescape(self.config.version), 'project': htmlescape(self.config.project), 'namespace': htmlescape(nspace),", "file...') # sections tocdoc = self.env.get_and_resolve_doctree(self.config.master_doc, self, prune_toctrees=False) def istoctree(node):", "'ref': link} parts.append(' '*4*indentlevel + item) for subnode in node.children[1]:", "we have to make sure # they are all unicode", "indentlevel=4): # XXX this should return a Unicode string, not", "htmlescape(refnode.astext()).replace('\"', '&quot;') item = '<section title=\"%(title)s\" ref=\"%(ref)s\">' % \\ {'title':", "# It may contain various other information for customizing Qt", "self.env.get_and_resolve_doctree(self.config.master_doc, self, prune_toctrees=False) def istoctree(node): return isinstance(node, addnodes.compact_paragraph) and \\", "files if not outdir.endswith(os.sep): outdir += os.sep olen = len(outdir)", "'namespace': htmlescape(nspace), 'masterdoc': htmlescape(self.config.master_doc), 'sections': sections, 'keywords': keywords, 'files': projectfiles})", "'homepage': htmlescape(homepage), 'startpage': htmlescape(startpage)}) finally: f.close() def isdocnode(self, node): if", "(.qhcp). # Is the input file for the help collection", "node: parts.extend(self.write_toc(subnode, indentlevel)) return parts def keyword_item(self, name, ref): matchobj", "information for customizing Qt Assistant. collection_template = u'''\\ <?xml version=\"1.0\"", "parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, nodes.reference): link = node['refuri'] title =", "'w', 'utf-8') try: f.write(collection_template % { 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_short_title),", "(\\((class in )?(?P<id>[\\w\\.]+)( (?P<descr>\\w+))?\\))$') # Qt Help Collection Project (.qhcp).", "<reponame>CharleyFarley/ovvio<gh_stars>0 # -*- coding: utf-8 -*- \"\"\" sphinx.builders.qthelp ~~~~~~~~~~~~~~~~~~~~~~ Build", "the output files for HTML help must be .html only", "nspace = re.sub(r'\\.+', '.', nspace).strip('.') nspace = nspace.lower() # write", "# title, i, ref)) # item.encode('ascii', 'xmlcharrefreplace') # keywords.append(item) keywords.append(self.keyword_item(title,", "indexcls.localname, 'ref': '%s.html' % indexname} sections.append(' ' * 4 *", "nodes from sphinx import addnodes from sphinx.builders.html import StandaloneHTMLBuilder from", "= groupdict.get('id') # descr = groupdict.get('descr') if shortname.endswith('()'): shortname =", "to compressed help files which should be # included in", "' * 4 * 4 + item) # sections may", "htmlescape(self.config.html_short_title), 'homepage': htmlescape(homepage), 'startpage': htmlescape(startpage)}) finally: f.close() def isdocnode(self, node):", "htmlescape _idpattern = re.compile( r'(?P<title>.+) (\\((class in )?(?P<id>[\\w\\.]+)( (?P<descr>\\w+))?\\))$') #", "= re.sub('[^a-zA-Z0-9.]', '', nspace) nspace = re.sub(r'\\.+', '.', nspace).strip('.') nspace", "build_keywords(self, title, refs, subitems): keywords = [] title = htmlescape(title)", "if not outdir.endswith(os.sep): outdir += os.sep olen = len(outdir) projectfiles", "sphinx.util import force_decode from sphinx.util.pycompat import htmlescape _idpattern = re.compile(", "if len(node.children) != 2: return False if not isinstance(node.children[0], addnodes.compact_paragraph):", "for the documentation. project_template = u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?>", "text_type from docutils import nodes from sphinx import addnodes from", "nspace.lower() # write the project file f = codecs.open(path.join(outdir, outname+'.qhp'),", "isinstance(node.children[1], nodes.bullet_list): return False return True def write_toc(self, node, indentlevel=4):", "_idpattern.match(name) if matchobj: groupdict = matchobj.groupdict() shortname = groupdict['title'] id", "docutils import nodes from sphinx import addnodes from sphinx.builders.html import", "= codecs.open(path.join(outdir, outname+'.qhcp'), 'w', 'utf-8') try: f.write(collection_template % { 'outname':", "help generator. # It contains the table of contents, indices", "ref)) # item.encode('ascii', 'xmlcharrefreplace') # keywords.append(item) keywords.append(self.keyword_item(title, ref)) if subitems:", "dot, or leading/trailing # dots, are also forbidden nspace =", "'qthelp' # don't copy the reST source copysource = False", "% indexname} sections.append(' ' * 4 * 4 + item)", "'doc', 'index.html') self.info('writing collection project file...') f = codecs.open(path.join(outdir, outname+'.qhcp'),", "files. \"\"\" name = 'qthelp' # don't copy the reST", "# dots, are also forbidden nspace = 'org.sphinx.%s.%s' % (outname,", "node, indentlevel=4): # XXX this should return a Unicode string,", "'%s.html' % indexname} sections.append(' ' * 4 * 4 +", "= ' '*12 + '<keyword name=\"%s\" ref=\"%s\"/>' % (name, ref[1])", "% ( # title, i, ref)) # item.encode('ascii', 'xmlcharrefreplace') #", "4 * indentlevel + item parts.append(item.encode('ascii', 'xmlcharrefreplace')) elif isinstance(node, nodes.bullet_list):", "homepage = 'qthelp://' + posixpath.join( nspace, 'doc', self.get_target_uri(self.config.master_doc)) startpage =", "the Qt collection generator. :copyright: Copyright 2007-2016 by the Sphinx", "= '%s.%s' % (id, shortname) else: id = None if", "# don't add links add_permalinks = False # don't add", "item = section_template % {'title': indexcls.localname, 'ref': '%s.html' % indexname}", "link} item = u' ' * 4 * indentlevel +", "istoctree(node): return isinstance(node, addnodes.compact_paragraph) and \\ 'toctree' in node sections", "shortname = shortname[:-2] id = '%s.%s' % (id, shortname) else:", "= True def init(self): StandaloneHTMLBuilder.init(self) # the output files for", "<?xml version=\"1.0\" encoding=\"utf-8\" ?> <QHelpCollectionProject version=\"1.0\"> <assistant> <title>%(title)s</title> <homePage>%(homepage)s</homePage> <startPage>%(startpage)s</startPage>", "id = groupdict.get('id') # descr = groupdict.get('descr') if shortname.endswith('()'): shortname", "+ posixpath.join(nspace, 'doc', 'index.html') self.info('writing collection project file...') f =", "<title>%(title)s</title> <homePage>%(homepage)s</homePage> <startPage>%(startpage)s</startPage> </assistant> <docFiles> <generate> <file> <input>%(outname)s.qhp</input> <output>%(outname)s.qch</output> </file>", "embedded = True def init(self): StandaloneHTMLBuilder.init(self) # the output files", "matchobj = _idpattern.match(name) if matchobj: groupdict = matchobj.groupdict() shortname =", "id = None if id: item = ' '*12 +", "(' '*12 + # '<keyword name=\"%s [%d]\" ref=\"%s\"/>' % (", "</QHelpCollectionProject> ''' # Qt Help Project (.qhp) # This is", "shortname[:-2] id = '%s.%s' % (id, shortname) else: id =", "True def init(self): StandaloneHTMLBuilder.init(self) # the output files for HTML", "if not isinstance(section, text_type): new_sections.append(force_decode(section, None)) else: new_sections.append(section) sections =", "i, ref)) # item.encode('ascii', 'xmlcharrefreplace') # keywords.append(item) keywords.append(self.keyword_item(title, ref)) if", "shortname = groupdict['title'] id = groupdict.get('id') # descr = groupdict.get('descr')", "(outname, self.config.version) nspace = re.sub('[^a-zA-Z0-9.]', '', nspace) nspace = re.sub(r'\\.+',", "= path.join(outdir, '_static') imagesdir = path.join(outdir, self.imagedir) for root, dirs,", "resourcedir = root.startswith(staticdir) or \\ root.startswith(imagesdir) for fn in files:", "<homePage>%(homepage)s</homePage> <startPage>%(startpage)s</startPage> </assistant> <docFiles> <generate> <file> <input>%(outname)s.qhp</input> <output>%(outname)s.qch</output> </file> </generate>", "section in sections: if not isinstance(section, text_type): new_sections.append(force_decode(section, None)) else:", "2007-2016 by the Sphinx team, see AUTHORS. :license: BSD, see", "collection generator. :copyright: Copyright 2007-2016 by the Sphinx team, see", "item) for subnode in node.children[1]: parts.extend(self.write_toc(subnode, indentlevel+1)) parts.append(' '*4*indentlevel +", "else: new_sections.append(section) sections = u'\\n'.join(new_sections) # keywords keywords = []", "'ref': link} item = u' ' * 4 * indentlevel", "for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) elif isinstance(node, addnodes.compact_paragraph): for", "codecs import posixpath from os import path from six import", "= [] staticdir = path.join(outdir, '_static') imagesdir = path.join(outdir, self.imagedir)", "elif isinstance(node, nodes.reference): link = node['refuri'] title = htmlescape(node.astext()).replace('\"', '&quot;')", "\\ fn.endswith('.html'): filename = path.join(root, fn)[olen:] projectfiles.append(file_template % {'filename': htmlescape(filename)})", "# don't add sidebar etc. embedded = True def init(self):", "is the input file for the help generator. # It", "reST source copysource = False supported_image_types = ['image/svg+xml', 'image/png', 'image/gif',", "nspace = re.sub('[^a-zA-Z0-9.]', '', nspace) nspace = re.sub(r'\\.+', '.', nspace).strip('.')", "from sphinx.util.pycompat import htmlescape _idpattern = re.compile( r'(?P<title>.+) (\\((class in", "+ item parts.append(item.encode('ascii', 'xmlcharrefreplace')) elif isinstance(node, nodes.bullet_list): for subnode in", "= [] title = htmlescape(title) # if len(refs) == 0:", "htmlescape(filename)}) projectfiles = '\\n'.join(projectfiles) # it seems that the \"namespace\"", "self.domain_indices: item = section_template % {'title': indexcls.localname, 'ref': '%s.html' %", "files in os.walk(outdir): resourcedir = root.startswith(staticdir) or \\ root.startswith(imagesdir) for", "return a Unicode string, not a bytestring parts = []", "title = htmlescape(refnode.astext()).replace('\"', '&quot;') item = '<section title=\"%(title)s\" ref=\"%(ref)s\">' %", "addnodes.compact_paragraph): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) return parts def", "non-alphanumeric # characters, and more than one successive dot, or", "?> <QtHelpProject version=\"1.0\"> <namespace>%(namespace)s</namespace> <virtualFolder>doc</virtualFolder> <customFilter name=\"%(project)s %(version)s\"> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute>", "\\ root.startswith(imagesdir) for fn in files: if (resourcedir and not", "file for the help collection generator. # It contains references", "# the output files for HTML help must be .html", "item = '<section title=\"%(title)s\" ref=\"%(ref)s\">' % \\ {'title': title, 'ref':", "<file> <input>%(outname)s.qhp</input> <output>%(outname)s.qch</output> </file> </generate> <register> <file>%(outname)s.qch</file> </register> </docFiles> </QHelpCollectionProject>", "help must be .html only self.out_suffix = '.html' # self.config.html_style", "generator. # It contains references to compressed help files which", "for HTML help must be .html only self.out_suffix = '.html'", "posixpath from os import path from six import text_type from", "len(outdir) projectfiles = [] staticdir = path.join(outdir, '_static') imagesdir =", "name, ref): matchobj = _idpattern.match(name) if matchobj: groupdict = matchobj.groupdict()", "'*12 + # '<keyword name=\"%s [%d]\" ref=\"%s\"/>' % ( #", "tocdoc.traverse(istoctree): sections.extend(self.write_toc(node)) for indexname, indexcls, content, collapse in self.domain_indices: item", "'*4*indentlevel + item) for subnode in node.children[1]: parts.extend(self.write_toc(subnode, indentlevel+1)) parts.append('", "htmlescape(title) # if len(refs) == 0: # XXX # write_param('See", "len(refs) == 0: # XXX # write_param('See Also', title) if", "contain non-alphanumeric # characters, and more than one successive dot,", "return False if not isinstance(node.children[0], addnodes.compact_paragraph): return False if not", "= nspace.lower() # write the project file f = codecs.open(path.join(outdir,", "id: item = ' '*12 + '<keyword name=\"%s\" id=\"%s\" ref=\"%s\"/>'", "Qt help project, contents and index files. \"\"\" name =", "in os.walk(outdir): resourcedir = root.startswith(staticdir) or \\ root.startswith(imagesdir) for fn", "<generate> <file> <input>%(outname)s.qhp</input> <output>%(outname)s.qch</output> </file> </generate> <register> <file>%(outname)s.qch</file> </register> </docFiles>", "collapse in self.domain_indices: item = section_template % {'title': indexcls.localname, 'ref':", "root.startswith(imagesdir) for fn in files: if (resourcedir and not fn.endswith('.js'))", "title=\"%(title)s\" ref=\"%(ref)s\"/>' file_template = ' '*12 + '<file>%(filename)s</file>' class QtHelpBuilder(StandaloneHTMLBuilder):", "% (outname, self.config.version) nspace = re.sub('[^a-zA-Z0-9.]', '', nspace) nspace =", "isinstance(node, nodes.list_item): return False if len(node.children) != 2: return False", "= '<section title=\"%(title)s\" ref=\"%(ref)s\">' % \\ {'title': title, 'ref': link}", "[] staticdir = path.join(outdir, '_static') imagesdir = path.join(outdir, self.imagedir) for", "self.info('writing collection project file...') f = codecs.open(path.join(outdir, outname+'.qhcp'), 'w', 'utf-8')", "'<keyword name=\"%s\" id=\"%s\" ref=\"%s\"/>' % ( name, id, ref[1]) else:", "group) in index: for title, (refs, subitems, key_) in group:", "keywords = [] title = htmlescape(title) # if len(refs) ==", "for i, ref in enumerate(refs): # XXX # item =", "collection. # It may contain various other information for customizing", "namespace for the documentation. project_template = u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\"", "== 0: # XXX # write_param('See Also', title) if len(refs)", "import os import re import codecs import posixpath from os", "before joining them new_sections = [] for section in sections:", "import nodes from sphinx import addnodes from sphinx.builders.html import StandaloneHTMLBuilder", "tocdoc = self.env.get_and_resolve_doctree(self.config.master_doc, self, prune_toctrees=False) def istoctree(node): return isinstance(node, addnodes.compact_paragraph)", "contents and index files. \"\"\" name = 'qthelp' # don't", "subitems): keywords = [] title = htmlescape(title) # if len(refs)", "'image/png', 'image/gif', 'image/jpeg'] # don't add links add_permalinks = False", "they are all unicode strings before joining them new_sections =", "for subnode in node: parts.extend(self.write_toc(subnode, indentlevel)) return parts def keyword_item(self,", "Qt Help Project (.qhp) # This is the input file", "other information for customizing Qt Assistant. collection_template = u'''\\ <?xml", "item) # sections may be unicode strings or byte strings,", "generator. :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.", "strings, we have to make sure # they are all", "node sections = [] for node in tocdoc.traverse(istoctree): sections.extend(self.write_toc(node)) for", "copysource = False supported_image_types = ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg'] #", "keywords.append(item) keywords.append(self.keyword_item(title, ref)) if subitems: for subitem in subitems: keywords.extend(self.build_keywords(subitem[0],", "sphinx.util.pycompat import htmlescape _idpattern = re.compile( r'(?P<title>.+) (\\((class in )?(?P<id>[\\w\\.]+)(", "\"\"\" sphinx.builders.qthelp ~~~~~~~~~~~~~~~~~~~~~~ Build input files for the Qt collection", "from docutils import nodes from sphinx import addnodes from sphinx.builders.html", "for the help generator. # It contains the table of", "'<file>%(filename)s</file>' class QtHelpBuilder(StandaloneHTMLBuilder): \"\"\" Builder that also outputs Qt help", "'image/gif', 'image/jpeg'] # don't add links add_permalinks = False #", "sidebar etc. embedded = True def init(self): StandaloneHTMLBuilder.init(self) # the", "prune_toctrees=False) def istoctree(node): return isinstance(node, addnodes.compact_paragraph) and \\ 'toctree' in", "must be .html only self.out_suffix = '.html' # self.config.html_style =", "HTML help must be .html only self.out_suffix = '.html' #", "= 'org.sphinx.%s.%s' % (outname, self.config.version) nspace = re.sub('[^a-zA-Z0-9.]', '', nspace)", "re.compile( r'(?P<title>.+) (\\((class in )?(?P<id>[\\w\\.]+)( (?P<descr>\\w+))?\\))$') # Qt Help Collection", "ref=\"%s\"/>' % ( name, id, ref[1]) else: item = '", "= htmlescape(refnode.astext()).replace('\"', '&quot;') item = '<section title=\"%(title)s\" ref=\"%(ref)s\">' % \\", "'qthelp://' + posixpath.join( nspace, 'doc', self.get_target_uri(self.config.master_doc)) startpage = 'qthelp://' +", "nodes.reference): return False if not isinstance(node.children[1], nodes.bullet_list): return False return", "'files': projectfiles}) finally: f.close() homepage = 'qthelp://' + posixpath.join( nspace,", "<toc> <section title=\"%(title)s\" ref=\"%(masterdoc)s.html\"> %(sections)s </section> </toc> <keywords> %(keywords)s </keywords>", "parts = [] if self.isdocnode(node): refnode = node.children[0][0] link =", "+ # '<keyword name=\"%s [%d]\" ref=\"%s\"/>' % ( # title,", "# It contains the table of contents, indices and references", "</filterSection> </QtHelpProject> ''' section_template = '<section title=\"%(title)s\" ref=\"%(ref)s\"/>' file_template =", "self.info('writing project file...') # sections tocdoc = self.env.get_and_resolve_doctree(self.config.master_doc, self, prune_toctrees=False)", "input file for the help collection generator. # It contains", "sections, 'keywords': keywords, 'files': projectfiles}) finally: f.close() homepage = 'qthelp://'", "the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for", "node in tocdoc.traverse(istoctree): sections.extend(self.write_toc(node)) for indexname, indexcls, content, collapse in", "be .html only self.out_suffix = '.html' # self.config.html_style = 'traditional.css'", "{'title': title, 'ref': link} parts.append(' '*4*indentlevel + item) for subnode", "title) if len(refs) == 1: keywords.append(self.keyword_item(title, refs[0])) elif len(refs) >", "add_permalinks = False # don't add sidebar etc. embedded =", "'</section>') elif isinstance(node, nodes.list_item): for subnode in node: parts.extend(self.write_toc(subnode, indentlevel))", "'%s.%s' % (id, shortname) else: id = None if id:", "etc. embedded = True def init(self): StandaloneHTMLBuilder.init(self) # the output", "\\ 'toctree' in node sections = [] for node in", "unique namespace for the documentation. project_template = u'''\\ <?xml version=\"1.0\"", "copy the reST source copysource = False supported_image_types = ['image/svg+xml',", "or leading/trailing # dots, are also forbidden nspace = 'org.sphinx.%s.%s'", "'org.sphinx.%s.%s' % (outname, self.config.version) nspace = re.sub('[^a-zA-Z0-9.]', '', nspace) nspace", "file for the help generator. # It contains the table", "bytestring parts = [] if self.isdocnode(node): refnode = node.children[0][0] link", "It may contain various other information for customizing Qt Assistant.", "generator. # It contains the table of contents, indices and", "name=\"%(project)s %(version)s\"> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> </customFilter> <filterSection> <filterAttribute>%(outname)s</filterAttribute> <filterAttribute>%(version)s</filterAttribute> <toc> <section", "isinstance(section, text_type): new_sections.append(force_decode(section, None)) else: new_sections.append(section) sections = u'\\n'.join(new_sections) #", "{ 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_title), 'version': htmlescape(self.config.version), 'project': htmlescape(self.config.project), 'namespace':", "included in the collection. # It may contain various other", "' '*12 + '<file>%(filename)s</file>' class QtHelpBuilder(StandaloneHTMLBuilder): \"\"\" Builder that also", "import addnodes from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.util import force_decode", "!= 2: return False if not isinstance(node.children[0], addnodes.compact_paragraph): return False", "and index files. \"\"\" name = 'qthelp' # don't copy", "def write_toc(self, node, indentlevel=4): # XXX this should return a", "from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.util import force_decode from sphinx.util.pycompat", "sure # they are all unicode strings before joining them", "nspace = nspace.lower() # write the project file f =", "'*4*indentlevel + '</section>') elif isinstance(node, nodes.list_item): for subnode in node:", "encoding=\"utf-8\" ?> <QHelpCollectionProject version=\"1.0\"> <assistant> <title>%(title)s</title> <homePage>%(homepage)s</homePage> <startPage>%(startpage)s</startPage> </assistant> <docFiles>", "path.join(outdir, self.imagedir) for root, dirs, files in os.walk(outdir): resourcedir =", "<section title=\"%(title)s\" ref=\"%(masterdoc)s.html\"> %(sections)s </section> </toc> <keywords> %(keywords)s </keywords> <files>", "actual documentation files (*.html). # In addition it defines a", "byte strings, we have to make sure # they are", "</files> </filterSection> </QtHelpProject> ''' section_template = '<section title=\"%(title)s\" ref=\"%(ref)s\"/>' file_template", "shortname.endswith('()'): shortname = shortname[:-2] id = '%s.%s' % (id, shortname)", "Copyright 2007-2016 by the Sphinx team, see AUTHORS. :license: BSD,", "for the help collection generator. # It contains references to", "+ item) for subnode in node.children[1]: parts.extend(self.write_toc(subnode, indentlevel+1)) parts.append(' '*4*indentlevel", "groupdict.get('id') # descr = groupdict.get('descr') if shortname.endswith('()'): shortname = shortname[:-2]", "= u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?> <QtHelpProject version=\"1.0\"> <namespace>%(namespace)s</namespace> <virtualFolder>doc</virtualFolder>", "= u'\\n'.join(keywords) # files if not outdir.endswith(os.sep): outdir += os.sep", "link = refnode['refuri'] title = htmlescape(refnode.astext()).replace('\"', '&quot;') item = '<section", "name=\"%s\" ref=\"%s\"/>' % (name, ref[1]) item.encode('ascii', 'xmlcharrefreplace') return item def", "import posixpath from os import path from six import text_type", "contents, indices and references to the # actual documentation files", "coding: utf-8 -*- \"\"\" sphinx.builders.qthelp ~~~~~~~~~~~~~~~~~~~~~~ Build input files for", "not isinstance(node, nodes.list_item): return False if len(node.children) != 2: return", "forbidden nspace = 'org.sphinx.%s.%s' % (outname, self.config.version) nspace = re.sub('[^a-zA-Z0-9.]',", "indices and references to the # actual documentation files (*.html).", "in files: if (resourcedir and not fn.endswith('.js')) or \\ fn.endswith('.html'):", "+ '<keyword name=\"%s\" id=\"%s\" ref=\"%s\"/>' % ( name, id, ref[1])", "= refnode['refuri'] title = htmlescape(refnode.astext()).replace('\"', '&quot;') item = '<section title=\"%(title)s\"", "sections tocdoc = self.env.get_and_resolve_doctree(self.config.master_doc, self, prune_toctrees=False) def istoctree(node): return isinstance(node,", "from sphinx import addnodes from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.util", "not outdir.endswith(os.sep): outdir += os.sep olen = len(outdir) projectfiles =", "len(refs) > 1: for i, ref in enumerate(refs): # XXX", "table of contents, indices and references to the # actual", "subitems, key_) in group: keywords.extend(self.build_keywords(title, refs, subitems)) keywords = u'\\n'.join(keywords)", "</toc> <keywords> %(keywords)s </keywords> <files> %(files)s </files> </filterSection> </QtHelpProject> '''", "should return a Unicode string, not a bytestring parts =", "parts.extend(self.write_toc(subnode, indentlevel+1)) parts.append(' '*4*indentlevel + '</section>') elif isinstance(node, nodes.list_item): for", "# self.config.html_style = 'traditional.css' def handle_finish(self): self.build_qhp(self.outdir, self.config.qthelp_basename) def build_qhp(self,", "group: keywords.extend(self.build_keywords(title, refs, subitems)) keywords = u'\\n'.join(keywords) # files if", "<keywords> %(keywords)s </keywords> <files> %(files)s </files> </filterSection> </QtHelpProject> ''' section_template", "are also forbidden nspace = 'org.sphinx.%s.%s' % (outname, self.config.version) nspace", "the help generator. # It contains the table of contents,", "not isinstance(node.children[1], nodes.bullet_list): return False return True def write_toc(self, node,", "def keyword_item(self, name, ref): matchobj = _idpattern.match(name) if matchobj: groupdict", "# It contains references to compressed help files which should", "ref=\"%(masterdoc)s.html\"> %(sections)s </section> </toc> <keywords> %(keywords)s </keywords> <files> %(files)s </files>", "nodes.list_item): return False if len(node.children) != 2: return False if", "LICENSE for details. \"\"\" import os import re import codecs", "input files for the Qt collection generator. :copyright: Copyright 2007-2016", "a unique namespace for the documentation. project_template = u'''\\ <?xml", "= matchobj.groupdict() shortname = groupdict['title'] id = groupdict.get('id') # descr", "not contain non-alphanumeric # characters, and more than one successive", "\"\"\" import os import re import codecs import posixpath from", "(*.html). # In addition it defines a unique namespace for", "In addition it defines a unique namespace for the documentation.", "in node: parts.extend(self.write_toc(subnode, indentlevel)) return parts def keyword_item(self, name, ref):", "= section_template % {'title': title, 'ref': link} item = u'", "files for the Qt collection generator. :copyright: Copyright 2007-2016 by", "project file...') # sections tocdoc = self.env.get_and_resolve_doctree(self.config.master_doc, self, prune_toctrees=False) def", "if len(refs) == 1: keywords.append(self.keyword_item(title, refs[0])) elif len(refs) > 1:", "version=\"1.0\"> <assistant> <title>%(title)s</title> <homePage>%(homepage)s</homePage> <startPage>%(startpage)s</startPage> </assistant> <docFiles> <generate> <file> <input>%(outname)s.qhp</input>", "= path.join(outdir, self.imagedir) for root, dirs, files in os.walk(outdir): resourcedir", "nspace, 'doc', self.get_target_uri(self.config.master_doc)) startpage = 'qthelp://' + posixpath.join(nspace, 'doc', 'index.html')", "1: keywords.append(self.keyword_item(title, refs[0])) elif len(refs) > 1: for i, ref", "for the Qt collection generator. :copyright: Copyright 2007-2016 by the", "% (name, ref[1]) item.encode('ascii', 'xmlcharrefreplace') return item def build_keywords(self, title,", "</generate> <register> <file>%(outname)s.qch</file> </register> </docFiles> </QHelpCollectionProject> ''' # Qt Help", "group_entries=False) for (key, group) in index: for title, (refs, subitems,", "not isinstance(node.children[0], addnodes.compact_paragraph): return False if not isinstance(node.children[0][0], nodes.reference): return", "[] if self.isdocnode(node): refnode = node.children[0][0] link = refnode['refuri'] title", "return isinstance(node, addnodes.compact_paragraph) and \\ 'toctree' in node sections =", "%(sections)s </section> </toc> <keywords> %(keywords)s </keywords> <files> %(files)s </files> </filterSection>", "in index: for title, (refs, subitems, key_) in group: keywords.extend(self.build_keywords(title,", "characters, and more than one successive dot, or leading/trailing #", "'', nspace) nspace = re.sub(r'\\.+', '.', nspace).strip('.') nspace = nspace.lower()", "the reST source copysource = False supported_image_types = ['image/svg+xml', 'image/png',", "re.sub(r'\\.+', '.', nspace).strip('.') nspace = nspace.lower() # write the project", "'version': htmlescape(self.config.version), 'project': htmlescape(self.config.project), 'namespace': htmlescape(nspace), 'masterdoc': htmlescape(self.config.master_doc), 'sections': sections,", "'keywords': keywords, 'files': projectfiles}) finally: f.close() homepage = 'qthelp://' +", "False if not isinstance(node.children[0][0], nodes.reference): return False if not isinstance(node.children[1],", "+ '<keyword name=\"%s\" ref=\"%s\"/>' % (name, ref[1]) item.encode('ascii', 'xmlcharrefreplace') return", "in node sections = [] for node in tocdoc.traverse(istoctree): sections.extend(self.write_toc(node))", "u'''\\ <?xml version=\"1.0\" encoding=\"utf-8\" ?> <QHelpCollectionProject version=\"1.0\"> <assistant> <title>%(title)s</title> <homePage>%(homepage)s</homePage>", "outdir += os.sep olen = len(outdir) projectfiles = [] staticdir", "files which should be # included in the collection. #", "</section> </toc> <keywords> %(keywords)s </keywords> <files> %(files)s </files> </filterSection> </QtHelpProject>", "= False # don't add sidebar etc. embedded = True", "htmlescape(outname), 'title': htmlescape(self.config.html_short_title), 'homepage': htmlescape(homepage), 'startpage': htmlescape(startpage)}) finally: f.close() def", "return False if len(node.children) != 2: return False if not", "not fn.endswith('.js')) or \\ fn.endswith('.html'): filename = path.join(root, fn)[olen:] projectfiles.append(file_template", "source copysource = False supported_image_types = ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg']", "i, ref in enumerate(refs): # XXX # item = ('", "= shortname[:-2] id = '%s.%s' % (id, shortname) else: id", "Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details.", "= None if id: item = ' '*12 + '<keyword", "2: return False if not isinstance(node.children[0], addnodes.compact_paragraph): return False if", "title, refs, subitems): keywords = [] title = htmlescape(title) #", "= node['refuri'] title = htmlescape(node.astext()).replace('\"', '&quot;') item = section_template %", "indexcls, content, collapse in self.domain_indices: item = section_template % {'title':", "<?xml version=\"1.0\" encoding=\"utf-8\" ?> <QtHelpProject version=\"1.0\"> <namespace>%(namespace)s</namespace> <virtualFolder>doc</virtualFolder> <customFilter name=\"%(project)s", "= re.sub(r'\\.+', '.', nspace).strip('.') nspace = nspace.lower() # write the", "refnode['refuri'] title = htmlescape(refnode.astext()).replace('\"', '&quot;') item = '<section title=\"%(title)s\" ref=\"%(ref)s\">'", "return False if not isinstance(node.children[0][0], nodes.reference): return False if not", "import re import codecs import posixpath from os import path", "ref=\"%s\"/>' % (name, ref[1]) item.encode('ascii', 'xmlcharrefreplace') return item def build_keywords(self,", "= u'\\n'.join(new_sections) # keywords keywords = [] index = self.env.create_index(self,", "file...') f = codecs.open(path.join(outdir, outname+'.qhcp'), 'w', 'utf-8') try: f.write(collection_template %", "# actual documentation files (*.html). # In addition it defines", "the help collection generator. # It contains references to compressed", "indentlevel + item parts.append(item.encode('ascii', 'xmlcharrefreplace')) elif isinstance(node, nodes.bullet_list): for subnode", "index: for title, (refs, subitems, key_) in group: keywords.extend(self.build_keywords(title, refs,", "projectfiles.append(file_template % {'filename': htmlescape(filename)}) projectfiles = '\\n'.join(projectfiles) # it seems", "sections.append(' ' * 4 * 4 + item) # sections", "link} parts.append(' '*4*indentlevel + item) for subnode in node.children[1]: parts.extend(self.write_toc(subnode,", "[] for node in tocdoc.traverse(istoctree): sections.extend(self.write_toc(node)) for indexname, indexcls, content,", "<assistant> <title>%(title)s</title> <homePage>%(homepage)s</homePage> <startPage>%(startpage)s</startPage> </assistant> <docFiles> <generate> <file> <input>%(outname)s.qhp</input> <output>%(outname)s.qch</output>", "try: f.write(collection_template % { 'outname': htmlescape(outname), 'title': htmlescape(self.config.html_short_title), 'homepage': htmlescape(homepage)," ]
[ "list displayed on gui ScienceDirect \"\"\" titles = [] urls", "properly if offset == 0: # if on page 1,", "elems def clean(elems): \"\"\" This method takes a list of", "after content is saved, go to the next year break", "def write_urls(urls,titles,file,journal,year): \"\"\" This method takes a list of urls", "we want journal_strings = ['chemistry','energy','molecular','atomic','chemical','biochem' ,'organic','polymer','chemical engineering','biotech','coloid'] name = df.Full_Category.str.contains", "being found. \"\"\" pub_elems = driver.find_elements_by_css_selector('input[id*=publicationTitles]') pub_names = [] for", "extension for URL storage: \") url_counter = 0 master_list =", "urls and turns them into urls that go through the", "full of only journals who's topic description contained the #", "+ '&years='+ str(year) if i != 0: url = url", "which should be the same as the list displayed on", "want journal_strings = ['chemistry','energy','molecular','atomic','chemical','biochem' ,'organic','polymer','chemical engineering','biotech','coloid'] name = df.Full_Category.str.contains #", "# new dataframe full of only journals who's topic description", "to scrape ScienceDirect of publication urls and write them to", ": The list of URLs to be converted uw_prefix (str)", "= 'Journal_Title') # drop any duplicate journals df = shuffle(df,random_state", "write_urls(urls,titles,file,journal,year): \"\"\" This method takes a list of urls and", "URLs saved is: ',url_counter) if len(scraped_elems) < 100: # after", "list of scraped selenium web elements and filters/ returns only", "there is an exception, it means we are on the", "+ journal + ',' + str(year) file.write(line) file.write('\\n') def find_pubTitle(driver,journal):", "takes the list of journals and creates a tiple nested", "return dict1 def proxify(scraped_urls,uw_prefix): \"\"\" This method takes a list", "hrefs, which should be the same as the list displayed", "np.arange(1995,2020): for offset in np.arange(60): page = url_dict[journal][year][offset] print(\"journal, year,", "return elems def clean(elems): \"\"\" This method takes a list", "are being found. \"\"\" pub_elems = driver.find_elements_by_css_selector('input[id*=publicationTitles]') pub_names = []", "list of journals and creates a tiple nested dictionary containing", "'chemistry%20OR%20molecule%20OR%20polymer%20OR%20organic' url_dict = build_url_list(gui_prefix,search_terms,journal_list) driver = webdriver.Chrome() uw_prefix = 'https://www-sciencedirect-com.offcampus.lib.washington.edu/science/article/pii/'", "urls and writes them to a desired text file. Parameters", "filename with .txt extension for URL storage: \") url_counter =", "= ['chemistry','energy','molecular','atomic','chemical','biochem' ,'organic','polymer','chemical engineering','biotech','coloid'] name = df.Full_Category.str.contains # making this", "file which will be written to. year (str or int)", "titles.append(title) urls.append(url) return urls, titles def build_url_list(gui_prefix,search_terms,journal_list): \"\"\" This method", "method takes a list of urls and writes them to", "\"\"\" pub_elems = driver.find_elements_by_css_selector('input[id*=publicationTitles]') pub_names = [] for elem in", "| name('chemical')] journal_list = df2.Journal_Title # Series of only the", "elems = driver.find_elements_by_class_name('ResultItem') return elems def clean(elems): \"\"\" This method", "for journal in journal_list: dict2 = {} for year in", ": The new list of hrefs, which should be the", "= find_pubTitle(driver,journal_list[journal_counter]) for url in url_dict[journal]: url = url +", "pubTitles # update every url in the list driver.get(url_dict[journal][year][0]) #", "str(year) if i != 0: url = url + '&offset='", "This method finds all the publication result web elements on", "The list of URLs to be converted uw_prefix (str) :", "desired journal are being found. \"\"\" pub_elems = driver.find_elements_by_css_selector('input[id*=publicationTitles]') pub_names", "in np.arange(60): page = url_dict[journal][year][offset] print(\"journal, year, offset = \",journal,year,offset)", "# Series of only the journals to be searched gui_prefix", "all URLs which go through the UW Library Proxy start", "to sort which journals we want journal_strings = ['chemistry','energy','molecular','atomic','chemical','biochem' ,'organic','polymer','chemical", "file in the current directory for later use. \"\"\" import", "selenium web elements and filters/ returns only the hrefs leading", "url in the list driver.get(url_dict[journal][year][0]) # reload the first page", "scraped_urls (list) : The list of URLs to be converted", "url[-17:] newlink = uw_prefix + sd_id if sd_id.startswith('S'): proxy_urls.append(newlink) return", "through the UW Library Proxy start with. Returns ------- proxy_urls", "anything \"\"\" for link,title in zip(urls,titles): line = link +", "directory for later use. \"\"\" import selenium from selenium import", "sort which journals we want journal_strings = ['chemistry','energy','molecular','atomic','chemical','biochem' ,'organic','polymer','chemical engineering','biotech','coloid']", "from sklearn.utils import shuffle def scrape_page(driver): \"\"\" This method finds", "= dict3 dict1[journal] = dict2 return dict1 def proxify(scraped_urls,uw_prefix): \"\"\"", "of URLs to be saved. file (file object) : The", "object) : The opened .txt file which will be written", "+ title + ',' + journal + ',' + str(year)", "A list of all scraped hrefs from the page \"\"\"", "'&articleTypes=FLA%2CREV' + '&years='+ str(year) if i != 0: url =", "sure this is needed write_urls(proxy_urls,titles,file,journal,year) url_counter += len(proxy_urls) print('Total URLs", "the publication result web elements on the webpage. Parameters ----------", "| name('energy') | name('molecular') | name('colloid') | name('biochem') | name('organic')", "the UW Library proxy so that all of them are", "converted uw_prefix (str) : The string that all URLs which", "href_child.get_attribute('href') title = href_child.text titles.append(title) urls.append(url) return urls, titles def", "dict2[year] = dict3 dict1[journal] = dict2 return dict1 def proxify(scraped_urls,uw_prefix):", "scraped_urls, titles = clean(scraped_elems) proxy_urls = proxify(scraped_urls,uw_prefix) # not even", "code is used to scrape ScienceDirect of publication urls and", "in journal_list: for year in np.arange(1995,2020): for offset in np.arange(60):", "def build_url_list(gui_prefix,search_terms,journal_list): \"\"\" This method takes the list of journals", "titles = [] urls = [] for elem in elems:", "import bs4 from bs4 import BeautifulSoup import time from sklearn.utils", "year in np.arange(1995,2020): for offset in np.arange(60): page = url_dict[journal][year][offset]", "nested dictionary containing all accessible urls to each page, in", "hrefs leading to publications. Filtering includes removing all urls with", "\") url_counter = 0 master_list = [] file = open(filename,'a+')", "this is the last page of urls for this year", "journal + ',' + str(year) file.write(line) file.write('\\n') def find_pubTitle(driver,journal): \"\"\"", "know this is the last page of urls for this", "| name('biotech') | name('chemical')] journal_list = df2.Journal_Title # Series of", "for searching df = df.drop_duplicates(subset = 'Journal_Title') # drop any", "name = df.Full_Category.str.contains # making this an easier command to", "only journals who's topic description contained the # desired keywords", "searching df = df.drop_duplicates(subset = 'Journal_Title') # drop any duplicate", "search_terms = 'chemistry%20OR%20molecule%20OR%20polymer%20OR%20organic' url_dict = build_url_list(gui_prefix,search_terms,journal_list) driver = webdriver.Chrome() uw_prefix", "scraped hrefs from the page \"\"\" elems = driver.find_elements_by_class_name('ResultItem') return", "are full access. Parameters ---------- scraped_urls (list) : The list", "non-html links. Parameters ---------- elems (list) : The list of", "each page, in each year, for each journal, for a", "of them are full access. Parameters ---------- scraped_urls (list) :", "= 0 master_list = [] file = open(filename,'a+') for journal", "them into urls that go through the UW Library proxy", "url_dict[journal]: url = url + '&pubTitles=' + pubTitles # update", "in scraped_urls: sd_id = url[-17:] newlink = uw_prefix + sd_id", "for link,title in zip(urls,titles): line = link + ',' +", "',' + title + ',' + journal + ',' +", "to load the page properly if offset == 0: #", "The new list of hrefs, which should be the same", "+ journal dict3[i] = url dict2[year] = dict3 dict1[journal] =", "indicative of non-html links. Parameters ---------- elems (list) : The", "proxify(scraped_urls,uw_prefix): \"\"\" This method takes a list of scraped urls", "(file object) : The opened .txt file which will be", "import time from sklearn.utils import shuffle def scrape_page(driver): \"\"\" This", "accessible urls to each page, in each year, for each", "+ '&pub=' + journal dict3[i] = url dict2[year] = dict3", "(list) : The list of converted URLs which go through", "the page scraped_urls, titles = clean(scraped_elems) proxy_urls = proxify(scraped_urls,uw_prefix) #", "desired text file. Parameters ---------- urls (list) : The list", "driver.find_elements_by_css_selector('input[id*=publicationTitles]') pub_names = [] for elem in pub_elems: pub_name =", "page = url_dict[journal][year][offset] print(\"journal, year, offset = \",journal,year,offset) driver.get(page) time.sleep(2)", "journals we want journal_strings = ['chemistry','energy','molecular','atomic','chemical','biochem' ,'organic','polymer','chemical engineering','biotech','coloid'] name =", "an exception, it means we are on the right page", "the desired journal are being found. \"\"\" pub_elems = driver.find_elements_by_css_selector('input[id*=publicationTitles]')", "[] for url in scraped_urls: sd_id = url[-17:] newlink =", "This method finds the identifying number for a specific journal.", "dict1[journal] = dict2 return dict1 def proxify(scraped_urls,uw_prefix): \"\"\" This method", "= webdriver.Chrome() uw_prefix = 'https://www-sciencedirect-com.offcampus.lib.washington.edu/science/article/pii/' filename = input(\"Input filename with", "# after content is saved, go to the next year", "\"\"\" elems = driver.find_elements_by_class_name('ResultItem') return elems def clean(elems): \"\"\" This", "i in range(60): url = gui_prefix + search_terms + '&show=100'+", "for url in scraped_urls: sd_id = url[-17:] newlink = uw_prefix", "offset == 0: # if on page 1, we need", "| name('chemistry') | name('energy') | name('molecular') | name('colloid') | name('biochem')", "selenium import webdriver import numpy as np import pandas as", "proxy_urls = [] for url in scraped_urls: sd_id = url[-17:]", "in zip(urls,titles): line = link + ',' + title +", "is needed write_urls(proxy_urls,titles,file,journal,year) url_counter += len(proxy_urls) print('Total URLs saved is:", "lowercase topics for searching df = df.drop_duplicates(subset = 'Journal_Title') #", "journal, for a given search on sciencedirect. \"\"\" dict1 =", "Does not return anything \"\"\" for link,title in zip(urls,titles): line", "urls (list) : The new list of hrefs, which should", "filename = input(\"Input filename with .txt extension for URL storage:", "break # because we know this is the last page", ": The list of hrefs to be filtered Returns -------", "ScienceDirect \"\"\" titles = [] urls = [] for elem", "that will be used to sort which journals we want", "dataframe full of only journals who's topic description contained the", "Library Proxy start with. Returns ------- proxy_urls (list) : The", "which will be written to. year (str or int) :", "file = open(filename,'a+') for journal in journal_list: for year in", "url = url + '&offset=' + str(i) +'00' url =", "in journal_list: dict2 = {} for year in years: dict3", "be the same as the list displayed on gui ScienceDirect", "tiple nested dictionary containing all accessible urls to each page,", "pass # if there is an exception, it means we", "page scraped_urls, titles = clean(scraped_elems) proxy_urls = proxify(scraped_urls,uw_prefix) # not", "write_urls(proxy_urls,titles,file,journal,year) url_counter += len(proxy_urls) print('Total URLs saved is: ',url_counter) if", "page which won't have the item we are looking for", "keywords that are indicative of non-html links. Parameters ---------- elems", "gui query URL to ensure only publciations from the desired", "is the last page of urls for this year file.close()", "grab the publisher number try: # we may be at", "',url_counter) if len(scraped_elems) < 100: # after content is saved,", "url + '&offset=' + str(i) +'00' url = url +", "displayed on gui ScienceDirect \"\"\" titles = [] urls =", ": The string that all URLs which go through the", "we may be at a page which won't have the", "be at a page which won't have the item we", "a given search on sciencedirect. \"\"\" dict1 = {} years", "e.g. webdriver.Chrome() Returns ------- elems (list) : A list of", "Library proxy so that all of them are full access.", "will be written to. year (str or int) : The", "(Selenium webdriver object) : Instance of the webdriver class e.g.", "specific journal. This identifying number is added to the gui", "to be converted uw_prefix (str) : The string that all", "+ '&pubTitles=' + pubTitles # update every url in the", "of only journals who's topic description contained the # desired", "driver.get(page) time.sleep(2) # need sleep to load the page properly", "dictionary containing all accessible urls to each page, in each", "!= 0: url = url + '&offset=' + str(i) +'00'", "access. Parameters ---------- scraped_urls (list) : The list of URLs", "finds the identifying number for a specific journal. This identifying", "be saved. file (file object) : The opened .txt file", "print(\"journal, year, offset = \",journal,year,offset) driver.get(page) time.sleep(2) # need sleep", "= df.Full_Category.str.contains # making this an easier command to type", "urls and write them to a text file in the", "added to the gui query URL to ensure only publciations", "used to scrape ScienceDirect of publication urls and write them", "elem in pub_elems: pub_name = elem.get_attribute(\"name\") if pub_name == journal:", "journal: return elem.get_attribute('id')[-6:] #returns the identifying number #for that journal", "strings that will be used to sort which journals we", "to a desired text file. Parameters ---------- urls (list) :", "of journals and creates a tiple nested dictionary containing all", "if pub_name == journal: return elem.get_attribute('id')[-6:] #returns the identifying number", "0: url = url + '&offset=' + str(i) +'00' url", "a list of urls and writes them to a desired", "years: dict3 = {} for i in range(60): url =", "the page \"\"\" elems = driver.find_elements_by_class_name('ResultItem') return elems def clean(elems):", "is added to the gui query URL to ensure only", "= \",journal,year,offset) driver.get(page) time.sleep(2) # need sleep to load the", "# we may be at a page which won't have", "0: # if on page 1, we need to grab", "+ pubTitles # update every url in the list driver.get(url_dict[journal][year][0])", "need to grab the publisher number try: # we may", "saved is: ',url_counter) if len(scraped_elems) < 100: # after content", "The opened .txt file which will be written to. year", "{} years = np.arange(1995,2020) for journal in journal_list: dict2 =", "(str or int) : The year associated with the publication", "to the gui query URL to ensure only publciations from", "may be at a page which won't have the item", "who's topic description contained the # desired keywords df2 =", "except: pass # if there is an exception, it means", "same as the list displayed on gui ScienceDirect \"\"\" titles", "= href_child.get_attribute('href') title = href_child.text titles.append(title) urls.append(url) return urls, titles", "be converted uw_prefix (str) : The string that all URLs", "= shuffle(df,random_state = 42) # The set of default strings", "number is added to the gui query URL to ensure", "journal are being found. \"\"\" pub_elems = driver.find_elements_by_css_selector('input[id*=publicationTitles]') pub_names =", "(list) : The list of URLs to be saved. file", "method takes the list of journals and creates a tiple", "1, we need to grab the publisher number try: #", "to grab the publisher number try: # we may be", "with keywords that are indicative of non-html links. Parameters ----------", "in each year, for each journal, for a given search", "Parameters ---------- scraped_urls (list) : The list of URLs to", "in elems: href_child = elem.find_element_by_css_selector('a[href]') url = href_child.get_attribute('href') title =", "'&pub=' + journal dict3[i] = url dict2[year] = dict3 dict1[journal]", "\"\"\" This method finds the identifying number for a specific", "of URLs to be converted uw_prefix (str) : The string", "---------- urls (list) : The list of URLs to be", "searched gui_prefix = 'https://www.sciencedirect.com/search/advanced?qs=' search_terms = 'chemistry%20OR%20molecule%20OR%20polymer%20OR%20organic' url_dict = build_url_list(gui_prefix,search_terms,journal_list)", "[] urls = [] for elem in elems: href_child =", "first page with the new url except: pass # if", "urls to each page, in each year, for each journal,", "= url_dict[journal][year][offset] print(\"journal, year, offset = \",journal,year,offset) driver.get(page) time.sleep(2) #", "the next year break # because we know this is", "containing all accessible urls to each page, in each year,", "of scraped urls and turns them into urls that go", "import shuffle def scrape_page(driver): \"\"\" This method finds all the", "be searched gui_prefix = 'https://www.sciencedirect.com/search/advanced?qs=' search_terms = 'chemistry%20OR%20molecule%20OR%20polymer%20OR%20organic' url_dict =", "find_pubTitle(driver,journal_list[journal_counter]) for url in url_dict[journal]: url = url + '&pubTitles='", "df2.Journal_Title # Series of only the journals to be searched", "at a page which won't have the item we are", "desired keywords df2 = df[name('polymer') | name('chemistry') | name('energy') |", "= [] for elem in elems: href_child = elem.find_element_by_css_selector('a[href]') url", "journal_list = df2.Journal_Title # Series of only the journals to", "gui ScienceDirect \"\"\" titles = [] urls = [] for", "UW Library Proxy start with. Returns ------- proxy_urls (list) :", "elem.find_element_by_css_selector('a[href]') url = href_child.get_attribute('href') title = href_child.text titles.append(title) urls.append(url) return", "This method takes a list of urls and writes them", "\"\"\" This method takes a list of scraped urls and", "------- urls (list) : The new list of hrefs, which", "publisher number try: # we may be at a page", "current directory for later use. \"\"\" import selenium from selenium", "journals df = shuffle(df,random_state = 42) # The set of", "| name('biochem') | name('organic') | name('biotech') | name('chemical')] journal_list =", "needed write_urls(proxy_urls,titles,file,journal,year) url_counter += len(proxy_urls) print('Total URLs saved is: ',url_counter)", "str(year) file.write(line) file.write('\\n') def find_pubTitle(driver,journal): \"\"\" This method finds the", "driver.find_elements_by_class_name('ResultItem') return elems def clean(elems): \"\"\" This method takes a", "command to type # new dataframe full of only journals", "on the webpage. Parameters ---------- driver (Selenium webdriver object) :", "file. Parameters ---------- urls (list) : The list of URLs", "identifying number is added to the gui query URL to", "uw_prefix = 'https://www-sciencedirect-com.offcampus.lib.washington.edu/science/article/pii/' filename = input(\"Input filename with .txt extension", "\"\"\" for link,title in zip(urls,titles): line = link + ','", "the gui query URL to ensure only publciations from the", "elem.get_attribute('id')[-6:] #returns the identifying number #for that journal df =", "looking for pubTitles = find_pubTitle(driver,journal_list[journal_counter]) for url in url_dict[journal]: url", "the hrefs leading to publications. Filtering includes removing all urls", "= url + '&offset=' + str(i) +'00' url = url", "UW Library proxy \"\"\" proxy_urls = [] for url in", "= 'https://www.sciencedirect.com/search/advanced?qs=' search_terms = 'chemistry%20OR%20molecule%20OR%20polymer%20OR%20organic' url_dict = build_url_list(gui_prefix,search_terms,journal_list) driver =", "url except: pass # if there is an exception, it", "pubTitles = find_pubTitle(driver,journal_list[journal_counter]) for url in url_dict[journal]: url = url", "df = pd.read_excel('elsevier_journals.xls') df.Full_Category = df.Full_Category.str.lower() # lowercase topics for", "journal_strings = ['chemistry','energy','molecular','atomic','chemical','biochem' ,'organic','polymer','chemical engineering','biotech','coloid'] name = df.Full_Category.str.contains # making", "to ensure only publciations from the desired journal are being", "= {} for year in years: dict3 = {} for", "that all URLs which go through the UW Library Proxy", "# if there is an exception, it means we are", "go through the UW Library proxy so that all of", "df = df.drop_duplicates(subset = 'Journal_Title') # drop any duplicate journals", "item we are looking for pubTitles = find_pubTitle(driver,journal_list[journal_counter]) for url", "to type # new dataframe full of only journals who's", "= clean(scraped_elems) proxy_urls = proxify(scraped_urls,uw_prefix) # not even sure this", "= {} years = np.arange(1995,2020) for journal in journal_list: dict2", "url = gui_prefix + search_terms + '&show=100'+ '&articleTypes=FLA%2CREV' + '&years='+", "file.write('\\n') def find_pubTitle(driver,journal): \"\"\" This method finds the identifying number", "be used to sort which journals we want journal_strings =", "URLs which go through UW Library proxy \"\"\" proxy_urls =", "topics for searching df = df.drop_duplicates(subset = 'Journal_Title') # drop", "with the publication date. Returns ------- Does not return anything", "text file. Parameters ---------- urls (list) : The list of", "the same as the list displayed on gui ScienceDirect \"\"\"", "that journal df = pd.read_excel('elsevier_journals.xls') df.Full_Category = df.Full_Category.str.lower() # lowercase", "journals and creates a tiple nested dictionary containing all accessible", "dict1 def proxify(scraped_urls,uw_prefix): \"\"\" This method takes a list of", "scrape_page(driver): \"\"\" This method finds all the publication result web", "This method takes the list of journals and creates a", "of the webdriver class e.g. webdriver.Chrome() Returns ------- elems (list)", "list of all scraped hrefs from the page \"\"\" elems", "publication result web elements on the webpage. Parameters ---------- driver", "= {} for i in range(60): url = gui_prefix +", "< 100: # after content is saved, go to the", "Proxy start with. Returns ------- proxy_urls (list) : The list", "proxy_urls.append(newlink) return proxy_urls def write_urls(urls,titles,file,journal,year): \"\"\" This method takes a", "page 1, we need to grab the publisher number try:", "them are full access. Parameters ---------- scraped_urls (list) : The", "| name('molecular') | name('colloid') | name('biochem') | name('organic') | name('biotech')", "# scrape the page scraped_urls, titles = clean(scraped_elems) proxy_urls =", "import pandas as pd import bs4 from bs4 import BeautifulSoup", "for offset in np.arange(60): page = url_dict[journal][year][offset] print(\"journal, year, offset", "web elements and filters/ returns only the hrefs leading to", "+ search_terms + '&show=100'+ '&articleTypes=FLA%2CREV' + '&years='+ str(year) if i", "page \"\"\" elems = driver.find_elements_by_class_name('ResultItem') return elems def clean(elems): \"\"\"", "hrefs to be filtered Returns ------- urls (list) : The", "that are indicative of non-html links. Parameters ---------- elems (list)", "pub_elems = driver.find_elements_by_css_selector('input[id*=publicationTitles]') pub_names = [] for elem in pub_elems:", "year break # because we know this is the last", "list of URLs to be saved. file (file object) :", "on sciencedirect. \"\"\" dict1 = {} years = np.arange(1995,2020) for", ": Instance of the webdriver class e.g. webdriver.Chrome() Returns -------", "= [] urls = [] for elem in elems: href_child", "dict3 = {} for i in range(60): url = gui_prefix", "pub_names = [] for elem in pub_elems: pub_name = elem.get_attribute(\"name\")", "to be searched gui_prefix = 'https://www.sciencedirect.com/search/advanced?qs=' search_terms = 'chemistry%20OR%20molecule%20OR%20polymer%20OR%20organic' url_dict", "scraped urls and turns them into urls that go through", "easier command to type # new dataframe full of only", "clean(scraped_elems) proxy_urls = proxify(scraped_urls,uw_prefix) # not even sure this is", "url in scraped_urls: sd_id = url[-17:] newlink = uw_prefix +", "converted URLs which go through UW Library proxy \"\"\" proxy_urls", "returns only the hrefs leading to publications. Filtering includes removing", "bs4 import BeautifulSoup import time from sklearn.utils import shuffle def", "dict3[i] = url dict2[year] = dict3 dict1[journal] = dict2 return", "= scrape_page(driver) # scrape the page scraped_urls, titles = clean(scraped_elems)", "| name('organic') | name('biotech') | name('chemical')] journal_list = df2.Journal_Title #", "shuffle def scrape_page(driver): \"\"\" This method finds all the publication", "web elements on the webpage. Parameters ---------- driver (Selenium webdriver", "= url + '&pubTitles=' + pubTitles # update every url", "= pd.read_excel('elsevier_journals.xls') df.Full_Category = df.Full_Category.str.lower() # lowercase topics for searching", "(str) : The string that all URLs which go through", "= df.Full_Category.str.lower() # lowercase topics for searching df = df.drop_duplicates(subset", "= url dict2[year] = dict3 dict1[journal] = dict2 return dict1", "driver (Selenium webdriver object) : Instance of the webdriver class", "\"\"\" This code is used to scrape ScienceDirect of publication", "a page which won't have the item we are looking", "method takes a list of scraped selenium web elements and", "object) : Instance of the webdriver class e.g. webdriver.Chrome() Returns", "file.write(line) file.write('\\n') def find_pubTitle(driver,journal): \"\"\" This method finds the identifying", "------- Does not return anything \"\"\" for link,title in zip(urls,titles):", "{} for i in range(60): url = gui_prefix + search_terms", "for a specific journal. This identifying number is added to", "master_list = [] file = open(filename,'a+') for journal in journal_list:", "pub_elems: pub_name = elem.get_attribute(\"name\") if pub_name == journal: return elem.get_attribute('id')[-6:]", "in url_dict[journal]: url = url + '&pubTitles=' + pubTitles #", "the list displayed on gui ScienceDirect \"\"\" titles = []", "proxy so that all of them are full access. Parameters", "The string that all URLs which go through the UW", "# The set of default strings that will be used", "df.Full_Category.str.contains # making this an easier command to type #", "0 master_list = [] file = open(filename,'a+') for journal in", "publication date. Returns ------- Does not return anything \"\"\" for", "= df.drop_duplicates(subset = 'Journal_Title') # drop any duplicate journals df", "every url in the list driver.get(url_dict[journal][year][0]) # reload the first", "Library proxy \"\"\" proxy_urls = [] for url in scraped_urls:", "# reload the first page with the new url except:", "{} for year in years: dict3 = {} for i", "try: # we may be at a page which won't", ": The opened .txt file which will be written to.", "is saved, go to the next year break # because", "and write them to a text file in the current", "for year in years: dict3 = {} for i in", "name('colloid') | name('biochem') | name('organic') | name('biotech') | name('chemical')] journal_list", "= open(filename,'a+') for journal in journal_list: for year in np.arange(1995,2020):", "pd import bs4 from bs4 import BeautifulSoup import time from", "journal in journal_list: dict2 = {} for year in years:", "url = url + '&pub=' + journal dict3[i] = url", "\"\"\" titles = [] urls = [] for elem in", "date. Returns ------- Does not return anything \"\"\" for link,title", "journal in journal_list: for year in np.arange(1995,2020): for offset in", ",'organic','polymer','chemical engineering','biotech','coloid'] name = df.Full_Category.str.contains # making this an easier", "which go through UW Library proxy \"\"\" proxy_urls = []", "df.Full_Category = df.Full_Category.str.lower() # lowercase topics for searching df =", "['chemistry','energy','molecular','atomic','chemical','biochem' ,'organic','polymer','chemical engineering','biotech','coloid'] name = df.Full_Category.str.contains # making this an", "which journals we want journal_strings = ['chemistry','energy','molecular','atomic','chemical','biochem' ,'organic','polymer','chemical engineering','biotech','coloid'] name", "to be filtered Returns ------- urls (list) : The new", "all scraped hrefs from the page \"\"\" elems = driver.find_elements_by_class_name('ResultItem')", "int) : The year associated with the publication date. Returns", "year, for each journal, for a given search on sciencedirect.", "or int) : The year associated with the publication date.", "df[name('polymer') | name('chemistry') | name('energy') | name('molecular') | name('colloid') |", "list of urls and writes them to a desired text", "for each journal, for a given search on sciencedirect. \"\"\"", "a list of scraped selenium web elements and filters/ returns", "title = href_child.text titles.append(title) urls.append(url) return urls, titles def build_url_list(gui_prefix,search_terms,journal_list):", "list of hrefs to be filtered Returns ------- urls (list)", "ensure only publciations from the desired journal are being found.", "journals to be searched gui_prefix = 'https://www.sciencedirect.com/search/advanced?qs=' search_terms = 'chemistry%20OR%20molecule%20OR%20polymer%20OR%20organic'", "urls = [] for elem in elems: href_child = elem.find_element_by_css_selector('a[href]')", "i != 0: url = url + '&offset=' + str(i)", "= df[name('polymer') | name('chemistry') | name('energy') | name('molecular') | name('colloid')", "This method takes a list of scraped selenium web elements", "titles def build_url_list(gui_prefix,search_terms,journal_list): \"\"\" This method takes the list of", "an easier command to type # new dataframe full of", "sciencedirect. \"\"\" dict1 = {} years = np.arange(1995,2020) for journal", "dict2 = {} for year in years: dict3 = {}", "year in years: dict3 = {} for i in range(60):", "offset in np.arange(60): page = url_dict[journal][year][offset] print(\"journal, year, offset =", "page properly if offset == 0: # if on page", "UW Library proxy so that all of them are full", "we need to grab the publisher number try: # we", "takes a list of urls and writes them to a", "# lowercase topics for searching df = df.drop_duplicates(subset = 'Journal_Title')", "hrefs from the page \"\"\" elems = driver.find_elements_by_class_name('ResultItem') return elems", "journal_list: dict2 = {} for year in years: dict3 =", "a text file in the current directory for later use.", "| name('colloid') | name('biochem') | name('organic') | name('biotech') | name('chemical')]", "'https://www.sciencedirect.com/search/advanced?qs=' search_terms = 'chemistry%20OR%20molecule%20OR%20polymer%20OR%20organic' url_dict = build_url_list(gui_prefix,search_terms,journal_list) driver = webdriver.Chrome()", "which won't have the item we are looking for pubTitles", "content is saved, go to the next year break #", "is: ',url_counter) if len(scraped_elems) < 100: # after content is", "= driver.find_elements_by_class_name('ResultItem') return elems def clean(elems): \"\"\" This method takes", "+ sd_id if sd_id.startswith('S'): proxy_urls.append(newlink) return proxy_urls def write_urls(urls,titles,file,journal,year): \"\"\"", "saved, go to the next year break # because we", "method finds the identifying number for a specific journal. This", "time from sklearn.utils import shuffle def scrape_page(driver): \"\"\" This method", "Series of only the journals to be searched gui_prefix =", "import webdriver import numpy as np import pandas as pd", "page scraped_elems = scrape_page(driver) # scrape the page scraped_urls, titles", "dict2 return dict1 def proxify(scraped_urls,uw_prefix): \"\"\" This method takes a", "\"\"\" dict1 = {} years = np.arange(1995,2020) for journal in", "from the page \"\"\" elems = driver.find_elements_by_class_name('ResultItem') return elems def", "title + ',' + journal + ',' + str(year) file.write(line)", "clean(elems): \"\"\" This method takes a list of scraped selenium", "year (str or int) : The year associated with the", "+ '&show=100'+ '&articleTypes=FLA%2CREV' + '&years='+ str(year) if i != 0:", "a tiple nested dictionary containing all accessible urls to each", "dict3 dict1[journal] = dict2 return dict1 def proxify(scraped_urls,uw_prefix): \"\"\" This", "from selenium import webdriver import numpy as np import pandas", "The list of converted URLs which go through UW Library", "through UW Library proxy \"\"\" proxy_urls = [] for url", "# not even sure this is needed write_urls(proxy_urls,titles,file,journal,year) url_counter +=", "def proxify(scraped_urls,uw_prefix): \"\"\" This method takes a list of scraped", "time.sleep(2) # need sleep to load the page properly if", "and writes them to a desired text file. Parameters ----------", "year, offset = \",journal,year,offset) driver.get(page) time.sleep(2) # need sleep to", "full access. Parameters ---------- scraped_urls (list) : The list of", "of hrefs, which should be the same as the list", "string that all URLs which go through the UW Library", "href_child.text titles.append(title) urls.append(url) return urls, titles def build_url_list(gui_prefix,search_terms,journal_list): \"\"\" This", "dict1 = {} years = np.arange(1995,2020) for journal in journal_list:", "= [] for url in scraped_urls: sd_id = url[-17:] newlink", "uw_prefix (str) : The string that all URLs which go", "topic description contained the # desired keywords df2 = df[name('polymer')", "proxy \"\"\" proxy_urls = [] for url in scraped_urls: sd_id", "be filtered Returns ------- urls (list) : The new list", "return urls, titles def build_url_list(gui_prefix,search_terms,journal_list): \"\"\" This method takes the", "numpy as np import pandas as pd import bs4 from", "list of converted URLs which go through UW Library proxy", "\",journal,year,offset) driver.get(page) time.sleep(2) # need sleep to load the page", "if len(scraped_elems) < 100: # after content is saved, go", "BeautifulSoup import time from sklearn.utils import shuffle def scrape_page(driver): \"\"\"", "pub_name = elem.get_attribute(\"name\") if pub_name == journal: return elem.get_attribute('id')[-6:] #returns", "into urls that go through the UW Library proxy so", "'&years='+ str(year) if i != 0: url = url +", "of publication urls and write them to a text file", "for later use. \"\"\" import selenium from selenium import webdriver", "finds all the publication result web elements on the webpage.", "[] for elem in pub_elems: pub_name = elem.get_attribute(\"name\") if pub_name", "url_counter += len(proxy_urls) print('Total URLs saved is: ',url_counter) if len(scraped_elems)", "takes a list of scraped selenium web elements and filters/", "pandas as pd import bs4 from bs4 import BeautifulSoup import", "= dict2 return dict1 def proxify(scraped_urls,uw_prefix): \"\"\" This method takes", "if sd_id.startswith('S'): proxy_urls.append(newlink) return proxy_urls def write_urls(urls,titles,file,journal,year): \"\"\" This method", "urls, titles def build_url_list(gui_prefix,search_terms,journal_list): \"\"\" This method takes the list", "file (file object) : The opened .txt file which will", "#returns the identifying number #for that journal df = pd.read_excel('elsevier_journals.xls')", "each journal, for a given search on sciencedirect. \"\"\" dict1", "[] for elem in elems: href_child = elem.find_element_by_css_selector('a[href]') url =", "proxify(scraped_urls,uw_prefix) # not even sure this is needed write_urls(proxy_urls,titles,file,journal,year) url_counter", "df = shuffle(df,random_state = 42) # The set of default", "proxy_urls (list) : The list of converted URLs which go", "sklearn.utils import shuffle def scrape_page(driver): \"\"\" This method finds all", "Returns ------- elems (list) : A list of all scraped", "page with the new url except: pass # if there", "+ str(year) file.write(line) file.write('\\n') def find_pubTitle(driver,journal): \"\"\" This method finds", "df2 = df[name('polymer') | name('chemistry') | name('energy') | name('molecular') |", "are looking for pubTitles = find_pubTitle(driver,journal_list[journal_counter]) for url in url_dict[journal]:", "it means we are on the right page scraped_elems =", "as pd import bs4 from bs4 import BeautifulSoup import time", "def clean(elems): \"\"\" This method takes a list of scraped", ": A list of all scraped hrefs from the page", "use. \"\"\" import selenium from selenium import webdriver import numpy", "\"\"\" This method takes a list of scraped selenium web", "name('molecular') | name('colloid') | name('biochem') | name('organic') | name('biotech') |", "= [] file = open(filename,'a+') for journal in journal_list: for", "with the new url except: pass # if there is", "\"\"\" This method takes the list of journals and creates", "url = href_child.get_attribute('href') title = href_child.text titles.append(title) urls.append(url) return urls,", "go through UW Library proxy \"\"\" proxy_urls = [] for", "sd_id = url[-17:] newlink = uw_prefix + sd_id if sd_id.startswith('S'):", "# need sleep to load the page properly if offset", "+'00' url = url + '&pub=' + journal dict3[i] =", "This method takes a list of scraped urls and turns", "storage: \") url_counter = 0 master_list = [] file =", "name('energy') | name('molecular') | name('colloid') | name('biochem') | name('organic') |", "import numpy as np import pandas as pd import bs4", "proxy_urls = proxify(scraped_urls,uw_prefix) # not even sure this is needed", "(list) : The list of URLs to be converted uw_prefix", "'Journal_Title') # drop any duplicate journals df = shuffle(df,random_state =", "load the page properly if offset == 0: # if", "build_url_list(gui_prefix,search_terms,journal_list) driver = webdriver.Chrome() uw_prefix = 'https://www-sciencedirect-com.offcampus.lib.washington.edu/science/article/pii/' filename = input(\"Input", ": The list of URLs to be saved. file (file", "for url in url_dict[journal]: url = url + '&pubTitles=' +", "The list of hrefs to be filtered Returns ------- urls", "+ ',' + str(year) file.write(line) file.write('\\n') def find_pubTitle(driver,journal): \"\"\" This", "to the next year break # because we know this", "be written to. year (str or int) : The year", "name('organic') | name('biotech') | name('chemical')] journal_list = df2.Journal_Title # Series", "identifying number for a specific journal. This identifying number is", "to. year (str or int) : The year associated with", "the publisher number try: # we may be at a", "as the list displayed on gui ScienceDirect \"\"\" titles =", "+ ',' + title + ',' + journal + ','", "= driver.find_elements_by_css_selector('input[id*=publicationTitles]') pub_names = [] for elem in pub_elems: pub_name", "webdriver.Chrome() Returns ------- elems (list) : A list of all", "scrape_page(driver) # scrape the page scraped_urls, titles = clean(scraped_elems) proxy_urls", "= proxify(scraped_urls,uw_prefix) # not even sure this is needed write_urls(proxy_urls,titles,file,journal,year)", "scraped_urls: sd_id = url[-17:] newlink = uw_prefix + sd_id if", "later use. \"\"\" import selenium from selenium import webdriver import", "identifying number #for that journal df = pd.read_excel('elsevier_journals.xls') df.Full_Category =", "links. Parameters ---------- elems (list) : The list of hrefs", "query URL to ensure only publciations from the desired journal", "def scrape_page(driver): \"\"\" This method finds all the publication result", "making this an easier command to type # new dataframe", "proxy_urls def write_urls(urls,titles,file,journal,year): \"\"\" This method takes a list of", "journals who's topic description contained the # desired keywords df2", "with .txt extension for URL storage: \") url_counter = 0", "publication urls and write them to a text file in", "if offset == 0: # if on page 1, we", ".txt file which will be written to. year (str or", "the current directory for later use. \"\"\" import selenium from", "new dataframe full of only journals who's topic description contained", "the identifying number #for that journal df = pd.read_excel('elsevier_journals.xls') df.Full_Category", "scraped_elems = scrape_page(driver) # scrape the page scraped_urls, titles =", "and turns them into urls that go through the UW", "URLs to be converted uw_prefix (str) : The string that", "df.Full_Category.str.lower() # lowercase topics for searching df = df.drop_duplicates(subset =", ".txt extension for URL storage: \") url_counter = 0 master_list", "are on the right page scraped_elems = scrape_page(driver) # scrape", "gui_prefix + search_terms + '&show=100'+ '&articleTypes=FLA%2CREV' + '&years='+ str(year) if", "urls that go through the UW Library proxy so that", "them to a text file in the current directory for", "in range(60): url = gui_prefix + search_terms + '&show=100'+ '&articleTypes=FLA%2CREV'", "elem.get_attribute(\"name\") if pub_name == journal: return elem.get_attribute('id')[-6:] #returns the identifying", "because we know this is the last page of urls", "'https://www-sciencedirect-com.offcampus.lib.washington.edu/science/article/pii/' filename = input(\"Input filename with .txt extension for URL", "webdriver object) : Instance of the webdriver class e.g. webdriver.Chrome()", "each year, for each journal, for a given search on", "search_terms + '&show=100'+ '&articleTypes=FLA%2CREV' + '&years='+ str(year) if i !=", "webpage. Parameters ---------- driver (Selenium webdriver object) : Instance of", "of hrefs to be filtered Returns ------- urls (list) :", "input(\"Input filename with .txt extension for URL storage: \") url_counter", "number try: # we may be at a page which", "won't have the item we are looking for pubTitles =", "is an exception, it means we are on the right", "# drop any duplicate journals df = shuffle(df,random_state = 42)", "webdriver class e.g. webdriver.Chrome() Returns ------- elems (list) : A", "len(scraped_elems) < 100: # after content is saved, go to", "import BeautifulSoup import time from sklearn.utils import shuffle def scrape_page(driver):", "method takes a list of scraped urls and turns them", "= 'https://www-sciencedirect-com.offcampus.lib.washington.edu/science/article/pii/' filename = input(\"Input filename with .txt extension for", "with. Returns ------- proxy_urls (list) : The list of converted", "any duplicate journals df = shuffle(df,random_state = 42) # The", "= df2.Journal_Title # Series of only the journals to be", "all urls with keywords that are indicative of non-html links.", "webdriver.Chrome() uw_prefix = 'https://www-sciencedirect-com.offcampus.lib.washington.edu/science/article/pii/' filename = input(\"Input filename with .txt", "on gui ScienceDirect \"\"\" titles = [] urls = []", "journal_list: for year in np.arange(1995,2020): for offset in np.arange(60): page", "not even sure this is needed write_urls(proxy_urls,titles,file,journal,year) url_counter += len(proxy_urls)", "journal. This identifying number is added to the gui query", "+ '&offset=' + str(i) +'00' url = url + '&pub='", "= url + '&pub=' + journal dict3[i] = url dict2[year]", "exception, it means we are on the right page scraped_elems", "import selenium from selenium import webdriver import numpy as np", "go through the UW Library Proxy start with. Returns -------", "the identifying number for a specific journal. This identifying number", "description contained the # desired keywords df2 = df[name('polymer') |", "(list) : The new list of hrefs, which should be", "in the current directory for later use. \"\"\" import selenium", "year associated with the publication date. Returns ------- Does not", "text file in the current directory for later use. \"\"\"", "= 'chemistry%20OR%20molecule%20OR%20polymer%20OR%20organic' url_dict = build_url_list(gui_prefix,search_terms,journal_list) driver = webdriver.Chrome() uw_prefix =", "ScienceDirect of publication urls and write them to a text", "scrape ScienceDirect of publication urls and write them to a", "'&offset=' + str(i) +'00' url = url + '&pub=' +", "we are looking for pubTitles = find_pubTitle(driver,journal_list[journal_counter]) for url in", "= href_child.text titles.append(title) urls.append(url) return urls, titles def build_url_list(gui_prefix,search_terms,journal_list): \"\"\"", "drop any duplicate journals df = shuffle(df,random_state = 42) #", "webdriver import numpy as np import pandas as pd import", "driver.get(url_dict[journal][year][0]) # reload the first page with the new url", "opened .txt file which will be written to. year (str", "on page 1, we need to grab the publisher number", "This identifying number is added to the gui query URL", "= 42) # The set of default strings that will", "turns them into urls that go through the UW Library", "years = np.arange(1995,2020) for journal in journal_list: dict2 = {}", "contained the # desired keywords df2 = df[name('polymer') | name('chemistry')", "on the right page scraped_elems = scrape_page(driver) # scrape the", "elements on the webpage. Parameters ---------- driver (Selenium webdriver object)", "in np.arange(1995,2020): for offset in np.arange(60): page = url_dict[journal][year][offset] print(\"journal,", "journal df = pd.read_excel('elsevier_journals.xls') df.Full_Category = df.Full_Category.str.lower() # lowercase topics", "of only the journals to be searched gui_prefix = 'https://www.sciencedirect.com/search/advanced?qs='", "---------- elems (list) : The list of hrefs to be", "the first page with the new url except: pass #", "written to. year (str or int) : The year associated", "url_counter = 0 master_list = [] file = open(filename,'a+') for", "URL storage: \") url_counter = 0 master_list = [] file", "that all of them are full access. Parameters ---------- scraped_urls", "name('biotech') | name('chemical')] journal_list = df2.Journal_Title # Series of only", "Instance of the webdriver class e.g. webdriver.Chrome() Returns ------- elems", "find_pubTitle(driver,journal): \"\"\" This method finds the identifying number for a", "pd.read_excel('elsevier_journals.xls') df.Full_Category = df.Full_Category.str.lower() # lowercase topics for searching df", "if i != 0: url = url + '&offset=' +", "even sure this is needed write_urls(proxy_urls,titles,file,journal,year) url_counter += len(proxy_urls) print('Total", "------- proxy_urls (list) : The list of converted URLs which", "next year break # because we know this is the", "includes removing all urls with keywords that are indicative of", "a list of scraped urls and turns them into urls", "href_child = elem.find_element_by_css_selector('a[href]') url = href_child.get_attribute('href') title = href_child.text titles.append(title)", "page, in each year, for each journal, for a given", "elements and filters/ returns only the hrefs leading to publications.", "name('chemical')] journal_list = df2.Journal_Title # Series of only the journals", "# if on page 1, we need to grab the", "= uw_prefix + sd_id if sd_id.startswith('S'): proxy_urls.append(newlink) return proxy_urls def", "Returns ------- Does not return anything \"\"\" for link,title in", "range(60): url = gui_prefix + search_terms + '&show=100'+ '&articleTypes=FLA%2CREV' +", "removing all urls with keywords that are indicative of non-html", "all of them are full access. Parameters ---------- scraped_urls (list)", "'&pubTitles=' + pubTitles # update every url in the list", "the last page of urls for this year file.close() driver.quit()", "100: # after content is saved, go to the next", "the webpage. Parameters ---------- driver (Selenium webdriver object) : Instance", "have the item we are looking for pubTitles = find_pubTitle(driver,journal_list[journal_counter])", "and filters/ returns only the hrefs leading to publications. Filtering", "type # new dataframe full of only journals who's topic", "---------- scraped_urls (list) : The list of URLs to be", "of all scraped hrefs from the page \"\"\" elems =", "saved. file (file object) : The opened .txt file which", "= [] for elem in pub_elems: pub_name = elem.get_attribute(\"name\") if", "str(i) +'00' url = url + '&pub=' + journal dict3[i]", "== journal: return elem.get_attribute('id')[-6:] #returns the identifying number #for that", "+= len(proxy_urls) print('Total URLs saved is: ',url_counter) if len(scraped_elems) <", "URLs which go through the UW Library Proxy start with.", "url_dict[journal][year][offset] print(\"journal, year, offset = \",journal,year,offset) driver.get(page) time.sleep(2) # need", "= input(\"Input filename with .txt extension for URL storage: \")", "to a text file in the current directory for later", "only the hrefs leading to publications. Filtering includes removing all", "as np import pandas as pd import bs4 from bs4", "search on sciencedirect. \"\"\" dict1 = {} years = np.arange(1995,2020)", "def find_pubTitle(driver,journal): \"\"\" This method finds the identifying number for", "for pubTitles = find_pubTitle(driver,journal_list[journal_counter]) for url in url_dict[journal]: url =", "creates a tiple nested dictionary containing all accessible urls to", "link + ',' + title + ',' + journal +", "the new url except: pass # if there is an", "\"\"\" This method takes a list of urls and writes", "name('biochem') | name('organic') | name('biotech') | name('chemical')] journal_list = df2.Journal_Title", "the publication date. Returns ------- Does not return anything \"\"\"", "name('chemistry') | name('energy') | name('molecular') | name('colloid') | name('biochem') |", "filtered Returns ------- urls (list) : The new list of", "urls.append(url) return urls, titles def build_url_list(gui_prefix,search_terms,journal_list): \"\"\" This method takes", "publciations from the desired journal are being found. \"\"\" pub_elems", "titles = clean(scraped_elems) proxy_urls = proxify(scraped_urls,uw_prefix) # not even sure", "== 0: # if on page 1, we need to", "elems (list) : A list of all scraped hrefs from", "filters/ returns only the hrefs leading to publications. Filtering includes", "This code is used to scrape ScienceDirect of publication urls", "list of hrefs, which should be the same as the", "= np.arange(1995,2020) for journal in journal_list: dict2 = {} for", "not return anything \"\"\" for link,title in zip(urls,titles): line =", "sleep to load the page properly if offset == 0:", "pub_name == journal: return elem.get_attribute('id')[-6:] #returns the identifying number #for", "scrape the page scraped_urls, titles = clean(scraped_elems) proxy_urls = proxify(scraped_urls,uw_prefix)", "elems: href_child = elem.find_element_by_css_selector('a[href]') url = href_child.get_attribute('href') title = href_child.text", "return elem.get_attribute('id')[-6:] #returns the identifying number #for that journal df", "Parameters ---------- elems (list) : The list of hrefs to", "print('Total URLs saved is: ',url_counter) if len(scraped_elems) < 100: #", "only the journals to be searched gui_prefix = 'https://www.sciencedirect.com/search/advanced?qs=' search_terms", "a desired text file. Parameters ---------- urls (list) : The", "associated with the publication date. Returns ------- Does not return", "for year in np.arange(1995,2020): for offset in np.arange(60): page =", "# making this an easier command to type # new", "np.arange(1995,2020) for journal in journal_list: dict2 = {} for year", "',' + str(year) file.write(line) file.write('\\n') def find_pubTitle(driver,journal): \"\"\" This method", "Parameters ---------- driver (Selenium webdriver object) : Instance of the", "in the list driver.get(url_dict[journal][year][0]) # reload the first page with", "# update every url in the list driver.get(url_dict[journal][year][0]) # reload", "bs4 from bs4 import BeautifulSoup import time from sklearn.utils import", "of scraped selenium web elements and filters/ returns only the", "in pub_elems: pub_name = elem.get_attribute(\"name\") if pub_name == journal: return", "the UW Library Proxy start with. Returns ------- proxy_urls (list)", "write them to a text file in the current directory", "for URL storage: \") url_counter = 0 master_list = []", "url in url_dict[journal]: url = url + '&pubTitles=' + pubTitles", "so that all of them are full access. Parameters ----------", "class e.g. webdriver.Chrome() Returns ------- elems (list) : A list", "build_url_list(gui_prefix,search_terms,journal_list): \"\"\" This method takes the list of journals and", "to be saved. file (file object) : The opened .txt", "update every url in the list driver.get(url_dict[journal][year][0]) # reload the", "from bs4 import BeautifulSoup import time from sklearn.utils import shuffle", "of converted URLs which go through UW Library proxy \"\"\"", "duplicate journals df = shuffle(df,random_state = 42) # The set", "used to sort which journals we want journal_strings = ['chemistry','energy','molecular','atomic','chemical','biochem'", "line = link + ',' + title + ',' +", "df.drop_duplicates(subset = 'Journal_Title') # drop any duplicate journals df =", "newlink = uw_prefix + sd_id if sd_id.startswith('S'): proxy_urls.append(newlink) return proxy_urls", "The list of URLs to be saved. file (file object)", "url_dict = build_url_list(gui_prefix,search_terms,journal_list) driver = webdriver.Chrome() uw_prefix = 'https://www-sciencedirect-com.offcampus.lib.washington.edu/science/article/pii/' filename", "selenium from selenium import webdriver import numpy as np import", "from the desired journal are being found. \"\"\" pub_elems =", "driver = webdriver.Chrome() uw_prefix = 'https://www-sciencedirect-com.offcampus.lib.washington.edu/science/article/pii/' filename = input(\"Input filename", "journal dict3[i] = url dict2[year] = dict3 dict1[journal] = dict2", "'&show=100'+ '&articleTypes=FLA%2CREV' + '&years='+ str(year) if i != 0: url", "Parameters ---------- urls (list) : The list of URLs to", "elems (list) : The list of hrefs to be filtered", "# desired keywords df2 = df[name('polymer') | name('chemistry') | name('energy')", "them to a desired text file. Parameters ---------- urls (list)", "we know this is the last page of urls for", "means we are on the right page scraped_elems = scrape_page(driver)", "of non-html links. Parameters ---------- elems (list) : The list", "the right page scraped_elems = scrape_page(driver) # scrape the page", "= url[-17:] newlink = uw_prefix + sd_id if sd_id.startswith('S'): proxy_urls.append(newlink)", "+ ',' + journal + ',' + str(year) file.write(line) file.write('\\n')", "---------- driver (Selenium webdriver object) : Instance of the webdriver", "default strings that will be used to sort which journals", "offset = \",journal,year,offset) driver.get(page) time.sleep(2) # need sleep to load", "right page scraped_elems = scrape_page(driver) # scrape the page scraped_urls,", "link,title in zip(urls,titles): line = link + ',' + title", "which go through the UW Library Proxy start with. Returns", "(list) : The list of hrefs to be filtered Returns", "open(filename,'a+') for journal in journal_list: for year in np.arange(1995,2020): for", "and creates a tiple nested dictionary containing all accessible urls", "the list of journals and creates a tiple nested dictionary", "URLs to be saved. file (file object) : The opened", "to each page, in each year, for each journal, for", "through the UW Library proxy so that all of them", "sd_id.startswith('S'): proxy_urls.append(newlink) return proxy_urls def write_urls(urls,titles,file,journal,year): \"\"\" This method takes", "method finds all the publication result web elements on the", "publications. Filtering includes removing all urls with keywords that are", "the journals to be searched gui_prefix = 'https://www.sciencedirect.com/search/advanced?qs=' search_terms =", "of default strings that will be used to sort which", "start with. Returns ------- proxy_urls (list) : The list of", "writes them to a desired text file. Parameters ---------- urls", "42) # The set of default strings that will be", "\"\"\" This method finds all the publication result web elements", "= elem.find_element_by_css_selector('a[href]') url = href_child.get_attribute('href') title = href_child.text titles.append(title) urls.append(url)", "new url except: pass # if there is an exception,", "set of default strings that will be used to sort", "number #for that journal df = pd.read_excel('elsevier_journals.xls') df.Full_Category = df.Full_Category.str.lower()", "return anything \"\"\" for link,title in zip(urls,titles): line = link", "if there is an exception, it means we are on", "all accessible urls to each page, in each year, for", "\"\"\" import selenium from selenium import webdriver import numpy as", "this is needed write_urls(proxy_urls,titles,file,journal,year) url_counter += len(proxy_urls) print('Total URLs saved", "(list) : A list of all scraped hrefs from the", ": The list of converted URLs which go through UW", "are indicative of non-html links. Parameters ---------- elems (list) :", "Returns ------- urls (list) : The new list of hrefs,", "to publications. Filtering includes removing all urls with keywords that", "list of scraped urls and turns them into urls that", "the list driver.get(url_dict[journal][year][0]) # reload the first page with the", "result web elements on the webpage. Parameters ---------- driver (Selenium", "given search on sciencedirect. \"\"\" dict1 = {} years =", "Returns ------- proxy_urls (list) : The list of converted URLs", "urls with keywords that are indicative of non-html links. Parameters", "the page properly if offset == 0: # if on", "list driver.get(url_dict[journal][year][0]) # reload the first page with the new", "takes a list of scraped urls and turns them into", "in years: dict3 = {} for i in range(60): url", "uw_prefix + sd_id if sd_id.startswith('S'): proxy_urls.append(newlink) return proxy_urls def write_urls(urls,titles,file,journal,year):", "this an easier command to type # new dataframe full", "that go through the UW Library proxy so that all", "the item we are looking for pubTitles = find_pubTitle(driver,journal_list[journal_counter]) for", "url + '&pub=' + journal dict3[i] = url dict2[year] =", "of urls and writes them to a desired text file.", "+ str(i) +'00' url = url + '&pub=' + journal", "The set of default strings that will be used to", "shuffle(df,random_state = 42) # The set of default strings that", "------- elems (list) : A list of all scraped hrefs", "gui_prefix = 'https://www.sciencedirect.com/search/advanced?qs=' search_terms = 'chemistry%20OR%20molecule%20OR%20polymer%20OR%20organic' url_dict = build_url_list(gui_prefix,search_terms,journal_list) driver", "leading to publications. Filtering includes removing all urls with keywords", "is used to scrape ScienceDirect of publication urls and write", "np import pandas as pd import bs4 from bs4 import", "all the publication result web elements on the webpage. Parameters", "scraped selenium web elements and filters/ returns only the hrefs", "list of URLs to be converted uw_prefix (str) : The", "found. \"\"\" pub_elems = driver.find_elements_by_css_selector('input[id*=publicationTitles]') pub_names = [] for elem", "\"\"\" proxy_urls = [] for url in scraped_urls: sd_id =", "= elem.get_attribute(\"name\") if pub_name == journal: return elem.get_attribute('id')[-6:] #returns the", "url dict2[year] = dict3 dict1[journal] = dict2 return dict1 def", "for elem in elems: href_child = elem.find_element_by_css_selector('a[href]') url = href_child.get_attribute('href')", "need sleep to load the page properly if offset ==", "sd_id if sd_id.startswith('S'): proxy_urls.append(newlink) return proxy_urls def write_urls(urls,titles,file,journal,year): \"\"\" This", "a specific journal. This identifying number is added to the", "for a given search on sciencedirect. \"\"\" dict1 = {}", "The year associated with the publication date. Returns ------- Does", "for journal in journal_list: for year in np.arange(1995,2020): for offset", "reload the first page with the new url except: pass", "np.arange(60): page = url_dict[journal][year][offset] print(\"journal, year, offset = \",journal,year,offset) driver.get(page)", ": The year associated with the publication date. Returns -------", "the webdriver class e.g. webdriver.Chrome() Returns ------- elems (list) :", "#for that journal df = pd.read_excel('elsevier_journals.xls') df.Full_Category = df.Full_Category.str.lower() #", "we are on the right page scraped_elems = scrape_page(driver) #", "= gui_prefix + search_terms + '&show=100'+ '&articleTypes=FLA%2CREV' + '&years='+ str(year)", "len(proxy_urls) print('Total URLs saved is: ',url_counter) if len(scraped_elems) < 100:", "number for a specific journal. This identifying number is added", "elem in elems: href_child = elem.find_element_by_css_selector('a[href]') url = href_child.get_attribute('href') title", "engineering','biotech','coloid'] name = df.Full_Category.str.contains # making this an easier command", "go to the next year break # because we know", "[] file = open(filename,'a+') for journal in journal_list: for year", "# because we know this is the last page of", "keywords df2 = df[name('polymer') | name('chemistry') | name('energy') | name('molecular')", "urls (list) : The list of URLs to be saved.", "for elem in pub_elems: pub_name = elem.get_attribute(\"name\") if pub_name ==", "URL to ensure only publciations from the desired journal are", "= build_url_list(gui_prefix,search_terms,journal_list) driver = webdriver.Chrome() uw_prefix = 'https://www-sciencedirect-com.offcampus.lib.washington.edu/science/article/pii/' filename =", "for i in range(60): url = gui_prefix + search_terms +", "url = url + '&pubTitles=' + pubTitles # update every", "= link + ',' + title + ',' + journal", "if on page 1, we need to grab the publisher", "Filtering includes removing all urls with keywords that are indicative", "return proxy_urls def write_urls(urls,titles,file,journal,year): \"\"\" This method takes a list", "should be the same as the list displayed on gui", "new list of hrefs, which should be the same as", "',' + journal + ',' + str(year) file.write(line) file.write('\\n') def", "the # desired keywords df2 = df[name('polymer') | name('chemistry') |", "will be used to sort which journals we want journal_strings", "only publciations from the desired journal are being found. \"\"\"", "zip(urls,titles): line = link + ',' + title + ','", "url + '&pubTitles=' + pubTitles # update every url in" ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "Any] Granularity = Union[str, Dict[str, Union[str, float]]] AdhocMetric = Dict[str,", "= Union[List[DbapiDescriptionRow], Tuple[DbapiDescriptionRow, ...]] DbapiResult = Sequence[Union[List[Any], Tuple[Any, ...]]] FilterValue", "Flask response. Base = Union[bytes, str] Status = Union[int, str]", "OF ANY # KIND, either express or implied. See the", "under the License. from datetime import datetime from typing import", "from flask import Flask from flask_caching import Cache from werkzeug.wrappers", "DbapiDescriptionRow = Tuple[ str, str, Optional[str], Optional[str], Optional[int], Optional[int], bool", "Software Foundation (ASF) under one # or more contributor license", "Optional[int], Optional[int], bool ] DbapiDescription = Union[List[DbapiDescriptionRow], Tuple[DbapiDescriptionRow, ...]] DbapiResult", "more contributor license agreements. See the NOTICE file # distributed", "Unless required by applicable law or agreed to in writing,", "flask_caching import Cache from werkzeug.wrappers import Response CacheConfig = Union[Callable[[Flask],", "= Dict[str, Any] Metric = Union[AdhocMetric, str] OrderBy = Tuple[Metric,", "str] OrderBy = Tuple[Metric, bool] QueryObjectDict = Dict[str, Any] VizData", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "str, str, Optional[str], Optional[str], Optional[int], Optional[int], bool ] DbapiDescription =", "# regarding copyright ownership. The ASF licenses this file #", "Union[Callable[[Flask], Cache], Dict[str, Any]] DbapiDescriptionRow = Tuple[ str, str, Optional[str],", "Apache Software Foundation (ASF) under one # or more contributor", "Any] Metric = Union[AdhocMetric, str] OrderBy = Tuple[Metric, bool] QueryObjectDict", "in compliance # with the License. You may obtain a", "# to you under the Apache License, Version 2.0 (the", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "License for the # specific language governing permissions and limitations", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "with this work for additional information # regarding copyright ownership.", "(ASF) under one # or more contributor license agreements. See", "2.0 (the # \"License\"); you may not use this file", "OR CONDITIONS OF ANY # KIND, either express or implied.", "# or more contributor license agreements. See the NOTICE file", "agreed to in writing, # software distributed under the License", "= Union[int, str] Headers = Dict[str, Any] FlaskResponse = Union[", "AdhocMetric = Dict[str, Any] Metric = Union[AdhocMetric, str] OrderBy =", "# Flask response. Base = Union[bytes, str] Status = Union[int,", "Headers = Dict[str, Any] FlaskResponse = Union[ Response, Base, Tuple[Base,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "Tuple[ str, str, Optional[str], Optional[str], Optional[int], Optional[int], bool ] DbapiDescription", "Tuple[DbapiDescriptionRow, ...]] DbapiResult = Sequence[Union[List[Any], Tuple[Any, ...]]] FilterValue = Union[datetime,", "work for additional information # regarding copyright ownership. The ASF", "specific language governing permissions and limitations # under the License.", "under the License is distributed on an # \"AS IS\"", "this file # to you under the Apache License, Version", "distributed under the License is distributed on an # \"AS", "import Flask from flask_caching import Cache from werkzeug.wrappers import Response", "Status = Union[int, str] Headers = Dict[str, Any] FlaskResponse =", "Sequence[Union[List[Any], Tuple[Any, ...]]] FilterValue = Union[datetime, float, int, str] FilterValues", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "flask import Flask from flask_caching import Cache from werkzeug.wrappers import", "copyright ownership. The ASF licenses this file # to you", "Dict, List, Optional, Sequence, Tuple, Union from flask import Flask", "Granularity = Union[str, Dict[str, Union[str, float]]] AdhocMetric = Dict[str, Any]", "# software distributed under the License is distributed on an", "DbapiDescription = Union[List[DbapiDescriptionRow], Tuple[DbapiDescriptionRow, ...]] DbapiResult = Sequence[Union[List[Any], Tuple[Any, ...]]]", "Union[datetime, float, int, str] FilterValues = Union[FilterValue, List[FilterValue], Tuple[FilterValue]] FormData", "Tuple, Union from flask import Flask from flask_caching import Cache", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "List[FilterValue], Tuple[FilterValue]] FormData = Dict[str, Any] Granularity = Union[str, Dict[str,", "(the # \"License\"); you may not use this file except", "the License. You may obtain a copy of the License", "in writing, # software distributed under the License is distributed", "Union[str, Dict[str, Union[str, float]]] AdhocMetric = Dict[str, Any] Metric =", "= Dict[str, Any] Granularity = Union[str, Dict[str, Union[str, float]]] AdhocMetric", "Metric = Union[AdhocMetric, str] OrderBy = Tuple[Metric, bool] QueryObjectDict =", "distributed with this work for additional information # regarding copyright", "Flask from flask_caching import Cache from werkzeug.wrappers import Response CacheConfig", "Cache], Dict[str, Any]] DbapiDescriptionRow = Tuple[ str, str, Optional[str], Optional[str],", "Any]]] VizPayload = Dict[str, Any] # Flask response. Base =", "Dict[str, Any] # Flask response. Base = Union[bytes, str] Status", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "License is distributed on an # \"AS IS\" BASIS, WITHOUT", "ASF licenses this file # to you under the Apache", "from datetime import datetime from typing import Any, Callable, Dict,", "Tuple[FilterValue]] FormData = Dict[str, Any] Granularity = Union[str, Dict[str, Union[str,", "under the Apache License, Version 2.0 (the # \"License\"); you", "for the # specific language governing permissions and limitations #", "Union[FilterValue, List[FilterValue], Tuple[FilterValue]] FormData = Dict[str, Any] Granularity = Union[str,", "= Union[ Response, Base, Tuple[Base, Status], Tuple[Base, Status, Headers], ]", "import Response CacheConfig = Union[Callable[[Flask], Cache], Dict[str, Any]] DbapiDescriptionRow =", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "regarding copyright ownership. The ASF licenses this file # to", "limitations # under the License. from datetime import datetime from", "See the License for the # specific language governing permissions", "to in writing, # software distributed under the License is", "or agreed to in writing, # software distributed under the", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "= Optional[Union[List[Any], Dict[Any, Any]]] VizPayload = Dict[str, Any] # Flask", "ownership. The ASF licenses this file # to you under", "= Sequence[Union[List[Any], Tuple[Any, ...]]] FilterValue = Union[datetime, float, int, str]", "FormData = Dict[str, Any] Granularity = Union[str, Dict[str, Union[str, float]]]", "= Dict[str, Any] VizData = Optional[Union[List[Any], Dict[Any, Any]]] VizPayload =", "= Dict[str, Any] # Flask response. Base = Union[bytes, str]", "datetime import datetime from typing import Any, Callable, Dict, List,", "Dict[str, Union[str, float]]] AdhocMetric = Dict[str, Any] Metric = Union[AdhocMetric,", "# \"License\"); you may not use this file except in", "Any, Callable, Dict, List, Optional, Sequence, Tuple, Union from flask", "= Union[FilterValue, List[FilterValue], Tuple[FilterValue]] FormData = Dict[str, Any] Granularity =", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "Union from flask import Flask from flask_caching import Cache from", "VizData = Optional[Union[List[Any], Dict[Any, Any]]] VizPayload = Dict[str, Any] #", "CacheConfig = Union[Callable[[Flask], Cache], Dict[str, Any]] DbapiDescriptionRow = Tuple[ str,", "Dict[str, Any] Granularity = Union[str, Dict[str, Union[str, float]]] AdhocMetric =", "to the Apache Software Foundation (ASF) under one # or", "\"License\"); you may not use this file except in compliance", "file # distributed with this work for additional information #", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "with the License. You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "] DbapiDescription = Union[List[DbapiDescriptionRow], Tuple[DbapiDescriptionRow, ...]] DbapiResult = Sequence[Union[List[Any], Tuple[Any,", "= Union[bytes, str] Status = Union[int, str] Headers = Dict[str,", "or more contributor license agreements. See the NOTICE file #", "Cache from werkzeug.wrappers import Response CacheConfig = Union[Callable[[Flask], Cache], Dict[str,", "Any] # Flask response. Base = Union[bytes, str] Status =", "import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union from", "applicable law or agreed to in writing, # software distributed", "# distributed with this work for additional information # regarding", "this work for additional information # regarding copyright ownership. The", "= Union[Callable[[Flask], Cache], Dict[str, Any]] DbapiDescriptionRow = Tuple[ str, str,", "writing, # software distributed under the License is distributed on", "= Tuple[Metric, bool] QueryObjectDict = Dict[str, Any] VizData = Optional[Union[List[Any],", "List, Optional, Sequence, Tuple, Union from flask import Flask from", "the NOTICE file # distributed with this work for additional", "Optional[str], Optional[int], Optional[int], bool ] DbapiDescription = Union[List[DbapiDescriptionRow], Tuple[DbapiDescriptionRow, ...]]", "Union[int, str] Headers = Dict[str, Any] FlaskResponse = Union[ Response,", "language governing permissions and limitations # under the License. from", "float]]] AdhocMetric = Dict[str, Any] Metric = Union[AdhocMetric, str] OrderBy", "Tuple[Metric, bool] QueryObjectDict = Dict[str, Any] VizData = Optional[Union[List[Any], Dict[Any,", "Dict[str, Any] VizData = Optional[Union[List[Any], Dict[Any, Any]]] VizPayload = Dict[str,", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "response. Base = Union[bytes, str] Status = Union[int, str] Headers", "implied. See the License for the # specific language governing", "file # to you under the Apache License, Version 2.0", "str, Optional[str], Optional[str], Optional[int], Optional[int], bool ] DbapiDescription = Union[List[DbapiDescriptionRow],", "FlaskResponse = Union[ Response, Base, Tuple[Base, Status], Tuple[Base, Status, Headers],", "to you under the Apache License, Version 2.0 (the #", "Union[bytes, str] Status = Union[int, str] Headers = Dict[str, Any]", "CONDITIONS OF ANY # KIND, either express or implied. See", "License. from datetime import datetime from typing import Any, Callable,", "# with the License. You may obtain a copy of", "Dict[str, Any] Metric = Union[AdhocMetric, str] OrderBy = Tuple[Metric, bool]", "# under the License. from datetime import datetime from typing", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "Union[str, float]]] AdhocMetric = Dict[str, Any] Metric = Union[AdhocMetric, str]", "the License. from datetime import datetime from typing import Any,", "datetime from typing import Any, Callable, Dict, List, Optional, Sequence,", "str] Status = Union[int, str] Headers = Dict[str, Any] FlaskResponse", "governing permissions and limitations # under the License. from datetime", "= Union[datetime, float, int, str] FilterValues = Union[FilterValue, List[FilterValue], Tuple[FilterValue]]", "may not use this file except in compliance # with", "typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union", "software distributed under the License is distributed on an #", "Licensed to the Apache Software Foundation (ASF) under one #", "str] Headers = Dict[str, Any] FlaskResponse = Union[ Response, Base,", "<filename>superset/typing.py<gh_stars>1-10 # Licensed to the Apache Software Foundation (ASF) under", "for additional information # regarding copyright ownership. The ASF licenses", "...]]] FilterValue = Union[datetime, float, int, str] FilterValues = Union[FilterValue,", "Tuple[Any, ...]]] FilterValue = Union[datetime, float, int, str] FilterValues =", "= Dict[str, Any] FlaskResponse = Union[ Response, Base, Tuple[Base, Status],", "the Apache Software Foundation (ASF) under one # or more", "Union[List[DbapiDescriptionRow], Tuple[DbapiDescriptionRow, ...]] DbapiResult = Sequence[Union[List[Any], Tuple[Any, ...]]] FilterValue =", "FilterValues = Union[FilterValue, List[FilterValue], Tuple[FilterValue]] FormData = Dict[str, Any] Granularity", "VizPayload = Dict[str, Any] # Flask response. Base = Union[bytes,", "# # Unless required by applicable law or agreed to", "Version 2.0 (the # \"License\"); you may not use this", "from werkzeug.wrappers import Response CacheConfig = Union[Callable[[Flask], Cache], Dict[str, Any]]", "under one # or more contributor license agreements. See the", "Response CacheConfig = Union[Callable[[Flask], Cache], Dict[str, Any]] DbapiDescriptionRow = Tuple[", "one # or more contributor license agreements. See the NOTICE", "License, Version 2.0 (the # \"License\"); you may not use", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "either express or implied. See the License for the #", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "Sequence, Tuple, Union from flask import Flask from flask_caching import", "and limitations # under the License. from datetime import datetime", "Callable, Dict, List, Optional, Sequence, Tuple, Union from flask import", "KIND, either express or implied. See the License for the", "information # regarding copyright ownership. The ASF licenses this file", "the Apache License, Version 2.0 (the # \"License\"); you may", "FilterValue = Union[datetime, float, int, str] FilterValues = Union[FilterValue, List[FilterValue],", "Base = Union[bytes, str] Status = Union[int, str] Headers =", "except in compliance # with the License. You may obtain", "additional information # regarding copyright ownership. The ASF licenses this", "you under the Apache License, Version 2.0 (the # \"License\");", "str] FilterValues = Union[FilterValue, List[FilterValue], Tuple[FilterValue]] FormData = Dict[str, Any]", "import Cache from werkzeug.wrappers import Response CacheConfig = Union[Callable[[Flask], Cache],", "or implied. See the License for the # specific language", "= Union[AdhocMetric, str] OrderBy = Tuple[Metric, bool] QueryObjectDict = Dict[str,", "See the NOTICE file # distributed with this work for", "# KIND, either express or implied. See the License for", "express or implied. See the License for the # specific", "Any] VizData = Optional[Union[List[Any], Dict[Any, Any]]] VizPayload = Dict[str, Any]", "NOTICE file # distributed with this work for additional information", "this file except in compliance # with the License. You", "agreements. See the NOTICE file # distributed with this work", "Apache License, Version 2.0 (the # \"License\"); you may not", "float, int, str] FilterValues = Union[FilterValue, List[FilterValue], Tuple[FilterValue]] FormData =", "the # specific language governing permissions and limitations # under", "licenses this file # to you under the Apache License,", "OrderBy = Tuple[Metric, bool] QueryObjectDict = Dict[str, Any] VizData =", "= Tuple[ str, str, Optional[str], Optional[str], Optional[int], Optional[int], bool ]", "Any] FlaskResponse = Union[ Response, Base, Tuple[Base, Status], Tuple[Base, Status,", "license agreements. See the NOTICE file # distributed with this", "import datetime from typing import Any, Callable, Dict, List, Optional,", "required by applicable law or agreed to in writing, #", "by applicable law or agreed to in writing, # software", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "Optional[int], bool ] DbapiDescription = Union[List[DbapiDescriptionRow], Tuple[DbapiDescriptionRow, ...]] DbapiResult =", "...]] DbapiResult = Sequence[Union[List[Any], Tuple[Any, ...]]] FilterValue = Union[datetime, float,", "Dict[str, Any] FlaskResponse = Union[ Response, Base, Tuple[Base, Status], Tuple[Base,", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "The ASF licenses this file # to you under the", "file except in compliance # with the License. You may", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "# specific language governing permissions and limitations # under the", "Any]] DbapiDescriptionRow = Tuple[ str, str, Optional[str], Optional[str], Optional[int], Optional[int],", "the License for the # specific language governing permissions and", "License. You may obtain a copy of the License at", "bool ] DbapiDescription = Union[List[DbapiDescriptionRow], Tuple[DbapiDescriptionRow, ...]] DbapiResult = Sequence[Union[List[Any],", "You may obtain a copy of the License at #", "ANY # KIND, either express or implied. See the License", "from flask_caching import Cache from werkzeug.wrappers import Response CacheConfig =", "Optional[str], Optional[str], Optional[int], Optional[int], bool ] DbapiDescription = Union[List[DbapiDescriptionRow], Tuple[DbapiDescriptionRow,", "# Licensed to the Apache Software Foundation (ASF) under one", "Dict[Any, Any]]] VizPayload = Dict[str, Any] # Flask response. Base", "the License is distributed on an # \"AS IS\" BASIS,", "you may not use this file except in compliance #", "werkzeug.wrappers import Response CacheConfig = Union[Callable[[Flask], Cache], Dict[str, Any]] DbapiDescriptionRow", "DbapiResult = Sequence[Union[List[Any], Tuple[Any, ...]]] FilterValue = Union[datetime, float, int,", "= Union[str, Dict[str, Union[str, float]]] AdhocMetric = Dict[str, Any] Metric", "Union[AdhocMetric, str] OrderBy = Tuple[Metric, bool] QueryObjectDict = Dict[str, Any]", "from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple,", "use this file except in compliance # with the License.", "compliance # with the License. You may obtain a copy", "Dict[str, Any]] DbapiDescriptionRow = Tuple[ str, str, Optional[str], Optional[str], Optional[int],", "Optional[Union[List[Any], Dict[Any, Any]]] VizPayload = Dict[str, Any] # Flask response.", "law or agreed to in writing, # software distributed under", "contributor license agreements. See the NOTICE file # distributed with", "Optional, Sequence, Tuple, Union from flask import Flask from flask_caching", "bool] QueryObjectDict = Dict[str, Any] VizData = Optional[Union[List[Any], Dict[Any, Any]]]", "Foundation (ASF) under one # or more contributor license agreements.", "permissions and limitations # under the License. from datetime import", "not use this file except in compliance # with the", "int, str] FilterValues = Union[FilterValue, List[FilterValue], Tuple[FilterValue]] FormData = Dict[str,", "QueryObjectDict = Dict[str, Any] VizData = Optional[Union[List[Any], Dict[Any, Any]]] VizPayload" ]
[ "\"python_compiler\": platform.python_compiler(), \"python_implementation\": platform.python_implementation(), \"python_version\": platform.python_version(), \"release\": platform.release(), \"system\": platform.system(),", "dev in usb.core.find(find_all=True): yield { \"port\": dev.port_number, \"vendor_id\": format_hex(dev.idVendor), \"product_id\":", "in usb.core.find(find_all=True): yield { \"port\": dev.port_number, \"vendor_id\": format_hex(dev.idVendor), \"product_id\": format_hex(dev.idProduct),", "print(json.dumps(data, indent=4)) print(\"System info gathered successfully - saved as \\\"log_system_information.json\\\"\")", "\"architecture\": ' '.join(platform.architecture()).strip(), \"machine\": platform.machine(), \"platform\": platform.platform(), \"processor\": platform.processor(), \"python_build\":", "\"python_build\": ' '.join(platform.python_build()).strip(), \"python_compiler\": platform.python_compiler(), \"python_implementation\": platform.python_implementation(), \"python_version\": platform.python_version(), \"release\":", "try: import usb.core except ImportError: yield \"NoLib\" return speeds =", "if not anonymous: result[\"uname\"] = ' '.join(platform.uname()).strip(), return result if", "json.dump(data, f, indent=4) print(json.dumps(data, indent=4)) print(\"System info gathered successfully -", "\"processor\": platform.processor(), \"python_build\": ' '.join(platform.python_build()).strip(), \"python_compiler\": platform.python_compiler(), \"python_implementation\": platform.python_implementation(), \"python_version\":", "\"system\": platform.system(), \"version\": platform.version(), \"win32_ver\": ' '.join(platform.win32_ver()).strip(), } if not", "found\" result = { \"architecture\": ' '.join(platform.architecture()).strip(), \"machine\": platform.machine(), \"platform\":", "get_usb(): try: import usb.core except ImportError: yield \"NoLib\" return speeds", "data = make_sys_report() with open(\"log_system_information.json\", \"w\") as f: json.dump(data, f,", "} if not skipPackages: from pip._internal.operations.freeze import freeze result[\"packages\"] =", "result if __name__ == \"__main__\": data = make_sys_report() with open(\"log_system_information.json\",", "result[\"usb\"] = list(get_usb()) if not anonymous: result[\"uname\"] = ' '.join(platform.uname()).strip(),", "\"release\": platform.release(), \"system\": platform.system(), \"version\": platform.version(), \"win32_ver\": ' '.join(platform.win32_ver()).strip(), }", "if __name__ == \"__main__\": data = make_sys_report() with open(\"log_system_information.json\", \"w\")", "\"Full\", \"High\", \"Super\", \"SuperPlus\"] format_hex = lambda val: f\"{val:#0{6}x}\" try:", "usb.core.find(find_all=True): yield { \"port\": dev.port_number, \"vendor_id\": format_hex(dev.idVendor), \"product_id\": format_hex(dev.idProduct), \"speed\":", "anonymous: result[\"uname\"] = ' '.join(platform.uname()).strip(), return result if __name__ ==", "= [\"Unknown\", \"Low\", \"Full\", \"High\", \"Super\", \"SuperPlus\"] format_hex = lambda", "else dev.speed } except usb.core.NoBackendError: yield \"No USB backend found\"", "f\"{val:#0{6}x}\" try: for dev in usb.core.find(find_all=True): yield { \"port\": dev.port_number,", "not skipUsb: result[\"usb\"] = list(get_usb()) if not anonymous: result[\"uname\"] =", "result[\"uname\"] = ' '.join(platform.uname()).strip(), return result if __name__ == \"__main__\":", "USB backend found\" result = { \"architecture\": ' '.join(platform.architecture()).strip(), \"machine\":", "skipUsb=False, skipPackages=False): def get_usb(): try: import usb.core except ImportError: yield", "with open(\"log_system_information.json\", \"w\") as f: json.dump(data, f, indent=4) print(json.dumps(data, indent=4))", "\"vendor_id\": format_hex(dev.idVendor), \"product_id\": format_hex(dev.idProduct), \"speed\": speeds[dev.speed] if dev.speed < len(speeds)", "yield \"No USB backend found\" result = { \"architecture\": '", "yield { \"port\": dev.port_number, \"vendor_id\": format_hex(dev.idVendor), \"product_id\": format_hex(dev.idProduct), \"speed\": speeds[dev.speed]", "< len(speeds) else dev.speed } except usb.core.NoBackendError: yield \"No USB", "== \"__main__\": data = make_sys_report() with open(\"log_system_information.json\", \"w\") as f:", "from pip._internal.operations.freeze import freeze result[\"packages\"] = list(freeze(local_only=True)) if not skipUsb:", "\"Low\", \"Full\", \"High\", \"Super\", \"SuperPlus\"] format_hex = lambda val: f\"{val:#0{6}x}\"", "skipUsb: result[\"usb\"] = list(get_usb()) if not anonymous: result[\"uname\"] = '", "[\"Unknown\", \"Low\", \"Full\", \"High\", \"Super\", \"SuperPlus\"] format_hex = lambda val:", "\"win32_ver\": ' '.join(platform.win32_ver()).strip(), } if not skipPackages: from pip._internal.operations.freeze import", "'.join(platform.architecture()).strip(), \"machine\": platform.machine(), \"platform\": platform.platform(), \"processor\": platform.processor(), \"python_build\": ' '.join(platform.python_build()).strip(),", "import usb.core except ImportError: yield \"NoLib\" return speeds = [\"Unknown\",", "if dev.speed < len(speeds) else dev.speed } except usb.core.NoBackendError: yield", "as f: json.dump(data, f, indent=4) print(json.dumps(data, indent=4)) print(\"System info gathered", "\"High\", \"Super\", \"SuperPlus\"] format_hex = lambda val: f\"{val:#0{6}x}\" try: for", "\"SuperPlus\"] format_hex = lambda val: f\"{val:#0{6}x}\" try: for dev in", "\"version\": platform.version(), \"win32_ver\": ' '.join(platform.win32_ver()).strip(), } if not skipPackages: from", "skipPackages=False): def get_usb(): try: import usb.core except ImportError: yield \"NoLib\"", "f, indent=4) print(json.dumps(data, indent=4)) print(\"System info gathered successfully - saved", "import platform def make_sys_report(anonymous=False, skipUsb=False, skipPackages=False): def get_usb(): try: import", "usb.core.NoBackendError: yield \"No USB backend found\" result = { \"architecture\":", "if not skipPackages: from pip._internal.operations.freeze import freeze result[\"packages\"] = list(freeze(local_only=True))", "not skipPackages: from pip._internal.operations.freeze import freeze result[\"packages\"] = list(freeze(local_only=True)) if", "backend found\" result = { \"architecture\": ' '.join(platform.architecture()).strip(), \"machine\": platform.machine(),", "platform.release(), \"system\": platform.system(), \"version\": platform.version(), \"win32_ver\": ' '.join(platform.win32_ver()).strip(), } if", "import json import platform def make_sys_report(anonymous=False, skipUsb=False, skipPackages=False): def get_usb():", "' '.join(platform.python_build()).strip(), \"python_compiler\": platform.python_compiler(), \"python_implementation\": platform.python_implementation(), \"python_version\": platform.python_version(), \"release\": platform.release(),", "list(freeze(local_only=True)) if not skipUsb: result[\"usb\"] = list(get_usb()) if not anonymous:", "usb.core except ImportError: yield \"NoLib\" return speeds = [\"Unknown\", \"Low\",", "' '.join(platform.architecture()).strip(), \"machine\": platform.machine(), \"platform\": platform.platform(), \"processor\": platform.processor(), \"python_build\": '", "= list(freeze(local_only=True)) if not skipUsb: result[\"usb\"] = list(get_usb()) if not", "'.join(platform.uname()).strip(), return result if __name__ == \"__main__\": data = make_sys_report()", "f: json.dump(data, f, indent=4) print(json.dumps(data, indent=4)) print(\"System info gathered successfully", "platform.platform(), \"processor\": platform.processor(), \"python_build\": ' '.join(platform.python_build()).strip(), \"python_compiler\": platform.python_compiler(), \"python_implementation\": platform.python_implementation(),", "\"machine\": platform.machine(), \"platform\": platform.platform(), \"processor\": platform.processor(), \"python_build\": ' '.join(platform.python_build()).strip(), \"python_compiler\":", "\"product_id\": format_hex(dev.idProduct), \"speed\": speeds[dev.speed] if dev.speed < len(speeds) else dev.speed", "} except usb.core.NoBackendError: yield \"No USB backend found\" result =", "platform.machine(), \"platform\": platform.platform(), \"processor\": platform.processor(), \"python_build\": ' '.join(platform.python_build()).strip(), \"python_compiler\": platform.python_compiler(),", "freeze result[\"packages\"] = list(freeze(local_only=True)) if not skipUsb: result[\"usb\"] = list(get_usb())", "' '.join(platform.win32_ver()).strip(), } if not skipPackages: from pip._internal.operations.freeze import freeze", "def make_sys_report(anonymous=False, skipUsb=False, skipPackages=False): def get_usb(): try: import usb.core except", "json import platform def make_sys_report(anonymous=False, skipUsb=False, skipPackages=False): def get_usb(): try:", "platform.system(), \"version\": platform.version(), \"win32_ver\": ' '.join(platform.win32_ver()).strip(), } if not skipPackages:", "import freeze result[\"packages\"] = list(freeze(local_only=True)) if not skipUsb: result[\"usb\"] =", "result = { \"architecture\": ' '.join(platform.architecture()).strip(), \"machine\": platform.machine(), \"platform\": platform.platform(),", "= ' '.join(platform.uname()).strip(), return result if __name__ == \"__main__\": data", "= make_sys_report() with open(\"log_system_information.json\", \"w\") as f: json.dump(data, f, indent=4)", "def get_usb(): try: import usb.core except ImportError: yield \"NoLib\" return", "\"__main__\": data = make_sys_report() with open(\"log_system_information.json\", \"w\") as f: json.dump(data,", "= { \"architecture\": ' '.join(platform.architecture()).strip(), \"machine\": platform.machine(), \"platform\": platform.platform(), \"processor\":", "return result if __name__ == \"__main__\": data = make_sys_report() with", "lambda val: f\"{val:#0{6}x}\" try: for dev in usb.core.find(find_all=True): yield {", "speeds = [\"Unknown\", \"Low\", \"Full\", \"High\", \"Super\", \"SuperPlus\"] format_hex =", "len(speeds) else dev.speed } except usb.core.NoBackendError: yield \"No USB backend", "\"python_implementation\": platform.python_implementation(), \"python_version\": platform.python_version(), \"release\": platform.release(), \"system\": platform.system(), \"version\": platform.version(),", "indent=4) print(json.dumps(data, indent=4)) print(\"System info gathered successfully - saved as", "format_hex(dev.idVendor), \"product_id\": format_hex(dev.idProduct), \"speed\": speeds[dev.speed] if dev.speed < len(speeds) else", "\"python_version\": platform.python_version(), \"release\": platform.release(), \"system\": platform.system(), \"version\": platform.version(), \"win32_ver\": '", "format_hex(dev.idProduct), \"speed\": speeds[dev.speed] if dev.speed < len(speeds) else dev.speed }", "platform def make_sys_report(anonymous=False, skipUsb=False, skipPackages=False): def get_usb(): try: import usb.core", "ImportError: yield \"NoLib\" return speeds = [\"Unknown\", \"Low\", \"Full\", \"High\",", "platform.version(), \"win32_ver\": ' '.join(platform.win32_ver()).strip(), } if not skipPackages: from pip._internal.operations.freeze", "= lambda val: f\"{val:#0{6}x}\" try: for dev in usb.core.find(find_all=True): yield", "except ImportError: yield \"NoLib\" return speeds = [\"Unknown\", \"Low\", \"Full\",", "yield \"NoLib\" return speeds = [\"Unknown\", \"Low\", \"Full\", \"High\", \"Super\",", "try: for dev in usb.core.find(find_all=True): yield { \"port\": dev.port_number, \"vendor_id\":", "{ \"architecture\": ' '.join(platform.architecture()).strip(), \"machine\": platform.machine(), \"platform\": platform.platform(), \"processor\": platform.processor(),", "platform.processor(), \"python_build\": ' '.join(platform.python_build()).strip(), \"python_compiler\": platform.python_compiler(), \"python_implementation\": platform.python_implementation(), \"python_version\": platform.python_version(),", "#!/usr/bin/env python3 import json import platform def make_sys_report(anonymous=False, skipUsb=False, skipPackages=False):", "format_hex = lambda val: f\"{val:#0{6}x}\" try: for dev in usb.core.find(find_all=True):", "\"speed\": speeds[dev.speed] if dev.speed < len(speeds) else dev.speed } except", "{ \"port\": dev.port_number, \"vendor_id\": format_hex(dev.idVendor), \"product_id\": format_hex(dev.idProduct), \"speed\": speeds[dev.speed] if", "\"port\": dev.port_number, \"vendor_id\": format_hex(dev.idVendor), \"product_id\": format_hex(dev.idProduct), \"speed\": speeds[dev.speed] if dev.speed", "for dev in usb.core.find(find_all=True): yield { \"port\": dev.port_number, \"vendor_id\": format_hex(dev.idVendor),", "__name__ == \"__main__\": data = make_sys_report() with open(\"log_system_information.json\", \"w\") as", "'.join(platform.win32_ver()).strip(), } if not skipPackages: from pip._internal.operations.freeze import freeze result[\"packages\"]", "python3 import json import platform def make_sys_report(anonymous=False, skipUsb=False, skipPackages=False): def", "\"platform\": platform.platform(), \"processor\": platform.processor(), \"python_build\": ' '.join(platform.python_build()).strip(), \"python_compiler\": platform.python_compiler(), \"python_implementation\":", "dev.port_number, \"vendor_id\": format_hex(dev.idVendor), \"product_id\": format_hex(dev.idProduct), \"speed\": speeds[dev.speed] if dev.speed <", "\"NoLib\" return speeds = [\"Unknown\", \"Low\", \"Full\", \"High\", \"Super\", \"SuperPlus\"]", "'.join(platform.python_build()).strip(), \"python_compiler\": platform.python_compiler(), \"python_implementation\": platform.python_implementation(), \"python_version\": platform.python_version(), \"release\": platform.release(), \"system\":", "if not skipUsb: result[\"usb\"] = list(get_usb()) if not anonymous: result[\"uname\"]", "return speeds = [\"Unknown\", \"Low\", \"Full\", \"High\", \"Super\", \"SuperPlus\"] format_hex", "' '.join(platform.uname()).strip(), return result if __name__ == \"__main__\": data =", "platform.python_version(), \"release\": platform.release(), \"system\": platform.system(), \"version\": platform.version(), \"win32_ver\": ' '.join(platform.win32_ver()).strip(),", "speeds[dev.speed] if dev.speed < len(speeds) else dev.speed } except usb.core.NoBackendError:", "make_sys_report(anonymous=False, skipUsb=False, skipPackages=False): def get_usb(): try: import usb.core except ImportError:", "\"No USB backend found\" result = { \"architecture\": ' '.join(platform.architecture()).strip(),", "result[\"packages\"] = list(freeze(local_only=True)) if not skipUsb: result[\"usb\"] = list(get_usb()) if", "pip._internal.operations.freeze import freeze result[\"packages\"] = list(freeze(local_only=True)) if not skipUsb: result[\"usb\"]", "not anonymous: result[\"uname\"] = ' '.join(platform.uname()).strip(), return result if __name__", "\"w\") as f: json.dump(data, f, indent=4) print(json.dumps(data, indent=4)) print(\"System info", "except usb.core.NoBackendError: yield \"No USB backend found\" result = {", "dev.speed } except usb.core.NoBackendError: yield \"No USB backend found\" result", "make_sys_report() with open(\"log_system_information.json\", \"w\") as f: json.dump(data, f, indent=4) print(json.dumps(data,", "platform.python_implementation(), \"python_version\": platform.python_version(), \"release\": platform.release(), \"system\": platform.system(), \"version\": platform.version(), \"win32_ver\":", "val: f\"{val:#0{6}x}\" try: for dev in usb.core.find(find_all=True): yield { \"port\":", "dev.speed < len(speeds) else dev.speed } except usb.core.NoBackendError: yield \"No", "= list(get_usb()) if not anonymous: result[\"uname\"] = ' '.join(platform.uname()).strip(), return", "platform.python_compiler(), \"python_implementation\": platform.python_implementation(), \"python_version\": platform.python_version(), \"release\": platform.release(), \"system\": platform.system(), \"version\":", "list(get_usb()) if not anonymous: result[\"uname\"] = ' '.join(platform.uname()).strip(), return result", "\"Super\", \"SuperPlus\"] format_hex = lambda val: f\"{val:#0{6}x}\" try: for dev", "open(\"log_system_information.json\", \"w\") as f: json.dump(data, f, indent=4) print(json.dumps(data, indent=4)) print(\"System", "skipPackages: from pip._internal.operations.freeze import freeze result[\"packages\"] = list(freeze(local_only=True)) if not" ]
[ "check_output, CalledProcessError from shutil import copyfile from os import remove,", "self.original + \"_temp\" cmd = [ self.xdelta_path, '-f', '-d', '-s',", "creating xdelta patches. \"\"\" import logging from subprocess import check_output,", "except CalledProcessError: raise PatchChecksumError('Target file had incorrect checksum', []) finally:", "self.original self.original = self.original + \"_temp\" cmd = [ self.xdelta_path,", "original # file. def __init__(self, original, filename, edited=None, xdelta_dir='.'): self.original", "found. self.xdelta_path = path.join(xdelta_dir, 'xdelta3') # self.xdelta_path = 'xdelta3' def", "for xdelta3 to be found. self.xdelta_path = path.join(xdelta_dir, 'xdelta3') #", "raise PatchChecksumError('Target file had incorrect checksum', []) finally: if self.original.endswith('_temp'):", "import copyfile from os import remove, path class PatchChecksumError(Exception): def", "= edited self.filename = filename # Need to have this", "self.filename, ] print(cmd) logging.info(cmd) try: check_output(cmd) except CalledProcessError as e:", "from os import remove, path class PatchChecksumError(Exception): def __init__(self, message,", "__init__(self, message, errors): super(PatchChecksumError, self).__init__(message) class Patch: # TODO: Abstract", "Exception cmd = [ self.xdelta_path, '-f', '-s', self.original, self.edited, self.filename,", "raise Exception(e.output) def apply(self): if not self.edited: copyfile(self.original, self.original +", "+ \"_temp\") self.edited = self.original self.original = self.original + \"_temp\"", "edited=None, xdelta_dir='.'): self.original = original self.edited = edited self.filename =", "filename # Need to have this absolute path for xdelta3", "# TODO: Abstract out the need for \"edited\" by just", "[ self.xdelta_path, '-f', '-s', self.original, self.edited, self.filename, ] print(cmd) logging.info(cmd)", "absolute path for xdelta3 to be found. self.xdelta_path = path.join(xdelta_dir,", "errors): super(PatchChecksumError, self).__init__(message) class Patch: # TODO: Abstract out the", "None: raise Exception cmd = [ self.xdelta_path, '-f', '-s', self.original,", "from subprocess import check_output, CalledProcessError from shutil import copyfile from", "= [ self.xdelta_path, '-f', '-d', '-s', self.original, self.filename, self.edited, ]", "subprocess import check_output, CalledProcessError from shutil import copyfile from os", "remove, path class PatchChecksumError(Exception): def __init__(self, message, errors): super(PatchChecksumError, self).__init__(message)", "= self.original + \"_temp\" cmd = [ self.xdelta_path, '-f', '-d',", "xdelta patches. \"\"\" import logging from subprocess import check_output, CalledProcessError", "self.edited = self.original self.original = self.original + \"_temp\" cmd =", "for creating xdelta patches. \"\"\" import logging from subprocess import", "original self.edited = edited self.filename = filename # Need to", "patches. \"\"\" import logging from subprocess import check_output, CalledProcessError from", "not self.edited: copyfile(self.original, self.original + \"_temp\") self.edited = self.original self.original", "self.filename, self.edited, ] logging.info(cmd) try: check_output(cmd) except CalledProcessError: raise PatchChecksumError('Target", "original, filename, edited=None, xdelta_dir='.'): self.original = original self.edited = edited", "self.edited = edited self.filename = filename # Need to have", "# file. def __init__(self, original, filename, edited=None, xdelta_dir='.'): self.original =", "def apply(self): if not self.edited: copyfile(self.original, self.original + \"_temp\") self.edited", "try: check_output(cmd) except CalledProcessError: raise PatchChecksumError('Target file had incorrect checksum',", "[ self.xdelta_path, '-f', '-d', '-s', self.original, self.filename, self.edited, ] logging.info(cmd)", "] logging.info(cmd) try: check_output(cmd) except CalledProcessError: raise PatchChecksumError('Target file had", "logging.info(cmd) try: check_output(cmd) except CalledProcessError as e: raise Exception(e.output) def", "message, errors): super(PatchChecksumError, self).__init__(message) class Patch: # TODO: Abstract out", "self.xdelta_path, '-f', '-s', self.original, self.edited, self.filename, ] print(cmd) logging.info(cmd) try:", "self.xdelta_path, '-f', '-d', '-s', self.original, self.filename, self.edited, ] logging.info(cmd) try:", "super(PatchChecksumError, self).__init__(message) class Patch: # TODO: Abstract out the need", "self.edited, ] logging.info(cmd) try: check_output(cmd) except CalledProcessError: raise PatchChecksumError('Target file", "raise Exception cmd = [ self.xdelta_path, '-f', '-s', self.original, self.edited,", "\"_temp\" cmd = [ self.xdelta_path, '-f', '-d', '-s', self.original, self.filename,", "xdelta3 to be found. self.xdelta_path = path.join(xdelta_dir, 'xdelta3') # self.xdelta_path", "import check_output, CalledProcessError from shutil import copyfile from os import", "self.original = self.original + \"_temp\" cmd = [ self.xdelta_path, '-f',", "be found. self.xdelta_path = path.join(xdelta_dir, 'xdelta3') # self.xdelta_path = 'xdelta3'", "import remove, path class PatchChecksumError(Exception): def __init__(self, message, errors): super(PatchChecksumError,", "self.original, self.filename, self.edited, ] logging.info(cmd) try: check_output(cmd) except CalledProcessError: raise", "cmd = [ self.xdelta_path, '-f', '-d', '-s', self.original, self.filename, self.edited,", "this absolute path for xdelta3 to be found. self.xdelta_path =", "if not self.edited: copyfile(self.original, self.original + \"_temp\") self.edited = self.original", "self.edited is None: raise Exception cmd = [ self.xdelta_path, '-f',", "CalledProcessError: raise PatchChecksumError('Target file had incorrect checksum', []) finally: if", "def __init__(self, message, errors): super(PatchChecksumError, self).__init__(message) class Patch: # TODO:", "\"\"\" Utils for creating xdelta patches. \"\"\" import logging from", "import logging from subprocess import check_output, CalledProcessError from shutil import", "= self.original self.original = self.original + \"_temp\" cmd = [", "class PatchChecksumError(Exception): def __init__(self, message, errors): super(PatchChecksumError, self).__init__(message) class Patch:", "check_output(cmd) except CalledProcessError as e: raise Exception(e.output) def apply(self): if", "self.edited, self.filename, ] print(cmd) logging.info(cmd) try: check_output(cmd) except CalledProcessError as", "CalledProcessError as e: raise Exception(e.output) def apply(self): if not self.edited:", "Utils for creating xdelta patches. \"\"\" import logging from subprocess", "as e: raise Exception(e.output) def apply(self): if not self.edited: copyfile(self.original,", "Exception(e.output) def apply(self): if not self.edited: copyfile(self.original, self.original + \"_temp\")", "except CalledProcessError as e: raise Exception(e.output) def apply(self): if not", "PatchChecksumError(Exception): def __init__(self, message, errors): super(PatchChecksumError, self).__init__(message) class Patch: #", "path for xdelta3 to be found. self.xdelta_path = path.join(xdelta_dir, 'xdelta3')", "= original self.edited = edited self.filename = filename # Need", "logging.info(cmd) try: check_output(cmd) except CalledProcessError: raise PatchChecksumError('Target file had incorrect", "for \"edited\" by just copying the original # file. def", "__init__(self, original, filename, edited=None, xdelta_dir='.'): self.original = original self.edited =", "\"edited\" by just copying the original # file. def __init__(self,", "file. def __init__(self, original, filename, edited=None, xdelta_dir='.'): self.original = original", "path.join(xdelta_dir, 'xdelta3') # self.xdelta_path = 'xdelta3' def create(self): if self.edited", "just copying the original # file. def __init__(self, original, filename,", "logging from subprocess import check_output, CalledProcessError from shutil import copyfile", "TODO: Abstract out the need for \"edited\" by just copying", "Patch: # TODO: Abstract out the need for \"edited\" by", "os import remove, path class PatchChecksumError(Exception): def __init__(self, message, errors):", "path class PatchChecksumError(Exception): def __init__(self, message, errors): super(PatchChecksumError, self).__init__(message) class", "self.original = original self.edited = edited self.filename = filename #", "is None: raise Exception cmd = [ self.xdelta_path, '-f', '-s',", "from shutil import copyfile from os import remove, path class", "copying the original # file. def __init__(self, original, filename, edited=None,", "= path.join(xdelta_dir, 'xdelta3') # self.xdelta_path = 'xdelta3' def create(self): if", "= filename # Need to have this absolute path for", "try: check_output(cmd) except CalledProcessError as e: raise Exception(e.output) def apply(self):", "create(self): if self.edited is None: raise Exception cmd = [", "copyfile from os import remove, path class PatchChecksumError(Exception): def __init__(self,", "\"_temp\") self.edited = self.original self.original = self.original + \"_temp\" cmd", "# self.xdelta_path = 'xdelta3' def create(self): if self.edited is None:", "if self.edited is None: raise Exception cmd = [ self.xdelta_path,", "self.original + \"_temp\") self.edited = self.original self.original = self.original +", "out the need for \"edited\" by just copying the original", "by just copying the original # file. def __init__(self, original,", "copyfile(self.original, self.original + \"_temp\") self.edited = self.original self.original = self.original", "have this absolute path for xdelta3 to be found. self.xdelta_path", "# Need to have this absolute path for xdelta3 to", "the original # file. def __init__(self, original, filename, edited=None, xdelta_dir='.'):", "e: raise Exception(e.output) def apply(self): if not self.edited: copyfile(self.original, self.original", "shutil import copyfile from os import remove, path class PatchChecksumError(Exception):", "'-s', self.original, self.edited, self.filename, ] print(cmd) logging.info(cmd) try: check_output(cmd) except", "check_output(cmd) except CalledProcessError: raise PatchChecksumError('Target file had incorrect checksum', [])", "Abstract out the need for \"edited\" by just copying the", "CalledProcessError from shutil import copyfile from os import remove, path", "'xdelta3' def create(self): if self.edited is None: raise Exception cmd", "+ \"_temp\" cmd = [ self.xdelta_path, '-f', '-d', '-s', self.original,", "] print(cmd) logging.info(cmd) try: check_output(cmd) except CalledProcessError as e: raise", "PatchChecksumError('Target file had incorrect checksum', []) finally: if self.original.endswith('_temp'): remove(self.original)", "self.xdelta_path = path.join(xdelta_dir, 'xdelta3') # self.xdelta_path = 'xdelta3' def create(self):", "\"\"\" import logging from subprocess import check_output, CalledProcessError from shutil", "'xdelta3') # self.xdelta_path = 'xdelta3' def create(self): if self.edited is", "filename, edited=None, xdelta_dir='.'): self.original = original self.edited = edited self.filename", "Need to have this absolute path for xdelta3 to be", "def create(self): if self.edited is None: raise Exception cmd =", "def __init__(self, original, filename, edited=None, xdelta_dir='.'): self.original = original self.edited", "xdelta_dir='.'): self.original = original self.edited = edited self.filename = filename", "to have this absolute path for xdelta3 to be found.", "print(cmd) logging.info(cmd) try: check_output(cmd) except CalledProcessError as e: raise Exception(e.output)", "class Patch: # TODO: Abstract out the need for \"edited\"", "the need for \"edited\" by just copying the original #", "= 'xdelta3' def create(self): if self.edited is None: raise Exception", "'-f', '-d', '-s', self.original, self.filename, self.edited, ] logging.info(cmd) try: check_output(cmd)", "'-f', '-s', self.original, self.edited, self.filename, ] print(cmd) logging.info(cmd) try: check_output(cmd)", "'-s', self.original, self.filename, self.edited, ] logging.info(cmd) try: check_output(cmd) except CalledProcessError:", "need for \"edited\" by just copying the original # file.", "self.filename = filename # Need to have this absolute path", "'-d', '-s', self.original, self.filename, self.edited, ] logging.info(cmd) try: check_output(cmd) except", "self.edited: copyfile(self.original, self.original + \"_temp\") self.edited = self.original self.original =", "= [ self.xdelta_path, '-f', '-s', self.original, self.edited, self.filename, ] print(cmd)", "cmd = [ self.xdelta_path, '-f', '-s', self.original, self.edited, self.filename, ]", "to be found. self.xdelta_path = path.join(xdelta_dir, 'xdelta3') # self.xdelta_path =", "self.xdelta_path = 'xdelta3' def create(self): if self.edited is None: raise", "self).__init__(message) class Patch: # TODO: Abstract out the need for", "edited self.filename = filename # Need to have this absolute", "self.original, self.edited, self.filename, ] print(cmd) logging.info(cmd) try: check_output(cmd) except CalledProcessError", "apply(self): if not self.edited: copyfile(self.original, self.original + \"_temp\") self.edited =" ]
[ "distance = self.rotors[2].get_distance(char) word += self.rotors[i % 2].rotate((i + 1)", "Phrase: phrase to encrypt/decrypt\\n\" + \"-d/--decrypt: enables decrypt default is", "\"--help\"): print_help() sys.exit() elif opt in (\"-k\", \"--key\"): key =", "elif opt == \"--r3\": rotors[2] = arg if not key", "phrase to encrypt/decrypt\\n\" + \"-d/--decrypt: enables decrypt default is encrypt\\n\"", "opt == \"--r2\": rotors[1] = arg elif opt == \"--r3\":", "rotors[2] = arg if not key == '' and not", "50, 51, 60, 61, 70 and 71\\n\") def main(argv): try:", "not key == '' and not phrase == '' and", "arg elif opt == \"--r3\": rotors[2] = arg if not", "3\\n\" + \"possible rotors are 50, 51, 60, 61, 70", "[\"help\", \"key=\", \"phrase\", \"decrypt\", \"r1=\", \"r2=\", \"r3=\"]) except getopt.GetoptError: print_help()", "% 2].get_distance(char) cipher += self.rotors[2].rotate((i + 1) % 2, distance)", "rotors[i])) def encrypt(self, word): cipher = '' for i, char", "2, distance) return cipher def decrypt(self, cipher): word = ''", "ROTOR: sets rotor 3\\n\" + \"possible rotors are 50, 51,", "== ''\\ and not rotors[1] == '' and not rotors[2]", "arg if not key == '' and not phrase ==", "\"r3=\"]) except getopt.GetoptError: print_help() sys.exit(2) key = '' phrase =", "for i in range(0, len(rotors)): self.rotors.append(Rotor(self.key[i], rotors[i])) def encrypt(self, word):", "== \"--r3\": rotors[2] = arg if not key == ''", "arg elif opt in (\"-p\", \"--phrase\"): phrase = arg elif", "% 2].rotate((i + 1) % 2, distance) return word def", "main(argv): try: opts, args = getopt.getopt(argv, \"hk:p:d\", [\"help\", \"key=\", \"phrase\",", "2\\n\" + \"--r3 ROTOR: sets rotor 3\\n\" + \"possible rotors", "= '' encrypt = True rotors = ['', '', '']", "'' encrypt = True rotors = ['', '', ''] for", "rotors[0] = arg elif opt == \"--r2\": rotors[1] = arg", "\"--r3 ROTOR: sets rotor 3\\n\" + \"possible rotors are 50,", "(\"-k\", \"--key\"): key = arg elif opt in (\"-p\", \"--phrase\"):", "in (\"-p\", \"--phrase\"): phrase = arg elif opt in (\"-d\",", "sys import getopt class Enigma: def __init__(self, key, rotors): self.key", "elif opt in (\"-k\", \"--key\"): key = arg elif opt", "\"-h/--help: all possible options\\n\" + \"-k/--key KEY: rotor starting key\\n\"", "== '' and not phrase == '' and not rotors[0]", "in enumerate(word.upper()): distance = self.rotors[i % 2].get_distance(char) cipher += self.rotors[2].rotate((i", "def main(argv): try: opts, args = getopt.getopt(argv, \"hk:p:d\", [\"help\", \"key=\",", "and 71\\n\") def main(argv): try: opts, args = getopt.getopt(argv, \"hk:p:d\",", "\"r2=\", \"r3=\"]) except getopt.GetoptError: print_help() sys.exit(2) key = '' phrase", "rotor 3\\n\" + \"possible rotors are 50, 51, 60, 61,", "word = '' for i, char in enumerate(cipher.upper()): distance =", "''] for opt, arg in opts: if opt in (\"-h\",", "60, 61, 70 and 71\\n\") def main(argv): try: opts, args", "return word def print_help(): print(\"\\ncommand line arguments:\\n\" + \"-h/--help: all", "sets rotor 3\\n\" + \"possible rotors are 50, 51, 60,", "\"--decrypt\"): encrypt = False elif opt == \"--r1\": rotors[0] =", "self.key = list(key) self.rotors = [] for i in range(0,", "\"--key\"): key = arg elif opt in (\"-p\", \"--phrase\"): phrase", "= [] for i in range(0, len(rotors)): self.rotors.append(Rotor(self.key[i], rotors[i])) def", "i, char in enumerate(cipher.upper()): distance = self.rotors[2].get_distance(char) word += self.rotors[i", "encrypt/decrypt\\n\" + \"-d/--decrypt: enables decrypt default is encrypt\\n\" + \"--r1", "\"--r1\": rotors[0] = arg elif opt == \"--r2\": rotors[1] =", "\"decrypt\", \"r1=\", \"r2=\", \"r3=\"]) except getopt.GetoptError: print_help() sys.exit(2) key =", "opt == \"--r1\": rotors[0] = arg elif opt == \"--r2\":", "'' and not rotors[2] == '': machine = Enigma(key, rotors)", "print_help() sys.exit() elif opt in (\"-k\", \"--key\"): key = arg", "arguments:\\n\" + \"-h/--help: all possible options\\n\" + \"-k/--key KEY: rotor", "ROTOR: sets rotor 2\\n\" + \"--r3 ROTOR: sets rotor 3\\n\"", "\"r1=\", \"r2=\", \"r3=\"]) except getopt.GetoptError: print_help() sys.exit(2) key = ''", "word def print_help(): print(\"\\ncommand line arguments:\\n\" + \"-h/--help: all possible", "'' and not rotors[0] == ''\\ and not rotors[1] ==", "in range(0, len(rotors)): self.rotors.append(Rotor(self.key[i], rotors[i])) def encrypt(self, word): cipher =", "\"--r3\": rotors[2] = arg if not key == '' and", "if encrypt: print(machine.encrypt(phrase)) else: print(machine.decrypt(phrase)) else: print_help() if __name__ ==", "self.rotors.append(Rotor(self.key[i], rotors[i])) def encrypt(self, word): cipher = '' for i,", "import sys import getopt class Enigma: def __init__(self, key, rotors):", "not phrase == '' and not rotors[0] == ''\\ and", "to encrypt/decrypt\\n\" + \"-d/--decrypt: enables decrypt default is encrypt\\n\" +", "for opt, arg in opts: if opt in (\"-h\", \"--help\"):", "key = arg elif opt in (\"-p\", \"--phrase\"): phrase =", "\"--r2 ROTOR: sets rotor 2\\n\" + \"--r3 ROTOR: sets rotor", "char in enumerate(word.upper()): distance = self.rotors[i % 2].get_distance(char) cipher +=", "rotors[1] == '' and not rotors[2] == '': machine =", "encrypt: print(machine.encrypt(phrase)) else: print(machine.decrypt(phrase)) else: print_help() if __name__ == '__main__':", "rotor 1\\n\" + \"--r2 ROTOR: sets rotor 2\\n\" + \"--r3", "ROTOR: sets rotor 1\\n\" + \"--r2 ROTOR: sets rotor 2\\n\"", "default is encrypt\\n\" + \"--r1 ROTOR: sets rotor 1\\n\" +", "opt in (\"-p\", \"--phrase\"): phrase = arg elif opt in", "rotor 2\\n\" + \"--r3 ROTOR: sets rotor 3\\n\" + \"possible", "= list(key) self.rotors = [] for i in range(0, len(rotors)):", "enumerate(word.upper()): distance = self.rotors[i % 2].get_distance(char) cipher += self.rotors[2].rotate((i +", "'' phrase = '' encrypt = True rotors = ['',", "== \"--r2\": rotors[1] = arg elif opt == \"--r3\": rotors[2]", "rotors[0] == ''\\ and not rotors[1] == '' and not", "not rotors[1] == '' and not rotors[2] == '': machine", "in (\"-h\", \"--help\"): print_help() sys.exit() elif opt in (\"-k\", \"--key\"):", "= Enigma(key, rotors) if encrypt: print(machine.encrypt(phrase)) else: print(machine.decrypt(phrase)) else: print_help()", "2].rotate((i + 1) % 2, distance) return word def print_help():", "are 50, 51, 60, 61, 70 and 71\\n\") def main(argv):", "''\\ and not rotors[1] == '' and not rotors[2] ==", "not rotors[0] == ''\\ and not rotors[1] == '' and", "rotors are 50, 51, 60, 61, 70 and 71\\n\") def", "= arg elif opt in (\"-d\", \"--decrypt\"): encrypt = False", "try: opts, args = getopt.getopt(argv, \"hk:p:d\", [\"help\", \"key=\", \"phrase\", \"decrypt\",", "elif opt in (\"-d\", \"--decrypt\"): encrypt = False elif opt", "for i, char in enumerate(word.upper()): distance = self.rotors[i % 2].get_distance(char)", "getopt.GetoptError: print_help() sys.exit(2) key = '' phrase = '' encrypt", "elif opt == \"--r1\": rotors[0] = arg elif opt ==", "\"hk:p:d\", [\"help\", \"key=\", \"phrase\", \"decrypt\", \"r1=\", \"r2=\", \"r3=\"]) except getopt.GetoptError:", "\"possible rotors are 50, 51, 60, 61, 70 and 71\\n\")", "\"-d/--decrypt: enables decrypt default is encrypt\\n\" + \"--r1 ROTOR: sets", "\"key=\", \"phrase\", \"decrypt\", \"r1=\", \"r2=\", \"r3=\"]) except getopt.GetoptError: print_help() sys.exit(2)", "if opt in (\"-h\", \"--help\"): print_help() sys.exit() elif opt in", "(\"-d\", \"--decrypt\"): encrypt = False elif opt == \"--r1\": rotors[0]", "rotor import Rotor import sys import getopt class Enigma: def", "+ \"possible rotors are 50, 51, 60, 61, 70 and", "import Rotor import sys import getopt class Enigma: def __init__(self,", "= arg elif opt == \"--r2\": rotors[1] = arg elif", "Rotor import sys import getopt class Enigma: def __init__(self, key,", "sys.exit() elif opt in (\"-k\", \"--key\"): key = arg elif", "+ \"-d/--decrypt: enables decrypt default is encrypt\\n\" + \"--r1 ROTOR:", "opt in (\"-d\", \"--decrypt\"): encrypt = False elif opt ==", "opts: if opt in (\"-h\", \"--help\"): print_help() sys.exit() elif opt", "not rotors[2] == '': machine = Enigma(key, rotors) if encrypt:", "phrase = arg elif opt in (\"-d\", \"--decrypt\"): encrypt =", "sys.exit(2) key = '' phrase = '' encrypt = True", "% 2, distance) return cipher def decrypt(self, cipher): word =", "= '' for i, char in enumerate(word.upper()): distance = self.rotors[i", "and not rotors[0] == ''\\ and not rotors[1] == ''", "+ 1) % 2, distance) return word def print_help(): print(\"\\ncommand", "\"-k/--key KEY: rotor starting key\\n\" + \"-p/--phrase Phrase: phrase to", "2, distance) return word def print_help(): print(\"\\ncommand line arguments:\\n\" +", "and not rotors[2] == '': machine = Enigma(key, rotors) if", "possible options\\n\" + \"-k/--key KEY: rotor starting key\\n\" + \"-p/--phrase", "def encrypt(self, word): cipher = '' for i, char in", "word): cipher = '' for i, char in enumerate(word.upper()): distance", "= '' for i, char in enumerate(cipher.upper()): distance = self.rotors[2].get_distance(char)", "print(\"\\ncommand line arguments:\\n\" + \"-h/--help: all possible options\\n\" + \"-k/--key", "phrase == '' and not rotors[0] == ''\\ and not", "opt in (\"-h\", \"--help\"): print_help() sys.exit() elif opt in (\"-k\",", "(\"-p\", \"--phrase\"): phrase = arg elif opt in (\"-d\", \"--decrypt\"):", "line arguments:\\n\" + \"-h/--help: all possible options\\n\" + \"-k/--key KEY:", "print_help(): print(\"\\ncommand line arguments:\\n\" + \"-h/--help: all possible options\\n\" +", "cipher += self.rotors[2].rotate((i + 1) % 2, distance) return cipher", "\"phrase\", \"decrypt\", \"r1=\", \"r2=\", \"r3=\"]) except getopt.GetoptError: print_help() sys.exit(2) key", "\"--r2\": rotors[1] = arg elif opt == \"--r3\": rotors[2] =", "['', '', ''] for opt, arg in opts: if opt", "except getopt.GetoptError: print_help() sys.exit(2) key = '' phrase = ''", "encrypt = True rotors = ['', '', ''] for opt,", "= arg elif opt == \"--r3\": rotors[2] = arg if", "'' for i, char in enumerate(cipher.upper()): distance = self.rotors[2].get_distance(char) word", "in enumerate(cipher.upper()): distance = self.rotors[2].get_distance(char) word += self.rotors[i % 2].rotate((i", "+= self.rotors[i % 2].rotate((i + 1) % 2, distance) return", "KEY: rotor starting key\\n\" + \"-p/--phrase Phrase: phrase to encrypt/decrypt\\n\"", "opt in (\"-k\", \"--key\"): key = arg elif opt in", "distance) return cipher def decrypt(self, cipher): word = '' for", "Enigma: def __init__(self, key, rotors): self.key = list(key) self.rotors =", "opt == \"--r3\": rotors[2] = arg if not key ==", "rotors): self.key = list(key) self.rotors = [] for i in", "= self.rotors[i % 2].get_distance(char) cipher += self.rotors[2].rotate((i + 1) %", "def __init__(self, key, rotors): self.key = list(key) self.rotors = []", "enables decrypt default is encrypt\\n\" + \"--r1 ROTOR: sets rotor", "elif opt == \"--r2\": rotors[1] = arg elif opt ==", "= arg if not key == '' and not phrase", "70 and 71\\n\") def main(argv): try: opts, args = getopt.getopt(argv,", "61, 70 and 71\\n\") def main(argv): try: opts, args =", "cipher = '' for i, char in enumerate(word.upper()): distance =", "self.rotors[2].rotate((i + 1) % 2, distance) return cipher def decrypt(self,", "range(0, len(rotors)): self.rotors.append(Rotor(self.key[i], rotors[i])) def encrypt(self, word): cipher = ''", "= getopt.getopt(argv, \"hk:p:d\", [\"help\", \"key=\", \"phrase\", \"decrypt\", \"r1=\", \"r2=\", \"r3=\"])", "opt, arg in opts: if opt in (\"-h\", \"--help\"): print_help()", "key = '' phrase = '' encrypt = True rotors", "if not key == '' and not phrase == ''", "def print_help(): print(\"\\ncommand line arguments:\\n\" + \"-h/--help: all possible options\\n\"", "in (\"-k\", \"--key\"): key = arg elif opt in (\"-p\",", "print(machine.encrypt(phrase)) else: print(machine.decrypt(phrase)) else: print_help() if __name__ == '__main__': main(sys.argv[1:])", "options\\n\" + \"-k/--key KEY: rotor starting key\\n\" + \"-p/--phrase Phrase:", "[] for i in range(0, len(rotors)): self.rotors.append(Rotor(self.key[i], rotors[i])) def encrypt(self,", "rotor starting key\\n\" + \"-p/--phrase Phrase: phrase to encrypt/decrypt\\n\" +", "key, rotors): self.key = list(key) self.rotors = [] for i", "+ \"--r1 ROTOR: sets rotor 1\\n\" + \"--r2 ROTOR: sets", "'', ''] for opt, arg in opts: if opt in", "char in enumerate(cipher.upper()): distance = self.rotors[2].get_distance(char) word += self.rotors[i %", "% 2, distance) return word def print_help(): print(\"\\ncommand line arguments:\\n\"", "self.rotors[i % 2].get_distance(char) cipher += self.rotors[2].rotate((i + 1) % 2,", "in opts: if opt in (\"-h\", \"--help\"): print_help() sys.exit() elif", "= '' phrase = '' encrypt = True rotors =", "rotors[2] == '': machine = Enigma(key, rotors) if encrypt: print(machine.encrypt(phrase))", "+ \"--r3 ROTOR: sets rotor 3\\n\" + \"possible rotors are", "= arg elif opt in (\"-p\", \"--phrase\"): phrase = arg", "= False elif opt == \"--r1\": rotors[0] = arg elif", "+ \"-h/--help: all possible options\\n\" + \"-k/--key KEY: rotor starting", "print_help() sys.exit(2) key = '' phrase = '' encrypt =", "distance = self.rotors[i % 2].get_distance(char) cipher += self.rotors[2].rotate((i + 1)", "self.rotors[i % 2].rotate((i + 1) % 2, distance) return word", "1) % 2, distance) return cipher def decrypt(self, cipher): word", "word += self.rotors[i % 2].rotate((i + 1) % 2, distance)", "== '' and not rotors[2] == '': machine = Enigma(key,", "starting key\\n\" + \"-p/--phrase Phrase: phrase to encrypt/decrypt\\n\" + \"-d/--decrypt:", "and not rotors[1] == '' and not rotors[2] == '':", "i in range(0, len(rotors)): self.rotors.append(Rotor(self.key[i], rotors[i])) def encrypt(self, word): cipher", "51, 60, 61, 70 and 71\\n\") def main(argv): try: opts,", "and not phrase == '' and not rotors[0] == ''\\", "all possible options\\n\" + \"-k/--key KEY: rotor starting key\\n\" +", "i, char in enumerate(word.upper()): distance = self.rotors[i % 2].get_distance(char) cipher", "self.rotors[2].get_distance(char) word += self.rotors[i % 2].rotate((i + 1) % 2,", "rotors = ['', '', ''] for opt, arg in opts:", "'' for i, char in enumerate(word.upper()): distance = self.rotors[i %", "rotors[1] = arg elif opt == \"--r3\": rotors[2] = arg", "rotors) if encrypt: print(machine.encrypt(phrase)) else: print(machine.decrypt(phrase)) else: print_help() if __name__", "is encrypt\\n\" + \"--r1 ROTOR: sets rotor 1\\n\" + \"--r2", "\"--phrase\"): phrase = arg elif opt in (\"-d\", \"--decrypt\"): encrypt", "'': machine = Enigma(key, rotors) if encrypt: print(machine.encrypt(phrase)) else: print(machine.decrypt(phrase))", "def decrypt(self, cipher): word = '' for i, char in", "decrypt(self, cipher): word = '' for i, char in enumerate(cipher.upper()):", "== \"--r1\": rotors[0] = arg elif opt == \"--r2\": rotors[1]", "enumerate(cipher.upper()): distance = self.rotors[2].get_distance(char) word += self.rotors[i % 2].rotate((i +", "\"-p/--phrase Phrase: phrase to encrypt/decrypt\\n\" + \"-d/--decrypt: enables decrypt default", "= True rotors = ['', '', ''] for opt, arg", "machine = Enigma(key, rotors) if encrypt: print(machine.encrypt(phrase)) else: print(machine.decrypt(phrase)) else:", "+ \"-p/--phrase Phrase: phrase to encrypt/decrypt\\n\" + \"-d/--decrypt: enables decrypt", "list(key) self.rotors = [] for i in range(0, len(rotors)): self.rotors.append(Rotor(self.key[i],", "encrypt(self, word): cipher = '' for i, char in enumerate(word.upper()):", "= self.rotors[2].get_distance(char) word += self.rotors[i % 2].rotate((i + 1) %", "distance) return word def print_help(): print(\"\\ncommand line arguments:\\n\" + \"-h/--help:", "'' and not phrase == '' and not rotors[0] ==", "from rotor import Rotor import sys import getopt class Enigma:", "getopt class Enigma: def __init__(self, key, rotors): self.key = list(key)", "True rotors = ['', '', ''] for opt, arg in", "key == '' and not phrase == '' and not", "encrypt = False elif opt == \"--r1\": rotors[0] = arg", "getopt.getopt(argv, \"hk:p:d\", [\"help\", \"key=\", \"phrase\", \"decrypt\", \"r1=\", \"r2=\", \"r3=\"]) except", "+= self.rotors[2].rotate((i + 1) % 2, distance) return cipher def", "== '': machine = Enigma(key, rotors) if encrypt: print(machine.encrypt(phrase)) else:", "2].get_distance(char) cipher += self.rotors[2].rotate((i + 1) % 2, distance) return", "elif opt in (\"-p\", \"--phrase\"): phrase = arg elif opt", "args = getopt.getopt(argv, \"hk:p:d\", [\"help\", \"key=\", \"phrase\", \"decrypt\", \"r1=\", \"r2=\",", "arg elif opt in (\"-d\", \"--decrypt\"): encrypt = False elif", "False elif opt == \"--r1\": rotors[0] = arg elif opt", "+ \"-k/--key KEY: rotor starting key\\n\" + \"-p/--phrase Phrase: phrase", "+ 1) % 2, distance) return cipher def decrypt(self, cipher):", "1) % 2, distance) return word def print_help(): print(\"\\ncommand line", "key\\n\" + \"-p/--phrase Phrase: phrase to encrypt/decrypt\\n\" + \"-d/--decrypt: enables", "sets rotor 2\\n\" + \"--r3 ROTOR: sets rotor 3\\n\" +", "phrase = '' encrypt = True rotors = ['', '',", "\"--r1 ROTOR: sets rotor 1\\n\" + \"--r2 ROTOR: sets rotor", "opts, args = getopt.getopt(argv, \"hk:p:d\", [\"help\", \"key=\", \"phrase\", \"decrypt\", \"r1=\",", "arg in opts: if opt in (\"-h\", \"--help\"): print_help() sys.exit()", "arg elif opt == \"--r2\": rotors[1] = arg elif opt", "71\\n\") def main(argv): try: opts, args = getopt.getopt(argv, \"hk:p:d\", [\"help\",", "len(rotors)): self.rotors.append(Rotor(self.key[i], rotors[i])) def encrypt(self, word): cipher = '' for", "sets rotor 1\\n\" + \"--r2 ROTOR: sets rotor 2\\n\" +", "return cipher def decrypt(self, cipher): word = '' for i,", "== '' and not rotors[0] == ''\\ and not rotors[1]", "cipher): word = '' for i, char in enumerate(cipher.upper()): distance", "encrypt\\n\" + \"--r1 ROTOR: sets rotor 1\\n\" + \"--r2 ROTOR:", "(\"-h\", \"--help\"): print_help() sys.exit() elif opt in (\"-k\", \"--key\"): key", "import getopt class Enigma: def __init__(self, key, rotors): self.key =", "class Enigma: def __init__(self, key, rotors): self.key = list(key) self.rotors", "self.rotors = [] for i in range(0, len(rotors)): self.rotors.append(Rotor(self.key[i], rotors[i]))", "= ['', '', ''] for opt, arg in opts: if", "for i, char in enumerate(cipher.upper()): distance = self.rotors[2].get_distance(char) word +=", "Enigma(key, rotors) if encrypt: print(machine.encrypt(phrase)) else: print(machine.decrypt(phrase)) else: print_help() if", "cipher def decrypt(self, cipher): word = '' for i, char", "1\\n\" + \"--r2 ROTOR: sets rotor 2\\n\" + \"--r3 ROTOR:", "+ \"--r2 ROTOR: sets rotor 2\\n\" + \"--r3 ROTOR: sets", "in (\"-d\", \"--decrypt\"): encrypt = False elif opt == \"--r1\":", "__init__(self, key, rotors): self.key = list(key) self.rotors = [] for", "decrypt default is encrypt\\n\" + \"--r1 ROTOR: sets rotor 1\\n\"" ]
[ "ord=2) ** 2 lc = np.zeros(n_groups) for g in range(n_groups):", "grp_size) R[:] = y - X @ w elif algo", "t_start = time.time() for it in range(max_iter): if it %", "bcd=lambda: _range, bcdshuf=lambda: np.random.choice(n_groups, n_groups, replace=False), rbcd=lambda: np.random.choice(n_groups, n_groups, replace=True))", "last_K_w = np.zeros([K + 1, n_features]) U = np.zeros([K, n_features])", "@ X_g).todense() lc[g] = norm(gram, ord=2) else: lc[g] = norm(X_g,", "np.zeros([K, n_features]) if algo in ('pgd', 'fista'): if is_sparse: L", "[] t_start = time.time() for it in range(max_iter): if it", "z / z.sum() w_acc = np.sum(last_K_w[:-1] * c[:, None], axis=0)", "X @ w p_obj = primal_grp(R, w, alpha, grp_size) E.append(p_obj)", "BST(x, u): \"\"\"Block soft-thresholding of vector x at level u.\"\"\"", "np.sqrt(1 + 4 * t_old ** 2)) / 2. z[:]", "is_sparse: _bcd_sparse( X.data, X.indices, X.indptr, w, R, alpha, lc) else:", "+ 1: last_K_w[it] = w else: for k in range(K):", "/ z.sum() w_acc = np.sum(last_K_w[:-1] * c[:, None], axis=0) p_obj", "= np.zeros([K + 1, n_features]) U = np.zeros([K, n_features]) if", "R_acc = y - X @ w_acc p_obj_acc = primal_grp(R_acc,", "Xg = X[:, grp] old_w_g = w[grp].copy() w[grp] = BST(old_w_g", "def BST_vec(x, u, grp_size): norm_grp = norm(x.reshape(-1, grp_size), axis=1) scaling", "it % f_gap == 0: if algo == 'fista': R", "X @ w_acc p_obj_acc = primal_grp(R_acc, w_acc, alpha, grp_size) if", "U = np.zeros([K, n_features]) if algo in ('pgd', 'fista'): if", "2 else: L = norm(X, ord=2) ** 2 lc =", "Xg, axis=1) @njit def _bcd_sparse( X_data, X_indices, X_indptr, w, R,", "X.data, X.indices, X.indptr, w, R, alpha, lc) else: _bcd(X, w,", "ValueError(\"Unknown algo %s\" % algo) if use_acc: if it <", "Groups are contiguous, of size grp_size. Objective: norm(y - Xw,", "w, R, alpha, lc) else: _bcd(X, w, R, alpha, lc,", "1 R = y.copy() E = [] gaps = np.zeros(max_iter", "R = y - X @ w p_obj = primal_grp(R,", "= np.zeros(n_groups) for g in range(n_groups): X_g = X[:, g", "def solver_group( X, y, alpha, grp_size, max_iter=10000, tol=1e-4, f_gap=10, K=5,", ": float, default=1000 Maximum time (in seconds) the algorithm is", "1]): R[X_indices[ix]] += (old_w_g[j % grp_size] - w[j % grp_size])", "group size\") n_groups = n_features // grp_size _range = np.arange(n_groups)", "raise ValueError(\"n_features is not a multiple of group size\") n_groups", "- 1] = w for k in range(K): U[k] =", "docstring Parameters: algo: string 'bcd', 'pgd', 'fista' compute_time : bool,", "U.T) try: z = np.linalg.solve(C, np.ones(K)) c = z /", "grp_size), axis=1)) if d_norm_theta > 1.: theta /= d_norm_theta d_obj", "svds from andersoncd.lasso import dual_lasso def primal_grp(R, w, alpha, grp_size):", "w[:] = BST_vec(z - X.T @ (X @ z -", "penalty \"\"\" is_sparse = sparse.issparse(X) n_features = X.shape[1] if n_features", "last_K_w[k + 1] last_K_w[K - 1] = w for k", "R, alpha, lc) else: _bcd(X, w, R, alpha, lc, groups[algo]())", "n_features = X.shape[1] if n_features % grp_size != 0: raise", "in range(X_indptr[j], X_indptr[j + 1]): R[X_indices[ix]] += (old_w_g[j % grp_size]", "= w.shape[0] // lc.shape[0] for g in groups: grp =", "from scipy import sparse from numba import njit from numpy.linalg", "scipy.sparse.linalg import svds from andersoncd.lasso import dual_lasso def primal_grp(R, w,", "% elapsed_times) if elapsed_times > tmax: break d_norm_theta = np.max(", "* grp_size, (g + 1) * grp_size) for j in", "k in range(K): U[k] = last_K_w[k + 1] - last_K_w[k]", "if elapsed_times > tmax: break d_norm_theta = np.max( norm((X.T @", "= np.maximum(1 - u / norm_grp, 0) return (x.reshape(-1, grp_size)", "with extrapolation. Groups are contiguous, of size grp_size. Objective: norm(y", "return (1 - u / norm_x) * x def BST_vec(x,", "lc = np.zeros(n_groups) for g in range(n_groups): X_g = X[:,", "@ R / L, alpha / L, grp_size) R[:] =", "range(grp_size * g, grp_size * (g + 1)): for ix", "algo == 'fista': w_old = w.copy() w[:] = BST_vec(z -", "import norm from scipy.sparse.linalg import svds from andersoncd.lasso import dual_lasso", "is_sparse = sparse.issparse(X) n_features = X.shape[1] if n_features % grp_size", "1, n_features]) U = np.zeros([K, n_features]) if algo in ('pgd',", "R, alpha, lc): grp_size = w.shape[0] // lc.shape[0] grad =", "algo.endswith('bcd'): if is_sparse: _bcd_sparse( X.data, X.indices, X.indptr, w, R, alpha,", "_bcd(X, w, R, alpha, lc, groups[algo]()) elif algo == 'pgd':", "range(X_indptr[j], X_indptr[j + 1]): grad[j % g] += X_data[ix] *", "np.linalg.LinAlgError: if verbose: print(\"----------Linalg error\") if compute_time: return w, np.array(E),", "grp] old_w_g = w[grp].copy() w[grp] = BST(old_w_g + Xg.T @", "w = np.zeros(n_features) if algo == 'fista': z = np.zeros(n_features)", "in range(lc.shape[0]): grad.fill(0) grp = slice(g * grp_size, (g +", "1.: theta /= d_norm_theta d_obj = dual_lasso(y, theta, alpha) gap", "alpha / lc[g]) if norm(w[grp] - old_w_g) != 0: R", "= w_acc R = R_acc except np.linalg.LinAlgError: if verbose: print(\"----------Linalg", "/ L, alpha / L, grp_size) t_old = t_new t_new", "- 1.) / t_new * (w - w_old) else: raise", "strength of the group penalty \"\"\" is_sparse = sparse.issparse(X) n_features", "raise ValueError(\"Unknown algo %s\" % algo) if use_acc: if it", "w, R, alpha, lc, groups[algo]()) elif algo == 'pgd': w[:]", "lc[g] = norm(gram, ord=2) else: lc[g] = norm(X_g, ord=2) **", "norm_x = norm(x) if norm_x < u: return np.zeros_like(x) else:", "// grp_size _range = np.arange(n_groups) groups = dict( bcd=lambda: _range,", "alpha / lc[g]) if norm(w[grp] - old_w_g) != 0: for", "np.random.choice(n_groups, n_groups, replace=True)) if not is_sparse and not np.isfortran(X): X", "grp_size): for ix in range(X_indptr[j], X_indptr[j + 1]): R[X_indices[ix]] +=", "range(X_indptr[j], X_indptr[j + 1]): R[X_indices[ix]] += (old_w_g[j % grp_size] -", "= y - X @ w p_obj = primal_grp(R, w,", "d_obj, gap)) gaps[it // f_gap] = gap if gap <", "gap if gap < tol: print(\"Early exit\") break if algo.endswith('bcd'):", "for k in range(K): last_K_w[k] = last_K_w[k + 1] last_K_w[K", "g * grp_size: (g + 1) * grp_size] if is_sparse:", "primal_grp(R, w, alpha, grp_size) R_acc = y - X @", "'pgd', 'fista' compute_time : bool, default=False If you want to", "time (in seconds) the algorithm is allowed to run alpha:", "alpha, grp_size) E.append(p_obj) theta = R / alpha if compute_time:", "print(\"elapsed time: %f \" % elapsed_times) if elapsed_times > tmax:", "1.) / t_new * (w - w_old) else: raise ValueError(\"Unknown", "for ix in range(X_indptr[j], X_indptr[j + 1]): R[X_indices[ix]] += (old_w_g[j", "- u / norm_x) * x def BST_vec(x, u, grp_size):", "if algo in ('pgd', 'fista'): if is_sparse: L = svds(X,", "% algo) if use_acc: if it < K + 1:", "of vector x at level u.\"\"\" norm_x = norm(x) if", "R, alpha, lc, groups): grp_size = w.shape[0] // lc.shape[0] for", "L = norm(X, ord=2) ** 2 lc = np.zeros(n_groups) for", "w else: for k in range(K): last_K_w[k] = last_K_w[k +", "lc) else: _bcd(X, w, R, alpha, lc, groups[algo]()) elif algo", "algo: string 'bcd', 'pgd', 'fista' compute_time : bool, default=False If", "n_groups = n_features // grp_size _range = np.arange(n_groups) groups =", "size\") n_groups = n_features // grp_size _range = np.arange(n_groups) groups", "= norm(X, ord=2) ** 2 lc = np.zeros(n_groups) for g", "alpha, grp_size) R_acc = y - X @ w_acc p_obj_acc", "y - X @ w_acc p_obj_acc = primal_grp(R_acc, w_acc, alpha,", "sparse from numba import njit from numpy.linalg import norm from", "= slice(g * grp_size, (g + 1) * grp_size) Xg", "K=5, use_acc=False, algo='bcd', compute_time=False, tmax=np.infty, verbose=True): \"\"\"Solve the GroupLasso with", "(old_w_g[j % grp_size] - w[j % grp_size]) * X_data[ix] def", "from andersoncd.lasso import dual_lasso def primal_grp(R, w, alpha, grp_size): return", "else: lc[g] = norm(X_g, ord=2) ** 2 w = np.zeros(n_features)", "= w.copy() w[:] = BST_vec(z - X.T @ (X @", "ord=2)**2 / 2 + alpha * sum_g ||w_{[g]}||_2 TODO: filled", "in range(K): U[k] = last_K_w[k + 1] - last_K_w[k] C", "R = y.copy() E = [] gaps = np.zeros(max_iter //", "lc, groups[algo]()) elif algo == 'pgd': w[:] = BST_vec(w +", "else: return (1 - u / norm_x) * x def", "= primal_grp(R, w, alpha, grp_size) E.append(p_obj) theta = R /", "lc): grp_size = w.shape[0] // lc.shape[0] grad = np.zeros(grp_size) for", "grp_size] - w[j % grp_size]) * X_data[ix] def solver_group( X,", "// f_gap) if compute_time: times = [] t_start = time.time()", "w[grp] = BST(old_w_g + Xg.T @ R / lc[g], alpha", "= norm(gram, ord=2) else: lc[g] = norm(X_g, ord=2) ** 2", "grp_size. Objective: norm(y - Xw, ord=2)**2 / 2 + alpha", "dual_lasso def primal_grp(R, w, alpha, grp_size): return (0.5 * norm(R)", "last_K_w[k + 1] - last_K_w[k] C = np.dot(U, U.T) try:", "- w_old) else: raise ValueError(\"Unknown algo %s\" % algo) if", "= norm(X_g, ord=2) ** 2 w = np.zeros(n_features) if algo", "%s\" % algo) if use_acc: if it < K +", "'fista'): if is_sparse: L = svds(X, k=1)[1][0] ** 2 else:", "% grp_size != 0: raise ValueError(\"n_features is not a multiple", "< K + 1: last_K_w[it] = w else: for k", "np.dot(U, U.T) try: z = np.linalg.solve(C, np.ones(K)) c = z", "np from scipy import sparse from numba import njit from", "j in range(grp_size * g, grp_size * (g + 1)):", "in groups: grp = slice(g * grp_size, (g + 1)", "X_data[ix] def solver_group( X, y, alpha, grp_size, max_iter=10000, tol=1e-4, f_gap=10,", "tmax=np.infty, verbose=True): \"\"\"Solve the GroupLasso with BCD/ISTA/FISTA, eventually with extrapolation.", "a multiple of group size\") n_groups = n_features // grp_size", "// lc.shape[0] for g in groups: grp = slice(g *", "= w + (t_old - 1.) / t_new * (w", "else: L = norm(X, ord=2) ** 2 lc = np.zeros(n_groups)", "- X.T @ (X @ z - y) / L,", "// f_gap + 1], times return w, np.array(E), gaps[:it //", "if compute_time: times = [] t_start = time.time() for it", "% grp_size] - w[j % grp_size]) * X_data[ix] def solver_group(", "- w[j % grp_size]) * X_data[ix] def solver_group( X, y,", "= 1 R = y.copy() E = [] gaps =", "R[X_indices[ix]] old_w_g = w[grp].copy() w[grp] = BST(old_w_g + grad /", "d_norm_theta > 1.: theta /= d_norm_theta d_obj = dual_lasso(y, theta,", "ix in range(X_indptr[j], X_indptr[j + 1]): R[X_indices[ix]] += (old_w_g[j %", "X_indptr[j + 1]): grad[j % g] += X_data[ix] * R[X_indices[ix]]", "grp_size, max_iter=10000, tol=1e-4, f_gap=10, K=5, use_acc=False, algo='bcd', compute_time=False, tmax=np.infty, verbose=True):", "alpha, lc, groups[algo]()) elif algo == 'pgd': w[:] = BST_vec(w", "@njit def _bcd(X, w, R, alpha, lc, groups): grp_size =", "k in range(K): last_K_w[k] = last_K_w[k + 1] last_K_w[K -", "+ 1) * grp_size] if is_sparse: gram = (X_g.T @", "= np.arange(n_groups) groups = dict( bcd=lambda: _range, bcdshuf=lambda: np.random.choice(n_groups, n_groups,", "= (1. + np.sqrt(1 + 4 * t_old ** 2))", "gaps[it // f_gap] = gap if gap < tol: print(\"Early", "1] - last_K_w[k] C = np.dot(U, U.T) try: z =", "grp_size) for j in range(grp_size * g, grp_size * (g", "g in range(n_groups): X_g = X[:, g * grp_size: (g", "\"\"\"Solve the GroupLasso with BCD/ISTA/FISTA, eventually with extrapolation. Groups are", "norm(y - Xw, ord=2)**2 / 2 + alpha * sum_g", "norm(w.reshape(-1, grp_size), axis=1).sum()) @njit def BST(x, u): \"\"\"Block soft-thresholding of", "(g + 1) * grp_size] if is_sparse: gram = (X_g.T", "// f_gap] = gap if gap < tol: print(\"Early exit\")", "= w[grp].copy() w[grp] = BST(old_w_g + grad / lc[g], alpha", "BST_vec(x, u, grp_size): norm_grp = norm(x.reshape(-1, grp_size), axis=1) scaling =", "np.linalg.solve(C, np.ones(K)) c = z / z.sum() w_acc = np.sum(last_K_w[:-1]", "= z / z.sum() w_acc = np.sum(last_K_w[:-1] * c[:, None],", "norm((X.T @ theta).reshape(-1, grp_size), axis=1)) if d_norm_theta > 1.: theta", "else: raise ValueError(\"Unknown algo %s\" % algo) if use_acc: if", "lc.shape[0] for g in groups: grp = slice(g * grp_size,", "njit from numpy.linalg import norm from scipy.sparse.linalg import svds from", "np.array(E), gaps[:it // f_gap + 1], times return w, np.array(E),", "1) * grp_size) for j in range(grp_size * g, grp_size", "< u: return np.zeros_like(x) else: return (1 - u /", "tol=1e-4, f_gap=10, K=5, use_acc=False, algo='bcd', compute_time=False, tmax=np.infty, verbose=True): \"\"\"Solve the", "grp_size) t_old = t_new t_new = (1. + np.sqrt(1 +", "X_indptr[j + 1]): R[X_indices[ix]] += (old_w_g[j % grp_size] - w[j", "if is_sparse: _bcd_sparse( X.data, X.indices, X.indptr, w, R, alpha, lc)", "- old_w_g) != 0: for j in range(g * grp_size,", "algo == 'pgd': w[:] = BST_vec(w + X.T @ R", "** 2 w = np.zeros(n_features) if algo == 'fista': z", "4 * t_old ** 2)) / 2. z[:] = w", "< p_obj: w = w_acc R = R_acc except np.linalg.LinAlgError:", "- Xw, ord=2)**2 / 2 + alpha * sum_g ||w_{[g]}||_2", "for k in range(K): U[k] = last_K_w[k + 1] -", "andersoncd.lasso import dual_lasso def primal_grp(R, w, alpha, grp_size): return (0.5", "are contiguous, of size grp_size. Objective: norm(y - Xw, ord=2)**2", "None], axis=0) p_obj = primal_grp(R, w, alpha, grp_size) R_acc =", "w_acc = np.sum(last_K_w[:-1] * c[:, None], axis=0) p_obj = primal_grp(R,", "Xg.T @ R / lc[g], alpha / lc[g]) if norm(w[grp]", "/ lc[g], alpha / lc[g]) if norm(w[grp] - old_w_g) !=", "w[grp]) * Xg, axis=1) @njit def _bcd_sparse( X_data, X_indices, X_indptr,", "if algo == 'fista': R = y - X @", "if verbose: print(\"elapsed time: %f \" % elapsed_times) if elapsed_times", "BST_vec(w + X.T @ R / L, alpha / L,", "X.shape[1] if n_features % grp_size != 0: raise ValueError(\"n_features is", "compute_time=False, tmax=np.infty, verbose=True): \"\"\"Solve the GroupLasso with BCD/ISTA/FISTA, eventually with", "and not np.isfortran(X): X = np.asfortranarray(X) last_K_w = np.zeros([K +", "% grp_size]) * X_data[ix] def solver_group( X, y, alpha, grp_size,", "allowed to run alpha: strength of the group penalty \"\"\"", "None]).reshape(x.shape[0]) @njit def _bcd(X, w, R, alpha, lc, groups): grp_size", "import time import numpy as np from scipy import sparse", "scaling = np.maximum(1 - u / norm_grp, 0) return (x.reshape(-1,", "of group size\") n_groups = n_features // grp_size _range =", "0: R += np.sum((old_w_g - w[grp]) * Xg, axis=1) @njit", "groups[algo]()) elif algo == 'pgd': w[:] = BST_vec(w + X.T", "elif algo == 'fista': w_old = w.copy() w[:] = BST_vec(z", "/ t_new * (w - w_old) else: raise ValueError(\"Unknown algo", "theta /= d_norm_theta d_obj = dual_lasso(y, theta, alpha) gap =", "w, alpha, grp_size) R_acc = y - X @ w_acc", "alpha: strength of the group penalty \"\"\" is_sparse = sparse.issparse(X)", "extrapolation. Groups are contiguous, of size grp_size. Objective: norm(y -", "* c[:, None], axis=0) p_obj = primal_grp(R, w, alpha, grp_size)", "R += np.sum((old_w_g - w[grp]) * Xg, axis=1) @njit def", "2 lc = np.zeros(n_groups) for g in range(n_groups): X_g =", "/ 2 + alpha * sum_g ||w_{[g]}||_2 TODO: filled docstring", "n_features // grp_size _range = np.arange(n_groups) groups = dict( bcd=lambda:", "(g + 1) * grp_size) for j in range(grp_size *", "R_acc except np.linalg.LinAlgError: if verbose: print(\"----------Linalg error\") if compute_time: return", "+ 4 * t_old ** 2)) / 2. z[:] =", "axis=1) scaling = np.maximum(1 - u / norm_grp, 0) return", "2 + alpha * sum_g ||w_{[g]}||_2 TODO: filled docstring Parameters:", "n_features]) if algo in ('pgd', 'fista'): if is_sparse: L =", "C = np.dot(U, U.T) try: z = np.linalg.solve(C, np.ones(K)) c", "soft-thresholding of vector x at level u.\"\"\" norm_x = norm(x)", "%d, p_obj::%.5f, d_obj::%.5f, gap::%.2e\" % (it, p_obj, d_obj, gap)) gaps[it", "alpha, grp_size, max_iter=10000, tol=1e-4, f_gap=10, K=5, use_acc=False, algo='bcd', compute_time=False, tmax=np.infty,", "** 2 + alpha * norm(w.reshape(-1, grp_size), axis=1).sum()) @njit def", "w elif algo == 'fista': w_old = w.copy() w[:] =", "* norm(w.reshape(-1, grp_size), axis=1).sum()) @njit def BST(x, u): \"\"\"Block soft-thresholding", "print(\"Early exit\") break if algo.endswith('bcd'): if is_sparse: _bcd_sparse( X.data, X.indices,", "compute_time: return w, np.array(E), gaps[:it // f_gap + 1], times", "= X.shape[1] if n_features % grp_size != 0: raise ValueError(\"n_features", "x def BST_vec(x, u, grp_size): norm_grp = norm(x.reshape(-1, grp_size), axis=1)", "max_iter=10000, tol=1e-4, f_gap=10, K=5, use_acc=False, algo='bcd', compute_time=False, tmax=np.infty, verbose=True): \"\"\"Solve", "you want to compute timings or not tmax : float,", "** 2 lc = np.zeros(n_groups) for g in range(n_groups): X_g", "- X @ w_acc p_obj_acc = primal_grp(R_acc, w_acc, alpha, grp_size)", "t_start times.append(elapsed_times) if verbose: print(\"elapsed time: %f \" % elapsed_times)", "old_w_g) != 0: for j in range(g * grp_size, (g", "p_obj, d_obj, gap)) gaps[it // f_gap] = gap if gap", "with BCD/ISTA/FISTA, eventually with extrapolation. Groups are contiguous, of size", "grp_size * (g + 1)): for ix in range(X_indptr[j], X_indptr[j", "p_obj - d_obj if verbose: print(\"Iteration %d, p_obj::%.5f, d_obj::%.5f, gap::%.2e\"", "- last_K_w[k] C = np.dot(U, U.T) try: z = np.linalg.solve(C,", "w[j % grp_size]) * X_data[ix] def solver_group( X, y, alpha,", "= w for k in range(K): U[k] = last_K_w[k +", "replace=True)) if not is_sparse and not np.isfortran(X): X = np.asfortranarray(X)", "to run alpha: strength of the group penalty \"\"\" is_sparse", "x at level u.\"\"\" norm_x = norm(x) if norm_x <", "\"\"\" is_sparse = sparse.issparse(X) n_features = X.shape[1] if n_features %", "primal_grp(R, w, alpha, grp_size): return (0.5 * norm(R) ** 2", "+ np.sqrt(1 + 4 * t_old ** 2)) / 2.", "print(\"Iteration %d, p_obj::%.5f, d_obj::%.5f, gap::%.2e\" % (it, p_obj, d_obj, gap))", "1] = w for k in range(K): U[k] = last_K_w[k", "- t_start times.append(elapsed_times) if verbose: print(\"elapsed time: %f \" %", "Objective: norm(y - Xw, ord=2)**2 / 2 + alpha *", "def BST(x, u): \"\"\"Block soft-thresholding of vector x at level", "If you want to compute timings or not tmax :", "d_norm_theta d_obj = dual_lasso(y, theta, alpha) gap = p_obj -", "else: for k in range(K): last_K_w[k] = last_K_w[k + 1]", "= BST(old_w_g + Xg.T @ R / lc[g], alpha /", "* (g + 1)): for ix in range(X_indptr[j], X_indptr[j +", "import sparse from numba import njit from numpy.linalg import norm", "is_sparse and not np.isfortran(X): X = np.asfortranarray(X) last_K_w = np.zeros([K", "the algorithm is allowed to run alpha: strength of the", "seconds) the algorithm is allowed to run alpha: strength of", "lc[g] = norm(X_g, ord=2) ** 2 w = np.zeros(n_features) if", "= primal_grp(R, w, alpha, grp_size) R_acc = y - X", "2 w = np.zeros(n_features) if algo == 'fista': z =", "grp_size) Xg = X[:, grp] old_w_g = w[grp].copy() w[grp] =", "not is_sparse and not np.isfortran(X): X = np.asfortranarray(X) last_K_w =", "BST(old_w_g + grad / lc[g], alpha / lc[g]) if norm(w[grp]", "axis=1) @njit def _bcd_sparse( X_data, X_indices, X_indptr, w, R, alpha,", "R / L, alpha / L, grp_size) R[:] = y", "w_acc, alpha, grp_size) if p_obj_acc < p_obj: w = w_acc", "R / alpha if compute_time: elapsed_times = time.time() - t_start", "> 1.: theta /= d_norm_theta d_obj = dual_lasso(y, theta, alpha)", "\" % elapsed_times) if elapsed_times > tmax: break d_norm_theta =", "lc, groups): grp_size = w.shape[0] // lc.shape[0] for g in", "else: _bcd(X, w, R, alpha, lc, groups[algo]()) elif algo ==", "np.zeros(grp_size) for g in range(lc.shape[0]): grad.fill(0) grp = slice(g *", "X, y, alpha, grp_size, max_iter=10000, tol=1e-4, f_gap=10, K=5, use_acc=False, algo='bcd',", "* grp_size] if is_sparse: gram = (X_g.T @ X_g).todense() lc[g]", "f_gap) if compute_time: times = [] t_start = time.time() for", "it < K + 1: last_K_w[it] = w else: for", "scaling[:, None]).reshape(x.shape[0]) @njit def _bcd(X, w, R, alpha, lc, groups):", "= svds(X, k=1)[1][0] ** 2 else: L = norm(X, ord=2)", "X = np.asfortranarray(X) last_K_w = np.zeros([K + 1, n_features]) U", ": bool, default=False If you want to compute timings or", "alpha if compute_time: elapsed_times = time.time() - t_start times.append(elapsed_times) if", "\"\"\"Block soft-thresholding of vector x at level u.\"\"\" norm_x =", "last_K_w[k] = last_K_w[k + 1] last_K_w[K - 1] = w", "+ 1) * grp_size) Xg = X[:, grp] old_w_g =", "- X @ w elif algo == 'fista': w_old =", "(g + 1) * grp_size) Xg = X[:, grp] old_w_g", "X[:, g * grp_size: (g + 1) * grp_size] if", "@ R / lc[g], alpha / lc[g]) if norm(w[grp] -", "svds(X, k=1)[1][0] ** 2 else: L = norm(X, ord=2) **", "compute_time: times = [] t_start = time.time() for it in", "return np.zeros_like(x) else: return (1 - u / norm_x) *", "rbcd=lambda: np.random.choice(n_groups, n_groups, replace=True)) if not is_sparse and not np.isfortran(X):", "grp_size: (g + 1) * grp_size] if is_sparse: gram =", "w + (t_old - 1.) / t_new * (w -", "np.zeros(n_features) t_new = 1 R = y.copy() E = []", "** 2 else: L = norm(X, ord=2) ** 2 lc", "import numpy as np from scipy import sparse from numba", "return (0.5 * norm(R) ** 2 + alpha * norm(w.reshape(-1,", "= gap if gap < tol: print(\"Early exit\") break if", "grp_size): return (0.5 * norm(R) ** 2 + alpha *", "range(g * grp_size, (g + 1) * grp_size): for ix", "= [] gaps = np.zeros(max_iter // f_gap) if compute_time: times", "lc.shape[0] grad = np.zeros(grp_size) for g in range(lc.shape[0]): grad.fill(0) grp", "** 2)) / 2. z[:] = w + (t_old -", "@ z - y) / L, alpha / L, grp_size)", "alpha / L, grp_size) t_old = t_new t_new = (1.", "2. z[:] = w + (t_old - 1.) / t_new", "n_groups, replace=True)) if not is_sparse and not np.isfortran(X): X =", "z = np.linalg.solve(C, np.ones(K)) c = z / z.sum() w_acc", "BST(old_w_g + Xg.T @ R / lc[g], alpha / lc[g])", "return w, np.array(E), gaps[:it // f_gap + 1], times return", "u: return np.zeros_like(x) else: return (1 - u / norm_x)", "R / lc[g], alpha / lc[g]) if norm(w[grp] - old_w_g)", "groups): grp_size = w.shape[0] // lc.shape[0] for g in groups:", "Parameters: algo: string 'bcd', 'pgd', 'fista' compute_time : bool, default=False", "if is_sparse: gram = (X_g.T @ X_g).todense() lc[g] = norm(gram,", "exit\") break if algo.endswith('bcd'): if is_sparse: _bcd_sparse( X.data, X.indices, X.indptr,", "primal_grp(R_acc, w_acc, alpha, grp_size) if p_obj_acc < p_obj: w =", "grp_size != 0: raise ValueError(\"n_features is not a multiple of", "def _bcd_sparse( X_data, X_indices, X_indptr, w, R, alpha, lc): grp_size", "np.random.choice(n_groups, n_groups, replace=False), rbcd=lambda: np.random.choice(n_groups, n_groups, replace=True)) if not is_sparse", "= time.time() for it in range(max_iter): if it % f_gap", "= np.zeros(max_iter // f_gap) if compute_time: times = [] t_start", "t_new * (w - w_old) else: raise ValueError(\"Unknown algo %s\"", "ValueError(\"n_features is not a multiple of group size\") n_groups =", "for g in range(n_groups): X_g = X[:, g * grp_size:", "t_old ** 2)) / 2. z[:] = w + (t_old", "np.maximum(1 - u / norm_grp, 0) return (x.reshape(-1, grp_size) *", "of the group penalty \"\"\" is_sparse = sparse.issparse(X) n_features =", "if algo.endswith('bcd'): if is_sparse: _bcd_sparse( X.data, X.indices, X.indptr, w, R,", "d_obj::%.5f, gap::%.2e\" % (it, p_obj, d_obj, gap)) gaps[it // f_gap]", "if gap < tol: print(\"Early exit\") break if algo.endswith('bcd'): if", "if compute_time: return w, np.array(E), gaps[:it // f_gap + 1],", "+ 1)): for ix in range(X_indptr[j], X_indptr[j + 1]): grad[j", "/ lc[g]) if norm(w[grp] - old_w_g) != 0: for j", "grad[j % g] += X_data[ix] * R[X_indices[ix]] old_w_g = w[grp].copy()", "// lc.shape[0] grad = np.zeros(grp_size) for g in range(lc.shape[0]): grad.fill(0)", "= last_K_w[k + 1] last_K_w[K - 1] = w for", "if not is_sparse and not np.isfortran(X): X = np.asfortranarray(X) last_K_w", "= np.dot(U, U.T) try: z = np.linalg.solve(C, np.ones(K)) c =", "X_indices, X_indptr, w, R, alpha, lc): grp_size = w.shape[0] //", "Maximum time (in seconds) the algorithm is allowed to run", "== 'fista': R = y - X @ w p_obj", "groups: grp = slice(g * grp_size, (g + 1) *", "times = [] t_start = time.time() for it in range(max_iter):", "g, grp_size * (g + 1)): for ix in range(X_indptr[j],", "if norm(w[grp] - old_w_g) != 0: for j in range(g", "numba import njit from numpy.linalg import norm from scipy.sparse.linalg import", "/ L, grp_size) t_old = t_new t_new = (1. +", "= (X_g.T @ X_g).todense() lc[g] = norm(gram, ord=2) else: lc[g]", "for j in range(g * grp_size, (g + 1) *", "last_K_w[it] = w else: for k in range(K): last_K_w[k] =", "slice(g * grp_size, (g + 1) * grp_size) for j", "norm_grp, 0) return (x.reshape(-1, grp_size) * scaling[:, None]).reshape(x.shape[0]) @njit def", "+ 1]): grad[j % g] += X_data[ix] * R[X_indices[ix]] old_w_g", "= BST(old_w_g + grad / lc[g], alpha / lc[g]) if", "+ 1], times return w, np.array(E), gaps[:it // f_gap +", "grp_size) E.append(p_obj) theta = R / alpha if compute_time: elapsed_times", "* grp_size, (g + 1) * grp_size) Xg = X[:,", "<gh_stars>0 import time import numpy as np from scipy import", "solver_group( X, y, alpha, grp_size, max_iter=10000, tol=1e-4, f_gap=10, K=5, use_acc=False,", "except np.linalg.LinAlgError: if verbose: print(\"----------Linalg error\") if compute_time: return w,", "if verbose: print(\"----------Linalg error\") if compute_time: return w, np.array(E), gaps[:it", "- d_obj if verbose: print(\"Iteration %d, p_obj::%.5f, d_obj::%.5f, gap::%.2e\" %", "@ (X @ z - y) / L, alpha /", "range(lc.shape[0]): grad.fill(0) grp = slice(g * grp_size, (g + 1)", "w, alpha, grp_size) E.append(p_obj) theta = R / alpha if", "gap = p_obj - d_obj if verbose: print(\"Iteration %d, p_obj::%.5f,", "import svds from andersoncd.lasso import dual_lasso def primal_grp(R, w, alpha,", "t_new t_new = (1. + np.sqrt(1 + 4 * t_old", "!= 0: R += np.sum((old_w_g - w[grp]) * Xg, axis=1)", "* t_old ** 2)) / 2. z[:] = w +", "multiple of group size\") n_groups = n_features // grp_size _range", "= y.copy() E = [] gaps = np.zeros(max_iter // f_gap)", "grp_size) R_acc = y - X @ w_acc p_obj_acc =", "is_sparse: L = svds(X, k=1)[1][0] ** 2 else: L =", "verbose=True): \"\"\"Solve the GroupLasso with BCD/ISTA/FISTA, eventually with extrapolation. Groups", "theta, alpha) gap = p_obj - d_obj if verbose: print(\"Iteration", "elif algo == 'pgd': w[:] = BST_vec(w + X.T @", "try: z = np.linalg.solve(C, np.ones(K)) c = z / z.sum()", "+ 1, n_features]) U = np.zeros([K, n_features]) if algo in", "= norm(x) if norm_x < u: return np.zeros_like(x) else: return", "_bcd_sparse( X.data, X.indices, X.indptr, w, R, alpha, lc) else: _bcd(X,", "== 'fista': w_old = w.copy() w[:] = BST_vec(z - X.T", "grp_size _range = np.arange(n_groups) groups = dict( bcd=lambda: _range, bcdshuf=lambda:", "= n_features // grp_size _range = np.arange(n_groups) groups = dict(", "X_g = X[:, g * grp_size: (g + 1) *", "norm_grp = norm(x.reshape(-1, grp_size), axis=1) scaling = np.maximum(1 - u", "@njit def BST(x, u): \"\"\"Block soft-thresholding of vector x at", "- X @ w p_obj = primal_grp(R, w, alpha, grp_size)", "grad = np.zeros(grp_size) for g in range(lc.shape[0]): grad.fill(0) grp =", "@ w elif algo == 'fista': w_old = w.copy() w[:]", "1]): grad[j % g] += X_data[ix] * R[X_indices[ix]] old_w_g =", "* sum_g ||w_{[g]}||_2 TODO: filled docstring Parameters: algo: string 'bcd',", "in ('pgd', 'fista'): if is_sparse: L = svds(X, k=1)[1][0] **", "== 0: if algo == 'fista': R = y -", "X_data, X_indices, X_indptr, w, R, alpha, lc): grp_size = w.shape[0]", "gaps = np.zeros(max_iter // f_gap) if compute_time: times = []", "group penalty \"\"\" is_sparse = sparse.issparse(X) n_features = X.shape[1] if", "X.indptr, w, R, alpha, lc) else: _bcd(X, w, R, alpha,", "f_gap] = gap if gap < tol: print(\"Early exit\") break", "> tmax: break d_norm_theta = np.max( norm((X.T @ theta).reshape(-1, grp_size),", "c = z / z.sum() w_acc = np.sum(last_K_w[:-1] * c[:,", "0: if algo == 'fista': R = y - X", "1) * grp_size) Xg = X[:, grp] old_w_g = w[grp].copy()", "filled docstring Parameters: algo: string 'bcd', 'pgd', 'fista' compute_time :", "p_obj: w = w_acc R = R_acc except np.linalg.LinAlgError: if", "p_obj_acc < p_obj: w = w_acc R = R_acc except", "w, np.array(E), gaps[:it // f_gap + 1], times return w,", "* X_data[ix] def solver_group( X, y, alpha, grp_size, max_iter=10000, tol=1e-4,", "- u / norm_grp, 0) return (x.reshape(-1, grp_size) * scaling[:,", "verbose: print(\"Iteration %d, p_obj::%.5f, d_obj::%.5f, gap::%.2e\" % (it, p_obj, d_obj,", "+ alpha * sum_g ||w_{[g]}||_2 TODO: filled docstring Parameters: algo:", "z = np.zeros(n_features) t_new = 1 R = y.copy() E", "p_obj_acc = primal_grp(R_acc, w_acc, alpha, grp_size) if p_obj_acc < p_obj:", "alpha * norm(w.reshape(-1, grp_size), axis=1).sum()) @njit def BST(x, u): \"\"\"Block", "y, alpha, grp_size, max_iter=10000, tol=1e-4, f_gap=10, K=5, use_acc=False, algo='bcd', compute_time=False,", "np.sum(last_K_w[:-1] * c[:, None], axis=0) p_obj = primal_grp(R, w, alpha,", "as np from scipy import sparse from numba import njit", "def _bcd(X, w, R, alpha, lc, groups): grp_size = w.shape[0]", "norm(R) ** 2 + alpha * norm(w.reshape(-1, grp_size), axis=1).sum()) @njit", "np.zeros(n_groups) for g in range(n_groups): X_g = X[:, g *", "+ 1) * grp_size): for ix in range(X_indptr[j], X_indptr[j +", "(1. + np.sqrt(1 + 4 * t_old ** 2)) /", "+ 1]): R[X_indices[ix]] += (old_w_g[j % grp_size] - w[j %", "1) * grp_size] if is_sparse: gram = (X_g.T @ X_g).todense()", "@ theta).reshape(-1, grp_size), axis=1)) if d_norm_theta > 1.: theta /=", "if it < K + 1: last_K_w[it] = w else:", "_bcd_sparse( X_data, X_indices, X_indptr, w, R, alpha, lc): grp_size =", "p_obj::%.5f, d_obj::%.5f, gap::%.2e\" % (it, p_obj, d_obj, gap)) gaps[it //", "= last_K_w[k + 1] - last_K_w[k] C = np.dot(U, U.T)", "%f \" % elapsed_times) if elapsed_times > tmax: break d_norm_theta", "w = w_acc R = R_acc except np.linalg.LinAlgError: if verbose:", "algo in ('pgd', 'fista'): if is_sparse: L = svds(X, k=1)[1][0]", "g in groups: grp = slice(g * grp_size, (g +", "@njit def _bcd_sparse( X_data, X_indices, X_indptr, w, R, alpha, lc):", "/ alpha if compute_time: elapsed_times = time.time() - t_start times.append(elapsed_times)", "g in range(lc.shape[0]): grad.fill(0) grp = slice(g * grp_size, (g", "w p_obj = primal_grp(R, w, alpha, grp_size) E.append(p_obj) theta =", "/ L, alpha / L, grp_size) R[:] = y -", "compute_time: elapsed_times = time.time() - t_start times.append(elapsed_times) if verbose: print(\"elapsed", "algo == 'fista': z = np.zeros(n_features) t_new = 1 R", "n_groups, replace=False), rbcd=lambda: np.random.choice(n_groups, n_groups, replace=True)) if not is_sparse and", "GroupLasso with BCD/ISTA/FISTA, eventually with extrapolation. Groups are contiguous, of", "gram = (X_g.T @ X_g).todense() lc[g] = norm(gram, ord=2) else:", "= np.linalg.solve(C, np.ones(K)) c = z / z.sum() w_acc =", "w, R, alpha, lc, groups): grp_size = w.shape[0] // lc.shape[0]", "if it % f_gap == 0: if algo == 'fista':", "norm(X, ord=2) ** 2 lc = np.zeros(n_groups) for g in", "+ Xg.T @ R / lc[g], alpha / lc[g]) if", "np.arange(n_groups) groups = dict( bcd=lambda: _range, bcdshuf=lambda: np.random.choice(n_groups, n_groups, replace=False),", "* grp_size: (g + 1) * grp_size] if is_sparse: gram", "/ L, grp_size) R[:] = y - X @ w", "theta = R / alpha if compute_time: elapsed_times = time.time()", "p_obj = primal_grp(R, w, alpha, grp_size) R_acc = y -", "verbose: print(\"----------Linalg error\") if compute_time: return w, np.array(E), gaps[:it //", "from numpy.linalg import norm from scipy.sparse.linalg import svds from andersoncd.lasso", "* Xg, axis=1) @njit def _bcd_sparse( X_data, X_indices, X_indptr, w,", "y - X @ w p_obj = primal_grp(R, w, alpha,", "= np.zeros([K, n_features]) if algo in ('pgd', 'fista'): if is_sparse:", "/ norm_x) * x def BST_vec(x, u, grp_size): norm_grp =", "= np.zeros(n_features) t_new = 1 R = y.copy() E =", "algo == 'fista': R = y - X @ w", "contiguous, of size grp_size. Objective: norm(y - Xw, ord=2)**2 /", "n_features]) U = np.zeros([K, n_features]) if algo in ('pgd', 'fista'):", "time: %f \" % elapsed_times) if elapsed_times > tmax: break", "ord=2) else: lc[g] = norm(X_g, ord=2) ** 2 w =", "verbose: print(\"elapsed time: %f \" % elapsed_times) if elapsed_times >", "norm(x.reshape(-1, grp_size), axis=1) scaling = np.maximum(1 - u / norm_grp,", "for ix in range(X_indptr[j], X_indptr[j + 1]): grad[j % g]", "* grp_size): for ix in range(X_indptr[j], X_indptr[j + 1]): R[X_indices[ix]]", "_range, bcdshuf=lambda: np.random.choice(n_groups, n_groups, replace=False), rbcd=lambda: np.random.choice(n_groups, n_groups, replace=True)) if", "old_w_g = w[grp].copy() w[grp] = BST(old_w_g + grad / lc[g],", "+= np.sum((old_w_g - w[grp]) * Xg, axis=1) @njit def _bcd_sparse(", "lc[g]) if norm(w[grp] - old_w_g) != 0: R += np.sum((old_w_g", "if norm_x < u: return np.zeros_like(x) else: return (1 -", "+ alpha * norm(w.reshape(-1, grp_size), axis=1).sum()) @njit def BST(x, u):", "times.append(elapsed_times) if verbose: print(\"elapsed time: %f \" % elapsed_times) if", "tol: print(\"Early exit\") break if algo.endswith('bcd'): if is_sparse: _bcd_sparse( X.data,", "y) / L, alpha / L, grp_size) t_old = t_new", "w, alpha, grp_size): return (0.5 * norm(R) ** 2 +", "grp_size) if p_obj_acc < p_obj: w = w_acc R =", "= dict( bcd=lambda: _range, bcdshuf=lambda: np.random.choice(n_groups, n_groups, replace=False), rbcd=lambda: np.random.choice(n_groups,", "time.time() - t_start times.append(elapsed_times) if verbose: print(\"elapsed time: %f \"", "compute_time : bool, default=False If you want to compute timings", "grp_size, (g + 1) * grp_size): for ix in range(X_indptr[j],", "w[:] = BST_vec(w + X.T @ R / L, alpha", "grp_size, (g + 1) * grp_size) Xg = X[:, grp]", "TODO: filled docstring Parameters: algo: string 'bcd', 'pgd', 'fista' compute_time", "= np.zeros(n_features) if algo == 'fista': z = np.zeros(n_features) t_new", "at level u.\"\"\" norm_x = norm(x) if norm_x < u:", "if norm(w[grp] - old_w_g) != 0: R += np.sum((old_w_g -", "grp_size]) * X_data[ix] def solver_group( X, y, alpha, grp_size, max_iter=10000,", "= w[grp].copy() w[grp] = BST(old_w_g + Xg.T @ R /", "(0.5 * norm(R) ** 2 + alpha * norm(w.reshape(-1, grp_size),", "in range(grp_size * g, grp_size * (g + 1)): for", "grp_size): norm_grp = norm(x.reshape(-1, grp_size), axis=1) scaling = np.maximum(1 -", "for j in range(grp_size * g, grp_size * (g +", "dual_lasso(y, theta, alpha) gap = p_obj - d_obj if verbose:", "/= d_norm_theta d_obj = dual_lasso(y, theta, alpha) gap = p_obj", "time import numpy as np from scipy import sparse from", "= y - X @ w_acc p_obj_acc = primal_grp(R_acc, w_acc,", "(t_old - 1.) / t_new * (w - w_old) else:", "* g, grp_size * (g + 1)): for ix in", "range(K): last_K_w[k] = last_K_w[k + 1] last_K_w[K - 1] =", "+= (old_w_g[j % grp_size] - w[j % grp_size]) * X_data[ix]", "size grp_size. Objective: norm(y - Xw, ord=2)**2 / 2 +", "= dual_lasso(y, theta, alpha) gap = p_obj - d_obj if", "break if algo.endswith('bcd'): if is_sparse: _bcd_sparse( X.data, X.indices, X.indptr, w,", "+ 1) * grp_size) for j in range(grp_size * g,", "(X_g.T @ X_g).todense() lc[g] = norm(gram, ord=2) else: lc[g] =", "time.time() for it in range(max_iter): if it % f_gap ==", "= R / alpha if compute_time: elapsed_times = time.time() -", "* grp_size) for j in range(grp_size * g, grp_size *", "/ lc[g]) if norm(w[grp] - old_w_g) != 0: R +=", "X_indptr, w, R, alpha, lc): grp_size = w.shape[0] // lc.shape[0]", "z[:] = w + (t_old - 1.) / t_new *", "alpha, lc, groups): grp_size = w.shape[0] // lc.shape[0] for g", "= w.shape[0] // lc.shape[0] grad = np.zeros(grp_size) for g in", "% g] += X_data[ix] * R[X_indices[ix]] old_w_g = w[grp].copy() w[grp]", "R[:] = y - X @ w elif algo ==", "[] gaps = np.zeros(max_iter // f_gap) if compute_time: times =", "scipy import sparse from numba import njit from numpy.linalg import", "grp_size), axis=1).sum()) @njit def BST(x, u): \"\"\"Block soft-thresholding of vector", "== 'pgd': w[:] = BST_vec(w + X.T @ R /", "if use_acc: if it < K + 1: last_K_w[it] =", "algo='bcd', compute_time=False, tmax=np.infty, verbose=True): \"\"\"Solve the GroupLasso with BCD/ISTA/FISTA, eventually", "E = [] gaps = np.zeros(max_iter // f_gap) if compute_time:", "= X[:, grp] old_w_g = w[grp].copy() w[grp] = BST(old_w_g +", "* (w - w_old) else: raise ValueError(\"Unknown algo %s\" %", "norm from scipy.sparse.linalg import svds from andersoncd.lasso import dual_lasso def", "f_gap + 1], times return w, np.array(E), gaps[:it // f_gap", "np.zeros(max_iter // f_gap) if compute_time: times = [] t_start =", "(w - w_old) else: raise ValueError(\"Unknown algo %s\" % algo)", "y.copy() E = [] gaps = np.zeros(max_iter // f_gap) if", "0: for j in range(g * grp_size, (g + 1)", "w_old = w.copy() w[:] = BST_vec(z - X.T @ (X", "break d_norm_theta = np.max( norm((X.T @ theta).reshape(-1, grp_size), axis=1)) if", "'fista' compute_time : bool, default=False If you want to compute", "not tmax : float, default=1000 Maximum time (in seconds) the", "@ w_acc p_obj_acc = primal_grp(R_acc, w_acc, alpha, grp_size) if p_obj_acc", "error\") if compute_time: return w, np.array(E), gaps[:it // f_gap +", "1] last_K_w[K - 1] = w for k in range(K):", "1: last_K_w[it] = w else: for k in range(K): last_K_w[k]", "from scipy.sparse.linalg import svds from andersoncd.lasso import dual_lasso def primal_grp(R,", "L, alpha / L, grp_size) R[:] = y - X", "w[grp].copy() w[grp] = BST(old_w_g + Xg.T @ R / lc[g],", "grad / lc[g], alpha / lc[g]) if norm(w[grp] - old_w_g)", "- w[grp]) * Xg, axis=1) @njit def _bcd_sparse( X_data, X_indices,", "if compute_time: elapsed_times = time.time() - t_start times.append(elapsed_times) if verbose:", "if algo == 'fista': z = np.zeros(n_features) t_new = 1", "- old_w_g) != 0: R += np.sum((old_w_g - w[grp]) *", "g] += X_data[ix] * R[X_indices[ix]] old_w_g = w[grp].copy() w[grp] =", "w_old) else: raise ValueError(\"Unknown algo %s\" % algo) if use_acc:", "range(max_iter): if it % f_gap == 0: if algo ==", "grp_size, (g + 1) * grp_size) for j in range(grp_size", "w.shape[0] // lc.shape[0] for g in groups: grp = slice(g", "grp_size) * scaling[:, None]).reshape(x.shape[0]) @njit def _bcd(X, w, R, alpha,", "k=1)[1][0] ** 2 else: L = norm(X, ord=2) ** 2", "sparse.issparse(X) n_features = X.shape[1] if n_features % grp_size != 0:", "for g in groups: grp = slice(g * grp_size, (g", "lc[g]) if norm(w[grp] - old_w_g) != 0: for j in", "= [] t_start = time.time() for it in range(max_iter): if", "* x def BST_vec(x, u, grp_size): norm_grp = norm(x.reshape(-1, grp_size),", "_bcd(X, w, R, alpha, lc, groups): grp_size = w.shape[0] //", "grp_size), axis=1) scaling = np.maximum(1 - u / norm_grp, 0)", "replace=False), rbcd=lambda: np.random.choice(n_groups, n_groups, replace=True)) if not is_sparse and not", "old_w_g) != 0: R += np.sum((old_w_g - w[grp]) * Xg,", "gap < tol: print(\"Early exit\") break if algo.endswith('bcd'): if is_sparse:", "if verbose: print(\"Iteration %d, p_obj::%.5f, d_obj::%.5f, gap::%.2e\" % (it, p_obj,", "u / norm_x) * x def BST_vec(x, u, grp_size): norm_grp", "X.indices, X.indptr, w, R, alpha, lc) else: _bcd(X, w, R,", "(X @ z - y) / L, alpha / L,", "'fista': z = np.zeros(n_features) t_new = 1 R = y.copy()", "grad.fill(0) grp = slice(g * grp_size, (g + 1) *", "w[grp] = BST(old_w_g + grad / lc[g], alpha / lc[g])", "E.append(p_obj) theta = R / alpha if compute_time: elapsed_times =", "use_acc: if it < K + 1: last_K_w[it] = w", "alpha) gap = p_obj - d_obj if verbose: print(\"Iteration %d,", "of size grp_size. Objective: norm(y - Xw, ord=2)**2 / 2", "algo %s\" % algo) if use_acc: if it < K", "= BST_vec(z - X.T @ (X @ z - y)", "groups = dict( bcd=lambda: _range, bcdshuf=lambda: np.random.choice(n_groups, n_groups, replace=False), rbcd=lambda:", "alpha, grp_size) if p_obj_acc < p_obj: w = w_acc R", "X[:, grp] old_w_g = w[grp].copy() w[grp] = BST(old_w_g + Xg.T", "+= X_data[ix] * R[X_indices[ix]] old_w_g = w[grp].copy() w[grp] = BST(old_w_g", "not np.isfortran(X): X = np.asfortranarray(X) last_K_w = np.zeros([K + 1,", "j in range(g * grp_size, (g + 1) * grp_size):", "import njit from numpy.linalg import norm from scipy.sparse.linalg import svds", "the group penalty \"\"\" is_sparse = sparse.issparse(X) n_features = X.shape[1]", "0: raise ValueError(\"n_features is not a multiple of group size\")", "bcdshuf=lambda: np.random.choice(n_groups, n_groups, replace=False), rbcd=lambda: np.random.choice(n_groups, n_groups, replace=True)) if not", "'pgd': w[:] = BST_vec(w + X.T @ R / L,", "want to compute timings or not tmax : float, default=1000", "slice(g * grp_size, (g + 1) * grp_size) Xg =", "lc[g], alpha / lc[g]) if norm(w[grp] - old_w_g) != 0:", "dict( bcd=lambda: _range, bcdshuf=lambda: np.random.choice(n_groups, n_groups, replace=False), rbcd=lambda: np.random.choice(n_groups, n_groups,", "* norm(R) ** 2 + alpha * norm(w.reshape(-1, grp_size), axis=1).sum())", "sum_g ||w_{[g]}||_2 TODO: filled docstring Parameters: algo: string 'bcd', 'pgd',", "f_gap=10, K=5, use_acc=False, algo='bcd', compute_time=False, tmax=np.infty, verbose=True): \"\"\"Solve the GroupLasso", "return (x.reshape(-1, grp_size) * scaling[:, None]).reshape(x.shape[0]) @njit def _bcd(X, w,", "norm(x) if norm_x < u: return np.zeros_like(x) else: return (1", "gap::%.2e\" % (it, p_obj, d_obj, gap)) gaps[it // f_gap] =", "= time.time() - t_start times.append(elapsed_times) if verbose: print(\"elapsed time: %f", "default=False If you want to compute timings or not tmax", "(in seconds) the algorithm is allowed to run alpha: strength", "or not tmax : float, default=1000 Maximum time (in seconds)", "last_K_w[k] C = np.dot(U, U.T) try: z = np.linalg.solve(C, np.ones(K))", "1], times return w, np.array(E), gaps[:it // f_gap + 1]", "== 'fista': z = np.zeros(n_features) t_new = 1 R =", "grp = slice(g * grp_size, (g + 1) * grp_size)", "norm_x < u: return np.zeros_like(x) else: return (1 - u", "alpha / L, grp_size) R[:] = y - X @", "norm_x) * x def BST_vec(x, u, grp_size): norm_grp = norm(x.reshape(-1,", "* grp_size) Xg = X[:, grp] old_w_g = w[grp].copy() w[grp]", "X.T @ (X @ z - y) / L, alpha", "tmax: break d_norm_theta = np.max( norm((X.T @ theta).reshape(-1, grp_size), axis=1))", "/ norm_grp, 0) return (x.reshape(-1, grp_size) * scaling[:, None]).reshape(x.shape[0]) @njit", "R[X_indices[ix]] += (old_w_g[j % grp_size] - w[j % grp_size]) *", "run alpha: strength of the group penalty \"\"\" is_sparse =", "vector x at level u.\"\"\" norm_x = norm(x) if norm_x", "= norm(x.reshape(-1, grp_size), axis=1) scaling = np.maximum(1 - u /", "= sparse.issparse(X) n_features = X.shape[1] if n_features % grp_size !=", "'fista': w_old = w.copy() w[:] = BST_vec(z - X.T @", "in range(max_iter): if it % f_gap == 0: if algo", "+ (t_old - 1.) / t_new * (w - w_old)", "- y) / L, alpha / L, grp_size) t_old =", "w.shape[0] // lc.shape[0] grad = np.zeros(grp_size) for g in range(lc.shape[0]):", "gap)) gaps[it // f_gap] = gap if gap < tol:", "+ 1] last_K_w[K - 1] = w for k in", "for g in range(lc.shape[0]): grad.fill(0) grp = slice(g * grp_size,", "= slice(g * grp_size, (g + 1) * grp_size) for", "||w_{[g]}||_2 TODO: filled docstring Parameters: algo: string 'bcd', 'pgd', 'fista'", "primal_grp(R, w, alpha, grp_size) E.append(p_obj) theta = R / alpha", "use_acc=False, algo='bcd', compute_time=False, tmax=np.infty, verbose=True): \"\"\"Solve the GroupLasso with BCD/ISTA/FISTA,", "grp_size] if is_sparse: gram = (X_g.T @ X_g).todense() lc[g] =", "= R_acc except np.linalg.LinAlgError: if verbose: print(\"----------Linalg error\") if compute_time:", "for it in range(max_iter): if it % f_gap == 0:", "from numba import njit from numpy.linalg import norm from scipy.sparse.linalg", "numpy as np from scipy import sparse from numba import", "algorithm is allowed to run alpha: strength of the group", "f_gap == 0: if algo == 'fista': R = y", "eventually with extrapolation. Groups are contiguous, of size grp_size. Objective:", "= X[:, g * grp_size: (g + 1) * grp_size]", "theta).reshape(-1, grp_size), axis=1)) if d_norm_theta > 1.: theta /= d_norm_theta", "axis=0) p_obj = primal_grp(R, w, alpha, grp_size) R_acc = y", "compute timings or not tmax : float, default=1000 Maximum time", "ix in range(X_indptr[j], X_indptr[j + 1]): grad[j % g] +=", "np.zeros_like(x) else: return (1 - u / norm_x) * x", "is allowed to run alpha: strength of the group penalty", "t_new = 1 R = y.copy() E = [] gaps", "is_sparse: gram = (X_g.T @ X_g).todense() lc[g] = norm(gram, ord=2)", "'bcd', 'pgd', 'fista' compute_time : bool, default=False If you want", "= t_new t_new = (1. + np.sqrt(1 + 4 *", "t_new = (1. + np.sqrt(1 + 4 * t_old **", "= y - X @ w elif algo == 'fista':", "the GroupLasso with BCD/ISTA/FISTA, eventually with extrapolation. Groups are contiguous,", "range(n_groups): X_g = X[:, g * grp_size: (g + 1)", "norm(w[grp] - old_w_g) != 0: for j in range(g *", "w for k in range(K): U[k] = last_K_w[k + 1]", "(x.reshape(-1, grp_size) * scaling[:, None]).reshape(x.shape[0]) @njit def _bcd(X, w, R,", "norm(gram, ord=2) else: lc[g] = norm(X_g, ord=2) ** 2 w", "(it, p_obj, d_obj, gap)) gaps[it // f_gap] = gap if", "2 + alpha * norm(w.reshape(-1, grp_size), axis=1).sum()) @njit def BST(x,", "u / norm_grp, 0) return (x.reshape(-1, grp_size) * scaling[:, None]).reshape(x.shape[0])", "default=1000 Maximum time (in seconds) the algorithm is allowed to", "('pgd', 'fista'): if is_sparse: L = svds(X, k=1)[1][0] ** 2", "(g + 1)): for ix in range(X_indptr[j], X_indptr[j + 1]):", "_range = np.arange(n_groups) groups = dict( bcd=lambda: _range, bcdshuf=lambda: np.random.choice(n_groups,", "if is_sparse: L = svds(X, k=1)[1][0] ** 2 else: L", "2)) / 2. z[:] = w + (t_old - 1.)", "bool, default=False If you want to compute timings or not", "elapsed_times > tmax: break d_norm_theta = np.max( norm((X.T @ theta).reshape(-1,", "tmax : float, default=1000 Maximum time (in seconds) the algorithm", "np.zeros([K + 1, n_features]) U = np.zeros([K, n_features]) if algo", "= BST_vec(w + X.T @ R / L, alpha /", "import dual_lasso def primal_grp(R, w, alpha, grp_size): return (0.5 *", "K + 1: last_K_w[it] = w else: for k in", "gaps[:it // f_gap + 1], times return w, np.array(E), gaps[:it", "w[grp].copy() w[grp] = BST(old_w_g + grad / lc[g], alpha /", "'fista': R = y - X @ w p_obj =", "is not a multiple of group size\") n_groups = n_features", "axis=1)) if d_norm_theta > 1.: theta /= d_norm_theta d_obj =", "alpha * sum_g ||w_{[g]}||_2 TODO: filled docstring Parameters: algo: string", "1) * grp_size): for ix in range(X_indptr[j], X_indptr[j + 1]):", "X_g).todense() lc[g] = norm(gram, ord=2) else: lc[g] = norm(X_g, ord=2)", "alpha, grp_size): return (0.5 * norm(R) ** 2 + alpha", "in range(X_indptr[j], X_indptr[j + 1]): grad[j % g] += X_data[ix]", "= primal_grp(R_acc, w_acc, alpha, grp_size) if p_obj_acc < p_obj: w", "= np.zeros(grp_size) for g in range(lc.shape[0]): grad.fill(0) grp = slice(g", "if d_norm_theta > 1.: theta /= d_norm_theta d_obj = dual_lasso(y,", "1)): for ix in range(X_indptr[j], X_indptr[j + 1]): grad[j %", "in range(g * grp_size, (g + 1) * grp_size): for", "timings or not tmax : float, default=1000 Maximum time (in", "d_norm_theta = np.max( norm((X.T @ theta).reshape(-1, grp_size), axis=1)) if d_norm_theta", "range(K): U[k] = last_K_w[k + 1] - last_K_w[k] C =", "= np.asfortranarray(X) last_K_w = np.zeros([K + 1, n_features]) U =", "z.sum() w_acc = np.sum(last_K_w[:-1] * c[:, None], axis=0) p_obj =", "norm(w[grp] - old_w_g) != 0: R += np.sum((old_w_g - w[grp])", "= w else: for k in range(K): last_K_w[k] = last_K_w[k", "w_acc p_obj_acc = primal_grp(R_acc, w_acc, alpha, grp_size) if p_obj_acc <", "/ 2. z[:] = w + (t_old - 1.) /", "Xw, ord=2)**2 / 2 + alpha * sum_g ||w_{[g]}||_2 TODO:", "to compute timings or not tmax : float, default=1000 Maximum", "+ grad / lc[g], alpha / lc[g]) if norm(w[grp] -", "L, grp_size) t_old = t_new t_new = (1. + np.sqrt(1", "np.isfortran(X): X = np.asfortranarray(X) last_K_w = np.zeros([K + 1, n_features])", "alpha, lc) else: _bcd(X, w, R, alpha, lc, groups[algo]()) elif", "np.asfortranarray(X) last_K_w = np.zeros([K + 1, n_features]) U = np.zeros([K,", "w.copy() w[:] = BST_vec(z - X.T @ (X @ z", "BCD/ISTA/FISTA, eventually with extrapolation. Groups are contiguous, of size grp_size.", "not a multiple of group size\") n_groups = n_features //", "print(\"----------Linalg error\") if compute_time: return w, np.array(E), gaps[:it // f_gap", "d_obj = dual_lasso(y, theta, alpha) gap = p_obj - d_obj", "U[k] = last_K_w[k + 1] - last_K_w[k] C = np.dot(U,", "c[:, None], axis=0) p_obj = primal_grp(R, w, alpha, grp_size) R_acc", "norm(X_g, ord=2) ** 2 w = np.zeros(n_features) if algo ==", "(1 - u / norm_x) * x def BST_vec(x, u,", "if n_features % grp_size != 0: raise ValueError(\"n_features is not", "(g + 1) * grp_size): for ix in range(X_indptr[j], X_indptr[j", "numpy.linalg import norm from scipy.sparse.linalg import svds from andersoncd.lasso import", "level u.\"\"\" norm_x = norm(x) if norm_x < u: return", "* R[X_indices[ix]] old_w_g = w[grp].copy() w[grp] = BST(old_w_g + grad", "n_features % grp_size != 0: raise ValueError(\"n_features is not a", "np.max( norm((X.T @ theta).reshape(-1, grp_size), axis=1)) if d_norm_theta > 1.:", "= np.sum(last_K_w[:-1] * c[:, None], axis=0) p_obj = primal_grp(R, w,", "X @ w elif algo == 'fista': w_old = w.copy()", "+ X.T @ R / L, alpha / L, grp_size)", "in range(n_groups): X_g = X[:, g * grp_size: (g +", "R = R_acc except np.linalg.LinAlgError: if verbose: print(\"----------Linalg error\") if", "!= 0: raise ValueError(\"n_features is not a multiple of group", "R, alpha, lc, groups[algo]()) elif algo == 'pgd': w[:] =", "L = svds(X, k=1)[1][0] ** 2 else: L = norm(X,", "y - X @ w elif algo == 'fista': w_old", "@ w p_obj = primal_grp(R, w, alpha, grp_size) E.append(p_obj) theta", "u.\"\"\" norm_x = norm(x) if norm_x < u: return np.zeros_like(x)", "* scaling[:, None]).reshape(x.shape[0]) @njit def _bcd(X, w, R, alpha, lc,", "0) return (x.reshape(-1, grp_size) * scaling[:, None]).reshape(x.shape[0]) @njit def _bcd(X,", "X_data[ix] * R[X_indices[ix]] old_w_g = w[grp].copy() w[grp] = BST(old_w_g +", "np.sum((old_w_g - w[grp]) * Xg, axis=1) @njit def _bcd_sparse( X_data,", "elapsed_times = time.time() - t_start times.append(elapsed_times) if verbose: print(\"elapsed time:", "< tol: print(\"Early exit\") break if algo.endswith('bcd'): if is_sparse: _bcd_sparse(", "algo) if use_acc: if it < K + 1: last_K_w[it]", "p_obj = primal_grp(R, w, alpha, grp_size) E.append(p_obj) theta = R", "ord=2) ** 2 w = np.zeros(n_features) if algo == 'fista':", "+ 1] - last_K_w[k] C = np.dot(U, U.T) try: z", "!= 0: for j in range(g * grp_size, (g +", "old_w_g = w[grp].copy() w[grp] = BST(old_w_g + Xg.T @ R", "= p_obj - d_obj if verbose: print(\"Iteration %d, p_obj::%.5f, d_obj::%.5f,", "np.zeros(n_features) if algo == 'fista': z = np.zeros(n_features) t_new =", "grp_size = w.shape[0] // lc.shape[0] grad = np.zeros(grp_size) for g", "L, alpha / L, grp_size) t_old = t_new t_new =", "in range(K): last_K_w[k] = last_K_w[k + 1] last_K_w[K - 1]", "it in range(max_iter): if it % f_gap == 0: if", "u, grp_size): norm_grp = norm(x.reshape(-1, grp_size), axis=1) scaling = np.maximum(1", "string 'bcd', 'pgd', 'fista' compute_time : bool, default=False If you", "= np.max( norm((X.T @ theta).reshape(-1, grp_size), axis=1)) if d_norm_theta >", "* grp_size, (g + 1) * grp_size): for ix in", "BST_vec(z - X.T @ (X @ z - y) /", "last_K_w[K - 1] = w for k in range(K): U[k]", "np.ones(K)) c = z / z.sum() w_acc = np.sum(last_K_w[:-1] *", "w, R, alpha, lc): grp_size = w.shape[0] // lc.shape[0] grad", "alpha, lc): grp_size = w.shape[0] // lc.shape[0] grad = np.zeros(grp_size)", "w_acc R = R_acc except np.linalg.LinAlgError: if verbose: print(\"----------Linalg error\")", "axis=1).sum()) @njit def BST(x, u): \"\"\"Block soft-thresholding of vector x", "d_obj if verbose: print(\"Iteration %d, p_obj::%.5f, d_obj::%.5f, gap::%.2e\" % (it,", "u): \"\"\"Block soft-thresholding of vector x at level u.\"\"\" norm_x", "elapsed_times) if elapsed_times > tmax: break d_norm_theta = np.max( norm((X.T", "L, grp_size) R[:] = y - X @ w elif", "z - y) / L, alpha / L, grp_size) t_old", "def primal_grp(R, w, alpha, grp_size): return (0.5 * norm(R) **", "float, default=1000 Maximum time (in seconds) the algorithm is allowed", "% f_gap == 0: if algo == 'fista': R =", "grp_size = w.shape[0] // lc.shape[0] for g in groups: grp", "X.T @ R / L, alpha / L, grp_size) R[:]", "t_old = t_new t_new = (1. + np.sqrt(1 + 4", "if p_obj_acc < p_obj: w = w_acc R = R_acc", "% (it, p_obj, d_obj, gap)) gaps[it // f_gap] = gap" ]
[ "et. al, 2019. See https://arxiv.org/abs/1907.11932 and https://github.com/jind11/TextFooler. \"\"\" import numpy", "is a reimplementation of the search method from the paper:", "\"\"\" def __init__(self, wir_method=\"unk\"): self.wir_method = wir_method def _get_index_order(self, initial_text):", "max_similarity = similarity_score best_result = result return best_result return cur_result", "from textattack.search_methods import SearchMethod from textattack.shared.validators import ( transformation_consists_of_word_swaps_and_deletions, )", "result in leave_one_results]) elif self.wir_method == \"random\": index_order = np.arange(len_text)", "for idx in range(len_text): transformed_text_candidates = self.get_transformations( initial_text, original_text=initial_text, indices_to_modify=[idx],", "as np import torch from torch.nn.functional import softmax from textattack.goal_function_results", "= initial_result results = None while i < len(index_order) and", "candidates won't have a similarity score. In this # case,", "= np.array([result.score for result in leave_one_results]) elif self.wir_method == \"weighted-saliency\":", "self.get_goal_results(transformed_text_candidates) score_change = [result.score for result in swap_results] max_score_change =", "elif self.wir_method == \"weighted-saliency\": # first, compute word saliency leave_one_texts", "\"\"\" import numpy as np import torch from torch.nn.functional import", ") if not transformed_text_candidates: # no valid synonym substitutions for", "\"unk\": leave_one_texts = [ initial_text.replace_word_at_index(i, \"[UNK]\") for i in range(len_text)", "1 if len(transformed_text_candidates) == 0: continue results, search_over = self.get_goal_results(transformed_text_candidates)", "search method from the paper: Is BERT Really Robust? A", "index_scores = np.array([result.score for result in leave_one_results]) elif self.wir_method ==", "False else: raise ValueError(f\"Unsupported WIR method {self.wir_method}\") if self.wir_method !=", "original_text=initial_text, indices_to_modify=[idx], ) if not transformed_text_candidates: # no valid synonym", "initial_result results = None while i < len(index_order) and not", "self.get_transformations( initial_text, original_text=initial_text, indices_to_modify=[idx], ) if not transformed_text_candidates: # no", "to ``unk``, this is a reimplementation of the search method", "len(index_order) and not search_over: transformed_text_candidates = self.get_transformations( cur_result.attacked_text, original_text=initial_result.attacked_text, indices_to_modify=[index_order[i]],", "Jin et. al, 2019. See https://arxiv.org/abs/1907.11932 and https://github.com/jind11/TextFooler. \"\"\" import", "for i in range(len_text) ] leave_one_results, search_over = self.get_goal_results(leave_one_texts) saliency_scores", "= softmax( torch.Tensor(saliency_scores), dim=0 ).numpy() # compute the largest change", "i in range(len_text) ] leave_one_results, search_over = self.get_goal_results(leave_one_texts) saliency_scores =", "= (-index_scores).argsort() return index_order, search_over def _perform_search(self, initial_result): attacked_text =", "chooses from a list of possible perturbations in order of", "ValueError(f\"Unsupported WIR method {self.wir_method}\") if self.wir_method != \"random\": index_order =", "len(initial_text.words) if self.wir_method == \"unk\": leave_one_texts = [ initial_text.replace_word_at_index(i, \"[UNK]\")", "initial_result): attacked_text = initial_result.attacked_text # Sort words by order of", "a similarity score. In this # case, break and return", "max_similarity: max_similarity = similarity_score best_result = result return best_result return", "word delta_ps = [] for idx in range(len_text): transformed_text_candidates =", "indices by importance. Args: wir_method: method for ranking most important", "= results[0] else: continue # If we succeeded, return the", "= initial_result.attacked_text # Sort words by order of importance index_order,", "elif self.wir_method == \"random\": index_order = np.arange(len_text) np.random.shuffle(index_order) search_over =", "is limited to word swap and deletion transformations.\"\"\" return transformation_consists_of_word_swaps_and_deletions(transformation)", "result.attacked_text try: similarity_score = candidate.attack_attrs[\"similarity_score\"] except KeyError: # If the", "synonym substitutions for this word delta_ps.append(0.0) continue swap_results, _ =", "their importance, GreedyWordSwapWIR is limited to word swap and deletion", "score we can find by swapping each word delta_ps =", "= np.max(score_change) delta_ps.append(max_score_change) index_scores = softmax_saliency_scores * np.array(delta_ps) elif self.wir_method", "== \"unk\": leave_one_texts = [ initial_text.replace_word_at_index(i, \"[UNK]\") for i in", "transformation_consists_of_word_swaps_and_deletions, ) class GreedyWordSwapWIR(SearchMethod): \"\"\"An attack that greedily chooses from", "from the paper: Is BERT Really Robust? A Strong Baseline", "= result.attacked_text try: similarity_score = candidate.attack_attrs[\"similarity_score\"] except KeyError: # If", "method from the paper: Is BERT Really Robust? A Strong", "if not transformed_text_candidates: # no valid synonym substitutions for this", "import GoalFunctionResultStatus from textattack.search_methods import SearchMethod from textattack.shared.validators import (", "= False else: raise ValueError(f\"Unsupported WIR method {self.wir_method}\") if self.wir_method", "of index, after ranking indices by importance. Args: wir_method: method", "transformation): \"\"\"Since it ranks words by their importance, GreedyWordSwapWIR is", "i < len(index_order) and not search_over: transformed_text_candidates = self.get_transformations( cur_result.attacked_text,", "* np.array(delta_ps) elif self.wir_method == \"delete\": leave_one_texts = [ initial_text.delete_word_at_index(i)", "swapping each word delta_ps = [] for idx in range(len_text):", "index_order, search_over = self._get_index_order(attacked_text) i = 0 cur_result = initial_result", "word delta_ps.append(0.0) continue swap_results, _ = self.get_goal_results(transformed_text_candidates) score_change = [result.score", "cur_result = results[0] else: continue # If we succeeded, return", "by swapping each word delta_ps = [] for idx in", "WIR method is set to ``unk``, this is a reimplementation", "i in range(len_text) ] leave_one_results, search_over = self.get_goal_results(leave_one_texts) index_scores =", "GreedyWordSwapWIR(SearchMethod): \"\"\"An attack that greedily chooses from a list of", "for this word delta_ps.append(0.0) continue swap_results, _ = self.get_goal_results(transformed_text_candidates) score_change", "index_scores = softmax_saliency_scores * np.array(delta_ps) elif self.wir_method == \"delete\": leave_one_texts", "i = 0 cur_result = initial_result results = None while", "\"random\": index_order = (-index_scores).argsort() return index_order, search_over def _perform_search(self, initial_result):", "in descending order of importance.\"\"\" len_text = len(initial_text.words) if self.wir_method", "Use vectorwise operations max_similarity = -float(\"inf\") for result in results:", "the attack was run without any similarity metrics, # candidates", "def __init__(self, wir_method=\"unk\"): self.wir_method = wir_method def _get_index_order(self, initial_text): \"\"\"Returns", "return the index with best similarity. if cur_result.goal_status == GoalFunctionResultStatus.SUCCEEDED:", "textattack.shared.validators import ( transformation_consists_of_word_swaps_and_deletions, ) class GreedyWordSwapWIR(SearchMethod): \"\"\"An attack that", "Args: wir_method: method for ranking most important words \"\"\" def", "def check_transformation_compatibility(self, transformation): \"\"\"Since it ranks words by their importance,", "= [] for idx in range(len_text): transformed_text_candidates = self.get_transformations( initial_text,", "WIR method {self.wir_method}\") if self.wir_method != \"random\": index_order = (-index_scores).argsort()", "_get_index_order(self, initial_text): \"\"\"Returns word indices of ``initial_text`` in descending order", "set to ``unk``, this is a reimplementation of the search", "softmax_saliency_scores * np.array(delta_ps) elif self.wir_method == \"delete\": leave_one_texts = [", "Entailment by Jin et. al, 2019. See https://arxiv.org/abs/1907.11932 and https://github.com/jind11/TextFooler.", "= result return best_result return cur_result def check_transformation_compatibility(self, transformation): \"\"\"Since", "result in leave_one_results]) elif self.wir_method == \"weighted-saliency\": # first, compute", "= softmax_saliency_scores * np.array(delta_ps) elif self.wir_method == \"delete\": leave_one_texts =", "self.get_goal_results(leave_one_texts) saliency_scores = np.array([result.score for result in leave_one_results]) softmax_saliency_scores =", "operations max_similarity = -float(\"inf\") for result in results: if result.goal_status", "for Natural Language Attack on Text Classification and Entailment by", "[result.score for result in swap_results] max_score_change = np.max(score_change) delta_ps.append(max_score_change) index_scores", "== \"delete\": leave_one_texts = [ initial_text.delete_word_at_index(i) for i in range(len_text)", "initial_text, original_text=initial_text, indices_to_modify=[idx], ) if not transformed_text_candidates: # no valid", "# Sort words by order of importance index_order, search_over =", "delta_ps.append(0.0) continue swap_results, _ = self.get_goal_results(transformed_text_candidates) score_change = [result.score for", "reimplementation of the search method from the paper: Is BERT", "possible perturbations in order of index, after ranking indices by", "np.arange(len_text) np.random.shuffle(index_order) search_over = False else: raise ValueError(f\"Unsupported WIR method", "descending order of importance.\"\"\" len_text = len(initial_text.words) if self.wir_method ==", "= -float(\"inf\") for result in results: if result.goal_status != GoalFunctionResultStatus.SUCCEEDED:", "GoalFunctionResultStatus.SUCCEEDED: break candidate = result.attacked_text try: similarity_score = candidate.attack_attrs[\"similarity_score\"] except", "index with best similarity. if cur_result.goal_status == GoalFunctionResultStatus.SUCCEEDED: best_result =", "= self.get_goal_results(transformed_text_candidates) score_change = [result.score for result in swap_results] max_score_change", "\"weighted-saliency\": # first, compute word saliency leave_one_texts = [ initial_text.replace_word_at_index(i,", "each word delta_ps = [] for idx in range(len_text): transformed_text_candidates", "order of importance.\"\"\" len_text = len(initial_text.words) if self.wir_method == \"unk\":", "case, break and return the candidate that changed # the", "ranks words by their importance, GreedyWordSwapWIR is limited to word", "from textattack.shared.validators import ( transformation_consists_of_word_swaps_and_deletions, ) class GreedyWordSwapWIR(SearchMethod): \"\"\"An attack", "index_order, search_over def _perform_search(self, initial_result): attacked_text = initial_result.attacked_text # Sort", "softmax( torch.Tensor(saliency_scores), dim=0 ).numpy() # compute the largest change in", "] leave_one_results, search_over = self.get_goal_results(leave_one_texts) saliency_scores = np.array([result.score for result", "initial_text.replace_word_at_index(i, \"[UNK]\") for i in range(len_text) ] leave_one_results, search_over =", "len(transformed_text_candidates) == 0: continue results, search_over = self.get_goal_results(transformed_text_candidates) results =", "\"random\": index_order = np.arange(len_text) np.random.shuffle(index_order) search_over = False else: raise", "[ initial_text.replace_word_at_index(i, \"[UNK]\") for i in range(len_text) ] leave_one_results, search_over", "np.array([result.score for result in leave_one_results]) softmax_saliency_scores = softmax( torch.Tensor(saliency_scores), dim=0", "self.wir_method == \"random\": index_order = np.arange(len_text) np.random.shuffle(index_order) search_over = False", "to word swap and deletion transformations.\"\"\" return transformation_consists_of_word_swaps_and_deletions(transformation) def extra_repr_keys(self):", "best_result return cur_result def check_transformation_compatibility(self, transformation): \"\"\"Since it ranks words", "\"\"\"An attack that greedily chooses from a list of possible", "Text Classification and Entailment by Jin et. al, 2019. See", "= self.get_goal_results(transformed_text_candidates) results = sorted(results, key=lambda x: -x.score) # Skip", "word swap and deletion transformations.\"\"\" return transformation_consists_of_word_swaps_and_deletions(transformation) def extra_repr_keys(self): return", "similarity. if cur_result.goal_status == GoalFunctionResultStatus.SUCCEEDED: best_result = cur_result # @TODO:", "SearchMethod from textattack.shared.validators import ( transformation_consists_of_word_swaps_and_deletions, ) class GreedyWordSwapWIR(SearchMethod): \"\"\"An", "== \"random\": index_order = np.arange(len_text) np.random.shuffle(index_order) search_over = False else:", "leave_one_results]) elif self.wir_method == \"weighted-saliency\": # first, compute word saliency", "score. In this # case, break and return the candidate", "continue results, search_over = self.get_goal_results(transformed_text_candidates) results = sorted(results, key=lambda x:", "def _get_index_order(self, initial_text): \"\"\"Returns word indices of ``initial_text`` in descending", "similarity metrics, # candidates won't have a similarity score. In", "initial_text): \"\"\"Returns word indices of ``initial_text`` in descending order of", "Robust? A Strong Baseline for Natural Language Attack on Text", "compute word saliency leave_one_texts = [ initial_text.replace_word_at_index(i, \"[UNK]\") for i", "if results[0].score > cur_result.score: cur_result = results[0] else: continue #", "] leave_one_results, search_over = self.get_goal_results(leave_one_texts) index_scores = np.array([result.score for result", "best similarity. if cur_result.goal_status == GoalFunctionResultStatus.SUCCEEDED: best_result = cur_result #", "attack was run without any similarity metrics, # candidates won't", "import SearchMethod from textattack.shared.validators import ( transformation_consists_of_word_swaps_and_deletions, ) class GreedyWordSwapWIR(SearchMethod):", "order of index, after ranking indices by importance. Args: wir_method:", "results = None while i < len(index_order) and not search_over:", "from textattack.goal_function_results import GoalFunctionResultStatus from textattack.search_methods import SearchMethod from textattack.shared.validators", "\"delete\": leave_one_texts = [ initial_text.delete_word_at_index(i) for i in range(len_text) ]", "!= \"random\": index_order = (-index_scores).argsort() return index_order, search_over def _perform_search(self,", "by importance. Args: wir_method: method for ranking most important words", "swap and deletion transformations.\"\"\" return transformation_consists_of_word_swaps_and_deletions(transformation) def extra_repr_keys(self): return [\"wir_method\"]", "=================================================== When WIR method is set to ``unk``, this is", "index, after ranking indices by importance. Args: wir_method: method for", "limited to word swap and deletion transformations.\"\"\" return transformation_consists_of_word_swaps_and_deletions(transformation) def", "ranking indices by importance. Args: wir_method: method for ranking most", "in leave_one_results]) softmax_saliency_scores = softmax( torch.Tensor(saliency_scores), dim=0 ).numpy() # compute", "similarity_score > max_similarity: max_similarity = similarity_score best_result = result return", "import softmax from textattack.goal_function_results import GoalFunctionResultStatus from textattack.search_methods import SearchMethod", "change in score we can find by swapping each word", "# If we succeeded, return the index with best similarity.", "leave_one_results]) elif self.wir_method == \"random\": index_order = np.arange(len_text) np.random.shuffle(index_order) search_over", "metrics, # candidates won't have a similarity score. In this", "this is a reimplementation of the search method from the", "greedily chooses from a list of possible perturbations in order", "import numpy as np import torch from torch.nn.functional import softmax", "https://github.com/jind11/TextFooler. \"\"\" import numpy as np import torch from torch.nn.functional", "self.wir_method == \"weighted-saliency\": # first, compute word saliency leave_one_texts =", "# first, compute word saliency leave_one_texts = [ initial_text.replace_word_at_index(i, \"[UNK]\")", "with Word Importance Ranking =================================================== When WIR method is set", "succeeded, return the index with best similarity. if cur_result.goal_status ==", "A Strong Baseline for Natural Language Attack on Text Classification", "in leave_one_results]) elif self.wir_method == \"random\": index_order = np.arange(len_text) np.random.shuffle(index_order)", "was run without any similarity metrics, # candidates won't have", "candidate that changed # the original score the most. break", "Is BERT Really Robust? A Strong Baseline for Natural Language", "range(len_text) ] leave_one_results, search_over = self.get_goal_results(leave_one_texts) saliency_scores = np.array([result.score for", "on Text Classification and Entailment by Jin et. al, 2019.", "try: similarity_score = candidate.attack_attrs[\"similarity_score\"] except KeyError: # If the attack", "= len(initial_text.words) if self.wir_method == \"unk\": leave_one_texts = [ initial_text.replace_word_at_index(i,", "saliency leave_one_texts = [ initial_text.replace_word_at_index(i, \"[UNK]\") for i in range(len_text)", "vectorwise operations max_similarity = -float(\"inf\") for result in results: if", "importance index_order, search_over = self._get_index_order(attacked_text) i = 0 cur_result =", "= cur_result # @TODO: Use vectorwise operations max_similarity = -float(\"inf\")", "transformed_text_candidates: # no valid synonym substitutions for this word delta_ps.append(0.0)", "@TODO: Use vectorwise operations max_similarity = -float(\"inf\") for result in", "2019. See https://arxiv.org/abs/1907.11932 and https://github.com/jind11/TextFooler. \"\"\" import numpy as np", "most important words \"\"\" def __init__(self, wir_method=\"unk\"): self.wir_method = wir_method", "largest change in score we can find by swapping each", "== \"weighted-saliency\": # first, compute word saliency leave_one_texts = [", "index_order = np.arange(len_text) np.random.shuffle(index_order) search_over = False else: raise ValueError(f\"Unsupported", "dim=0 ).numpy() # compute the largest change in score we", "0: continue results, search_over = self.get_goal_results(transformed_text_candidates) results = sorted(results, key=lambda", "we succeeded, return the index with best similarity. if cur_result.goal_status", "result.goal_status != GoalFunctionResultStatus.SUCCEEDED: break candidate = result.attacked_text try: similarity_score =", "break candidate = result.attacked_text try: similarity_score = candidate.attack_attrs[\"similarity_score\"] except KeyError:", "BERT Really Robust? A Strong Baseline for Natural Language Attack", "except KeyError: # If the attack was run without any", "self.get_goal_results(leave_one_texts) index_scores = np.array([result.score for result in leave_one_results]) elif self.wir_method", "from torch.nn.functional import softmax from textattack.goal_function_results import GoalFunctionResultStatus from textattack.search_methods", "len_text = len(initial_text.words) if self.wir_method == \"unk\": leave_one_texts = [", ").numpy() # compute the largest change in score we can", "= self.get_goal_results(leave_one_texts) index_scores = np.array([result.score for result in leave_one_results]) elif", "the search method from the paper: Is BERT Really Robust?", "score_change = [result.score for result in swap_results] max_score_change = np.max(score_change)", "= self.get_goal_results(leave_one_texts) saliency_scores = np.array([result.score for result in leave_one_results]) softmax_saliency_scores", "compute the largest change in score we can find by", "class GreedyWordSwapWIR(SearchMethod): \"\"\"An attack that greedily chooses from a list", "in leave_one_results]) elif self.wir_method == \"weighted-saliency\": # first, compute word", "leave_one_results, search_over = self.get_goal_results(leave_one_texts) saliency_scores = np.array([result.score for result in", "best_result = cur_result # @TODO: Use vectorwise operations max_similarity =", "with best similarity. if cur_result.goal_status == GoalFunctionResultStatus.SUCCEEDED: best_result = cur_result", "words \"\"\" def __init__(self, wir_method=\"unk\"): self.wir_method = wir_method def _get_index_order(self,", "for result in leave_one_results]) elif self.wir_method == \"random\": index_order =", "cur_result = initial_result results = None while i < len(index_order)", "x: -x.score) # Skip swaps which don't improve the score", "(-index_scores).argsort() return index_order, search_over def _perform_search(self, initial_result): attacked_text = initial_result.attacked_text", "importance.\"\"\" len_text = len(initial_text.words) if self.wir_method == \"unk\": leave_one_texts =", "else: raise ValueError(f\"Unsupported WIR method {self.wir_method}\") if self.wir_method != \"random\":", "textattack.search_methods import SearchMethod from textattack.shared.validators import ( transformation_consists_of_word_swaps_and_deletions, ) class", "saliency_scores = np.array([result.score for result in leave_one_results]) softmax_saliency_scores = softmax(", "wir_method: method for ranking most important words \"\"\" def __init__(self,", "changed # the original score the most. break if similarity_score", "self._get_index_order(attacked_text) i = 0 cur_result = initial_result results = None", "in swap_results] max_score_change = np.max(score_change) delta_ps.append(max_score_change) index_scores = softmax_saliency_scores *", "== GoalFunctionResultStatus.SUCCEEDED: best_result = cur_result # @TODO: Use vectorwise operations", "Strong Baseline for Natural Language Attack on Text Classification and", "of possible perturbations in order of index, after ranking indices", "by Jin et. al, 2019. See https://arxiv.org/abs/1907.11932 and https://github.com/jind11/TextFooler. \"\"\"", "Baseline for Natural Language Attack on Text Classification and Entailment", "# case, break and return the candidate that changed #", "in range(len_text) ] leave_one_results, search_over = self.get_goal_results(leave_one_texts) saliency_scores = np.array([result.score", "swap_results] max_score_change = np.max(score_change) delta_ps.append(max_score_change) index_scores = softmax_saliency_scores * np.array(delta_ps)", "KeyError: # If the attack was run without any similarity", "+= 1 if len(transformed_text_candidates) == 0: continue results, search_over =", "\"\"\"Since it ranks words by their importance, GreedyWordSwapWIR is limited", "result in swap_results] max_score_change = np.max(score_change) delta_ps.append(max_score_change) index_scores = softmax_saliency_scores", "== 0: continue results, search_over = self.get_goal_results(transformed_text_candidates) results = sorted(results,", "we can find by swapping each word delta_ps = []", "a list of possible perturbations in order of index, after", "self.get_transformations( cur_result.attacked_text, original_text=initial_result.attacked_text, indices_to_modify=[index_order[i]], ) i += 1 if len(transformed_text_candidates)", "original_text=initial_result.attacked_text, indices_to_modify=[index_order[i]], ) i += 1 if len(transformed_text_candidates) == 0:", "results[0] else: continue # If we succeeded, return the index", "( transformation_consists_of_word_swaps_and_deletions, ) class GreedyWordSwapWIR(SearchMethod): \"\"\"An attack that greedily chooses", "attacked_text = initial_result.attacked_text # Sort words by order of importance", "= self.get_transformations( cur_result.attacked_text, original_text=initial_result.attacked_text, indices_to_modify=[index_order[i]], ) i += 1 if", "elif self.wir_method == \"delete\": leave_one_texts = [ initial_text.delete_word_at_index(i) for i", "swaps which don't improve the score if results[0].score > cur_result.score:", "Skip swaps which don't improve the score if results[0].score >", "most. break if similarity_score > max_similarity: max_similarity = similarity_score best_result", "the score if results[0].score > cur_result.score: cur_result = results[0] else:", "that changed # the original score the most. break if", "Language Attack on Text Classification and Entailment by Jin et.", "= self._get_index_order(attacked_text) i = 0 cur_result = initial_result results =", "Swap with Word Importance Ranking =================================================== When WIR method is", "words by order of importance index_order, search_over = self._get_index_order(attacked_text) i", "self.get_goal_results(transformed_text_candidates) results = sorted(results, key=lambda x: -x.score) # Skip swaps", "and return the candidate that changed # the original score", "_ = self.get_goal_results(transformed_text_candidates) score_change = [result.score for result in swap_results]", "sorted(results, key=lambda x: -x.score) # Skip swaps which don't improve", "if len(transformed_text_candidates) == 0: continue results, search_over = self.get_goal_results(transformed_text_candidates) results", "-x.score) # Skip swaps which don't improve the score if", "softmax_saliency_scores = softmax( torch.Tensor(saliency_scores), dim=0 ).numpy() # compute the largest", "if self.wir_method != \"random\": index_order = (-index_scores).argsort() return index_order, search_over", "have a similarity score. In this # case, break and", "self.wir_method == \"unk\": leave_one_texts = [ initial_text.replace_word_at_index(i, \"[UNK]\") for i", "improve the score if results[0].score > cur_result.score: cur_result = results[0]", "# If the attack was run without any similarity metrics,", "# the original score the most. break if similarity_score >", "self.wir_method == \"delete\": leave_one_texts = [ initial_text.delete_word_at_index(i) for i in", "break if similarity_score > max_similarity: max_similarity = similarity_score best_result =", "in results: if result.goal_status != GoalFunctionResultStatus.SUCCEEDED: break candidate = result.attacked_text", "candidate.attack_attrs[\"similarity_score\"] except KeyError: # If the attack was run without", "that greedily chooses from a list of possible perturbations in", "np.array(delta_ps) elif self.wir_method == \"delete\": leave_one_texts = [ initial_text.delete_word_at_index(i) for", "perturbations in order of index, after ranking indices by importance.", "paper: Is BERT Really Robust? A Strong Baseline for Natural", "and https://github.com/jind11/TextFooler. \"\"\" import numpy as np import torch from", "import torch from torch.nn.functional import softmax from textattack.goal_function_results import GoalFunctionResultStatus", "without any similarity metrics, # candidates won't have a similarity", "If we succeeded, return the index with best similarity. if", "al, 2019. See https://arxiv.org/abs/1907.11932 and https://github.com/jind11/TextFooler. \"\"\" import numpy as", "check_transformation_compatibility(self, transformation): \"\"\"Since it ranks words by their importance, GreedyWordSwapWIR", "by their importance, GreedyWordSwapWIR is limited to word swap and", "result in results: if result.goal_status != GoalFunctionResultStatus.SUCCEEDED: break candidate =", "0 cur_result = initial_result results = None while i <", "_perform_search(self, initial_result): attacked_text = initial_result.attacked_text # Sort words by order", "results[0].score > cur_result.score: cur_result = results[0] else: continue # If", "# candidates won't have a similarity score. In this #", "i += 1 if len(transformed_text_candidates) == 0: continue results, search_over", "which don't improve the score if results[0].score > cur_result.score: cur_result", "= self.get_transformations( initial_text, original_text=initial_text, indices_to_modify=[idx], ) if not transformed_text_candidates: #", "max_similarity = -float(\"inf\") for result in results: if result.goal_status !=", "Ranking =================================================== When WIR method is set to ``unk``, this", "idx in range(len_text): transformed_text_candidates = self.get_transformations( initial_text, original_text=initial_text, indices_to_modify=[idx], )", "similarity_score = candidate.attack_attrs[\"similarity_score\"] except KeyError: # If the attack was", "if similarity_score > max_similarity: max_similarity = similarity_score best_result = result", "for result in swap_results] max_score_change = np.max(score_change) delta_ps.append(max_score_change) index_scores =", "Greedy Word Swap with Word Importance Ranking =================================================== When WIR", "transformed_text_candidates = self.get_transformations( cur_result.attacked_text, original_text=initial_result.attacked_text, indices_to_modify=[index_order[i]], ) i += 1", "the paper: Is BERT Really Robust? A Strong Baseline for", "and not search_over: transformed_text_candidates = self.get_transformations( cur_result.attacked_text, original_text=initial_result.attacked_text, indices_to_modify=[index_order[i]], )", "= wir_method def _get_index_order(self, initial_text): \"\"\"Returns word indices of ``initial_text``", "GoalFunctionResultStatus from textattack.search_methods import SearchMethod from textattack.shared.validators import ( transformation_consists_of_word_swaps_and_deletions,", "words by their importance, GreedyWordSwapWIR is limited to word swap", "find by swapping each word delta_ps = [] for idx", "= candidate.attack_attrs[\"similarity_score\"] except KeyError: # If the attack was run", "= [result.score for result in swap_results] max_score_change = np.max(score_change) delta_ps.append(max_score_change)", "index_order = (-index_scores).argsort() return index_order, search_over def _perform_search(self, initial_result): attacked_text", "from a list of possible perturbations in order of index,", "of importance index_order, search_over = self._get_index_order(attacked_text) i = 0 cur_result", "torch from torch.nn.functional import softmax from textattack.goal_function_results import GoalFunctionResultStatus from", "leave_one_results]) softmax_saliency_scores = softmax( torch.Tensor(saliency_scores), dim=0 ).numpy() # compute the", "the candidate that changed # the original score the most.", "``initial_text`` in descending order of importance.\"\"\" len_text = len(initial_text.words) if", "\"[UNK]\") for i in range(len_text) ] leave_one_results, search_over = self.get_goal_results(leave_one_texts)", "self.wir_method = wir_method def _get_index_order(self, initial_text): \"\"\"Returns word indices of", "of ``initial_text`` in descending order of importance.\"\"\" len_text = len(initial_text.words)", "in score we can find by swapping each word delta_ps", "return index_order, search_over def _perform_search(self, initial_result): attacked_text = initial_result.attacked_text #", "None while i < len(index_order) and not search_over: transformed_text_candidates =", "wir_method def _get_index_order(self, initial_text): \"\"\"Returns word indices of ``initial_text`` in", "[ initial_text.delete_word_at_index(i) for i in range(len_text) ] leave_one_results, search_over =", "# compute the largest change in score we can find", "max_score_change = np.max(score_change) delta_ps.append(max_score_change) index_scores = softmax_saliency_scores * np.array(delta_ps) elif", "the original score the most. break if similarity_score > max_similarity:", "self.wir_method != \"random\": index_order = (-index_scores).argsort() return index_order, search_over def", "initial_result.attacked_text # Sort words by order of importance index_order, search_over", "indices_to_modify=[idx], ) if not transformed_text_candidates: # no valid synonym substitutions", "swap_results, _ = self.get_goal_results(transformed_text_candidates) score_change = [result.score for result in", "# no valid synonym substitutions for this word delta_ps.append(0.0) continue", "< len(index_order) and not search_over: transformed_text_candidates = self.get_transformations( cur_result.attacked_text, original_text=initial_result.attacked_text,", "torch.nn.functional import softmax from textattack.goal_function_results import GoalFunctionResultStatus from textattack.search_methods import", "If the attack was run without any similarity metrics, #", "after ranking indices by importance. Args: wir_method: method for ranking", "cur_result.score: cur_result = results[0] else: continue # If we succeeded,", "cur_result def check_transformation_compatibility(self, transformation): \"\"\"Since it ranks words by their", "= similarity_score best_result = result return best_result return cur_result def", "> max_similarity: max_similarity = similarity_score best_result = result return best_result", "= np.array([result.score for result in leave_one_results]) softmax_saliency_scores = softmax( torch.Tensor(saliency_scores),", "not search_over: transformed_text_candidates = self.get_transformations( cur_result.attacked_text, original_text=initial_result.attacked_text, indices_to_modify=[index_order[i]], ) i", "= [ initial_text.delete_word_at_index(i) for i in range(len_text) ] leave_one_results, search_over", "return best_result return cur_result def check_transformation_compatibility(self, transformation): \"\"\"Since it ranks", "method {self.wir_method}\") if self.wir_method != \"random\": index_order = (-index_scores).argsort() return", "for ranking most important words \"\"\" def __init__(self, wir_method=\"unk\"): self.wir_method", "and Entailment by Jin et. al, 2019. See https://arxiv.org/abs/1907.11932 and", "can find by swapping each word delta_ps = [] for", "in order of index, after ranking indices by importance. Args:", "any similarity metrics, # candidates won't have a similarity score.", "substitutions for this word delta_ps.append(0.0) continue swap_results, _ = self.get_goal_results(transformed_text_candidates)", "this word delta_ps.append(0.0) continue swap_results, _ = self.get_goal_results(transformed_text_candidates) score_change =", "In this # case, break and return the candidate that", "numpy as np import torch from torch.nn.functional import softmax from", "import ( transformation_consists_of_word_swaps_and_deletions, ) class GreedyWordSwapWIR(SearchMethod): \"\"\"An attack that greedily", "{self.wir_method}\") if self.wir_method != \"random\": index_order = (-index_scores).argsort() return index_order,", "run without any similarity metrics, # candidates won't have a", "is set to ``unk``, this is a reimplementation of the", "similarity score. In this # case, break and return the", "= sorted(results, key=lambda x: -x.score) # Skip swaps which don't", "similarity_score best_result = result return best_result return cur_result def check_transformation_compatibility(self,", "continue swap_results, _ = self.get_goal_results(transformed_text_candidates) score_change = [result.score for result", "search_over: transformed_text_candidates = self.get_transformations( cur_result.attacked_text, original_text=initial_result.attacked_text, indices_to_modify=[index_order[i]], ) i +=", "importance. Args: wir_method: method for ranking most important words \"\"\"", "in range(len_text) ] leave_one_results, search_over = self.get_goal_results(leave_one_texts) index_scores = np.array([result.score", "result in leave_one_results]) softmax_saliency_scores = softmax( torch.Tensor(saliency_scores), dim=0 ).numpy() #", "np.array([result.score for result in leave_one_results]) elif self.wir_method == \"random\": index_order", "= [ initial_text.replace_word_at_index(i, \"[UNK]\") for i in range(len_text) ] leave_one_results,", "search_over = self.get_goal_results(transformed_text_candidates) results = sorted(results, key=lambda x: -x.score) #", "\"\"\"Returns word indices of ``initial_text`` in descending order of importance.\"\"\"", "for i in range(len_text) ] leave_one_results, search_over = self.get_goal_results(leave_one_texts) index_scores", "first, compute word saliency leave_one_texts = [ initial_text.replace_word_at_index(i, \"[UNK]\") for", "important words \"\"\" def __init__(self, wir_method=\"unk\"): self.wir_method = wir_method def", "for result in leave_one_results]) elif self.wir_method == \"weighted-saliency\": # first,", "Classification and Entailment by Jin et. al, 2019. See https://arxiv.org/abs/1907.11932", "the index with best similarity. if cur_result.goal_status == GoalFunctionResultStatus.SUCCEEDED: best_result", "candidate = result.attacked_text try: similarity_score = candidate.attack_attrs[\"similarity_score\"] except KeyError: #", "else: continue # If we succeeded, return the index with", "leave_one_texts = [ initial_text.delete_word_at_index(i) for i in range(len_text) ] leave_one_results,", "np import torch from torch.nn.functional import softmax from textattack.goal_function_results import", "textattack.goal_function_results import GoalFunctionResultStatus from textattack.search_methods import SearchMethod from textattack.shared.validators import", "transformed_text_candidates = self.get_transformations( initial_text, original_text=initial_text, indices_to_modify=[idx], ) if not transformed_text_candidates:", "GoalFunctionResultStatus.SUCCEEDED: best_result = cur_result # @TODO: Use vectorwise operations max_similarity", "results, search_over = self.get_goal_results(transformed_text_candidates) results = sorted(results, key=lambda x: -x.score)", "np.array([result.score for result in leave_one_results]) elif self.wir_method == \"weighted-saliency\": #", "np.max(score_change) delta_ps.append(max_score_change) index_scores = softmax_saliency_scores * np.array(delta_ps) elif self.wir_method ==", "if self.wir_method == \"unk\": leave_one_texts = [ initial_text.replace_word_at_index(i, \"[UNK]\") for", "results = sorted(results, key=lambda x: -x.score) # Skip swaps which", "ranking most important words \"\"\" def __init__(self, wir_method=\"unk\"): self.wir_method =", "a reimplementation of the search method from the paper: Is", "raise ValueError(f\"Unsupported WIR method {self.wir_method}\") if self.wir_method != \"random\": index_order", "continue # If we succeeded, return the index with best", "= 0 cur_result = initial_result results = None while i", "method for ranking most important words \"\"\" def __init__(self, wir_method=\"unk\"):", "# @TODO: Use vectorwise operations max_similarity = -float(\"inf\") for result", "of importance.\"\"\" len_text = len(initial_text.words) if self.wir_method == \"unk\": leave_one_texts", "leave_one_results, search_over = self.get_goal_results(leave_one_texts) index_scores = np.array([result.score for result in", "https://arxiv.org/abs/1907.11932 and https://github.com/jind11/TextFooler. \"\"\" import numpy as np import torch", "result return best_result return cur_result def check_transformation_compatibility(self, transformation): \"\"\"Since it", "results: if result.goal_status != GoalFunctionResultStatus.SUCCEEDED: break candidate = result.attacked_text try:", "search_over = False else: raise ValueError(f\"Unsupported WIR method {self.wir_method}\") if", ") i += 1 if len(transformed_text_candidates) == 0: continue results,", "search_over = self.get_goal_results(leave_one_texts) index_scores = np.array([result.score for result in leave_one_results])", "for result in leave_one_results]) softmax_saliency_scores = softmax( torch.Tensor(saliency_scores), dim=0 ).numpy()", "``unk``, this is a reimplementation of the search method from", "word indices of ``initial_text`` in descending order of importance.\"\"\" len_text", "softmax from textattack.goal_function_results import GoalFunctionResultStatus from textattack.search_methods import SearchMethod from", "!= GoalFunctionResultStatus.SUCCEEDED: break candidate = result.attacked_text try: similarity_score = candidate.attack_attrs[\"similarity_score\"]", "no valid synonym substitutions for this word delta_ps.append(0.0) continue swap_results,", "Attack on Text Classification and Entailment by Jin et. al,", "best_result = result return best_result return cur_result def check_transformation_compatibility(self, transformation):", "order of importance index_order, search_over = self._get_index_order(attacked_text) i = 0", "break and return the candidate that changed # the original", "GreedyWordSwapWIR is limited to word swap and deletion transformations.\"\"\" return", "initial_text.delete_word_at_index(i) for i in range(len_text) ] leave_one_results, search_over = self.get_goal_results(leave_one_texts)", "return the candidate that changed # the original score the", "list of possible perturbations in order of index, after ranking", "if result.goal_status != GoalFunctionResultStatus.SUCCEEDED: break candidate = result.attacked_text try: similarity_score", "= np.arange(len_text) np.random.shuffle(index_order) search_over = False else: raise ValueError(f\"Unsupported WIR", "> cur_result.score: cur_result = results[0] else: continue # If we", "the most. break if similarity_score > max_similarity: max_similarity = similarity_score", "while i < len(index_order) and not search_over: transformed_text_candidates = self.get_transformations(", "method is set to ``unk``, this is a reimplementation of", "for result in results: if result.goal_status != GoalFunctionResultStatus.SUCCEEDED: break candidate", "delta_ps.append(max_score_change) index_scores = softmax_saliency_scores * np.array(delta_ps) elif self.wir_method == \"delete\":", "torch.Tensor(saliency_scores), dim=0 ).numpy() # compute the largest change in score", "search_over = self._get_index_order(attacked_text) i = 0 cur_result = initial_result results", "by order of importance index_order, search_over = self._get_index_order(attacked_text) i =", "[] for idx in range(len_text): transformed_text_candidates = self.get_transformations( initial_text, original_text=initial_text,", "if cur_result.goal_status == GoalFunctionResultStatus.SUCCEEDED: best_result = cur_result # @TODO: Use", "Really Robust? A Strong Baseline for Natural Language Attack on", "search_over def _perform_search(self, initial_result): attacked_text = initial_result.attacked_text # Sort words", "# Skip swaps which don't improve the score if results[0].score", "return cur_result def check_transformation_compatibility(self, transformation): \"\"\"Since it ranks words by", "it ranks words by their importance, GreedyWordSwapWIR is limited to", "attack that greedily chooses from a list of possible perturbations", "cur_result.attacked_text, original_text=initial_result.attacked_text, indices_to_modify=[index_order[i]], ) i += 1 if len(transformed_text_candidates) ==", "in range(len_text): transformed_text_candidates = self.get_transformations( initial_text, original_text=initial_text, indices_to_modify=[idx], ) if", "wir_method=\"unk\"): self.wir_method = wir_method def _get_index_order(self, initial_text): \"\"\"Returns word indices", "= None while i < len(index_order) and not search_over: transformed_text_candidates", "cur_result # @TODO: Use vectorwise operations max_similarity = -float(\"inf\") for", "score the most. break if similarity_score > max_similarity: max_similarity =", "See https://arxiv.org/abs/1907.11932 and https://github.com/jind11/TextFooler. \"\"\" import numpy as np import", "the largest change in score we can find by swapping", "don't improve the score if results[0].score > cur_result.score: cur_result =", "word saliency leave_one_texts = [ initial_text.replace_word_at_index(i, \"[UNK]\") for i in", "score if results[0].score > cur_result.score: cur_result = results[0] else: continue", "key=lambda x: -x.score) # Skip swaps which don't improve the", "range(len_text) ] leave_one_results, search_over = self.get_goal_results(leave_one_texts) index_scores = np.array([result.score for", "__init__(self, wir_method=\"unk\"): self.wir_method = wir_method def _get_index_order(self, initial_text): \"\"\"Returns word", "cur_result.goal_status == GoalFunctionResultStatus.SUCCEEDED: best_result = cur_result # @TODO: Use vectorwise", "range(len_text): transformed_text_candidates = self.get_transformations( initial_text, original_text=initial_text, indices_to_modify=[idx], ) if not", "Importance Ranking =================================================== When WIR method is set to ``unk``,", "valid synonym substitutions for this word delta_ps.append(0.0) continue swap_results, _", "won't have a similarity score. In this # case, break", "indices_to_modify=[index_order[i]], ) i += 1 if len(transformed_text_candidates) == 0: continue", "indices of ``initial_text`` in descending order of importance.\"\"\" len_text =", "of the search method from the paper: Is BERT Really", "this # case, break and return the candidate that changed", "Word Importance Ranking =================================================== When WIR method is set to", "def _perform_search(self, initial_result): attacked_text = initial_result.attacked_text # Sort words by", "not transformed_text_candidates: # no valid synonym substitutions for this word", "leave_one_texts = [ initial_text.replace_word_at_index(i, \"[UNK]\") for i in range(len_text) ]", ") class GreedyWordSwapWIR(SearchMethod): \"\"\"An attack that greedily chooses from a", "When WIR method is set to ``unk``, this is a", "search_over = self.get_goal_results(leave_one_texts) saliency_scores = np.array([result.score for result in leave_one_results])", "Sort words by order of importance index_order, search_over = self._get_index_order(attacked_text)", "-float(\"inf\") for result in results: if result.goal_status != GoalFunctionResultStatus.SUCCEEDED: break", "delta_ps = [] for idx in range(len_text): transformed_text_candidates = self.get_transformations(", "= np.array([result.score for result in leave_one_results]) elif self.wir_method == \"random\":", "\"\"\" Greedy Word Swap with Word Importance Ranking =================================================== When", "Natural Language Attack on Text Classification and Entailment by Jin", "np.random.shuffle(index_order) search_over = False else: raise ValueError(f\"Unsupported WIR method {self.wir_method}\")", "original score the most. break if similarity_score > max_similarity: max_similarity", "Word Swap with Word Importance Ranking =================================================== When WIR method", "importance, GreedyWordSwapWIR is limited to word swap and deletion transformations.\"\"\"" ]
[ "on a given endpoint. :param endpoint: :param new_cert: :return: \"\"\"", "that certificate is available for rotation endpoint.source.plugin.update_endpoint(endpoint, new_cert) endpoint.certificate =", "rotate_certificate(endpoint, new_cert): \"\"\" Rotates a certificate on a given endpoint.", "certificate on a given endpoint. :param endpoint: :param new_cert: :return:", "def rotate_certificate(endpoint, new_cert): \"\"\" Rotates a certificate on a given", "given endpoint. :param endpoint: :param new_cert: :return: \"\"\" # ensure", "lemur import database def rotate_certificate(endpoint, new_cert): \"\"\" Rotates a certificate", "is available for rotation endpoint.source.plugin.update_endpoint(endpoint, new_cert) endpoint.certificate = new_cert database.update(endpoint)", "Rotates a certificate on a given endpoint. :param endpoint: :param", "database def rotate_certificate(endpoint, new_cert): \"\"\" Rotates a certificate on a", ":param endpoint: :param new_cert: :return: \"\"\" # ensure that certificate", ":param new_cert: :return: \"\"\" # ensure that certificate is available", "new_cert): \"\"\" Rotates a certificate on a given endpoint. :param", "\"\"\" Rotates a certificate on a given endpoint. :param endpoint:", ":return: \"\"\" # ensure that certificate is available for rotation", "a certificate on a given endpoint. :param endpoint: :param new_cert:", "endpoint. :param endpoint: :param new_cert: :return: \"\"\" # ensure that", "new_cert: :return: \"\"\" # ensure that certificate is available for", "ensure that certificate is available for rotation endpoint.source.plugin.update_endpoint(endpoint, new_cert) endpoint.certificate", "import database def rotate_certificate(endpoint, new_cert): \"\"\" Rotates a certificate on", "from lemur import database def rotate_certificate(endpoint, new_cert): \"\"\" Rotates a", "# ensure that certificate is available for rotation endpoint.source.plugin.update_endpoint(endpoint, new_cert)", "certificate is available for rotation endpoint.source.plugin.update_endpoint(endpoint, new_cert) endpoint.certificate = new_cert", "a given endpoint. :param endpoint: :param new_cert: :return: \"\"\" #", "endpoint: :param new_cert: :return: \"\"\" # ensure that certificate is", "\"\"\" # ensure that certificate is available for rotation endpoint.source.plugin.update_endpoint(endpoint," ]
[ "Copyright Luna Technology 2015 # <NAME> <<EMAIL>> from __future__ import", "import os from celery import Celery # Set the default", "Technology 2015 # <NAME> <<EMAIL>> from __future__ import absolute_import import", "from celery import Celery # Set the default Django settings", "settings from celery.signals import setup_logging @setup_logging.connect def configure_logging(sender=None, **kwargs): import", "**kwargs): import logging import logging.config logging.config.dictConfig(settings.LOGGING) app = Celery('pype') app.config_from_object('django.conf:settings')", "logging.config logging.config.dictConfig(settings.LOGGING) app = Celery('pype') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def", "# Copyright Luna Technology 2015 # <NAME> <<EMAIL>> from __future__", "os from celery import Celery # Set the default Django", "the default Django settings module for the 'celery' program os.environ.setdefault('DJANGO_SETTINGS_MODULE',", "Django settings module for the 'celery' program os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pype.settings') from", "django.conf import settings from celery.signals import setup_logging @setup_logging.connect def configure_logging(sender=None,", "import logging import logging.config logging.config.dictConfig(settings.LOGGING) app = Celery('pype') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda:", "setup_logging @setup_logging.connect def configure_logging(sender=None, **kwargs): import logging import logging.config logging.config.dictConfig(settings.LOGGING)", "absolute_import import os from celery import Celery # Set the", "app = Celery('pype') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request:", "from celery.signals import setup_logging @setup_logging.connect def configure_logging(sender=None, **kwargs): import logging", "@setup_logging.connect def configure_logging(sender=None, **kwargs): import logging import logging.config logging.config.dictConfig(settings.LOGGING) app", "celery import Celery # Set the default Django settings module", "import settings from celery.signals import setup_logging @setup_logging.connect def configure_logging(sender=None, **kwargs):", "import logging.config logging.config.dictConfig(settings.LOGGING) app = Celery('pype') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True)", "module for the 'celery' program os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pype.settings') from django.conf import", "__future__ import absolute_import import os from celery import Celery #", "Set the default Django settings module for the 'celery' program", "utf-8 # Copyright Luna Technology 2015 # <NAME> <<EMAIL>> from", "Celery # Set the default Django settings module for the", "'pype.settings') from django.conf import settings from celery.signals import setup_logging @setup_logging.connect", "logging.config.dictConfig(settings.LOGGING) app = Celery('pype') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self):", "program os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pype.settings') from django.conf import settings from celery.signals import", "# coding: utf-8 # Copyright Luna Technology 2015 # <NAME>", "# Set the default Django settings module for the 'celery'", "Luna Technology 2015 # <NAME> <<EMAIL>> from __future__ import absolute_import", "from __future__ import absolute_import import os from celery import Celery", "celery.signals import setup_logging @setup_logging.connect def configure_logging(sender=None, **kwargs): import logging import", "os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pype.settings') from django.conf import settings from celery.signals import setup_logging", "from django.conf import settings from celery.signals import setup_logging @setup_logging.connect def", "logging import logging.config logging.config.dictConfig(settings.LOGGING) app = Celery('pype') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)", "import absolute_import import os from celery import Celery # Set", "coding: utf-8 # Copyright Luna Technology 2015 # <NAME> <<EMAIL>>", "default Django settings module for the 'celery' program os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pype.settings')", "settings module for the 'celery' program os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pype.settings') from django.conf", "<<EMAIL>> from __future__ import absolute_import import os from celery import", "def configure_logging(sender=None, **kwargs): import logging import logging.config logging.config.dictConfig(settings.LOGGING) app =", "import setup_logging @setup_logging.connect def configure_logging(sender=None, **kwargs): import logging import logging.config", "<NAME> <<EMAIL>> from __future__ import absolute_import import os from celery", "= Celery('pype') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))", "import Celery # Set the default Django settings module for", "the 'celery' program os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pype.settings') from django.conf import settings from", "2015 # <NAME> <<EMAIL>> from __future__ import absolute_import import os", "# <NAME> <<EMAIL>> from __future__ import absolute_import import os from", "'celery' program os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pype.settings') from django.conf import settings from celery.signals", "for the 'celery' program os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pype.settings') from django.conf import settings", "configure_logging(sender=None, **kwargs): import logging import logging.config logging.config.dictConfig(settings.LOGGING) app = Celery('pype')" ]
[ "# 解析出parse result file parse_result_dir = 'parse_result' parse_result_dir = os.path.join(train_dir,", "KnowledgeBase() parser = sParser(KB) with open(pos_tags_file_path, 'w') as pos_tags_file: #", "% 5000 == 0: print('parsed %s sentence' % count) text", "file parse_result_dir = 'parse_result' parse_result_dir = os.path.join(train_dir, parse_result_dir) if not", "os.path.dirname(this_path) # print(par_path) if par_path == this_path: break else: this_path", "# print(par_path) if par_path == this_path: break else: this_path =", "KB = KnowledgeBase() parser = sParser(KB) with open(pos_tags_file_path, 'w') as", "== 0: print('parsed %s sentence' % count) text = line.strip()", "break par_path = os.path.dirname(this_path) # print(par_path) if par_path == this_path:", "this_file_path while this_path: if os.path.exists(os.path.join(this_path, 'sosweety_root_anchor.py')): root_path = this_path break", "0: print('parsed %s sentence' % count) text = line.strip() try:", "= os.path.split(os.path.realpath(__file__))[0] this_path = this_file_path root_path = this_file_path while this_path:", "count) text = line.strip() try: ss_pos_tags = parser.text2ss_pos_tags(text) for pos_tags", "sys import json # 获取当前路径, 通过anchor文件获取项目root路径 this_file_path = os.path.split(os.path.realpath(__file__))[0] this_path", "from modules.sParser.sParser import sParser from modules.knowledgebase.kb import KnowledgeBase train_dir =", "os.makedirs(train_dir) # 解析出parse result file parse_result_dir = 'parse_result' parse_result_dir =", "= sParser(KB) with open(pos_tags_file_path, 'w') as pos_tags_file: # 打开语料文件 file_path", "= os.path.join(root_path, file_path) file = open(file_path) line = file.readline() count", "<reponame>ss433s/sosweety<gh_stars>0 import os, sys import json # 获取当前路径, 通过anchor文件获取项目root路径 this_file_path", "pos_tags_file_name = 'pos_tags_file' pos_tags_file_path = os.path.join(parse_result_dir, pos_tags_file_name) KB = KnowledgeBase()", "open(pos_tags_file_path, 'w') as pos_tags_file: # 打开语料文件 file_path = 'data/corpus/zh_wiki/wiki_test' file_path", "file.readline() count = 0 while line: count += 1 if", "# 获取当前路径, 通过anchor文件获取项目root路径 this_file_path = os.path.split(os.path.realpath(__file__))[0] this_path = this_file_path root_path", "file_path) file = open(file_path) line = file.readline() count = 0", "print('parsed %s sentence' % count) text = line.strip() try: ss_pos_tags", "= parser.text2ss_pos_tags(text) for pos_tags in ss_pos_tags: pos_tags_file.write(json.dumps(pos_tags, ensure_ascii=False) + '\\n')", "os.path.join(root_path, file_path) file = open(file_path) line = file.readline() count =", "line: count += 1 if count % 5000 == 0:", "count += 1 if count % 5000 == 0: print('parsed", "ss_pos_tags: pos_tags_file.write(json.dumps(pos_tags, ensure_ascii=False) + '\\n') except Exception: print('line %s decode", "= this_file_path root_path = this_file_path while this_path: if os.path.exists(os.path.join(this_path, 'sosweety_root_anchor.py')):", "pos_tags_file.write(json.dumps(pos_tags, ensure_ascii=False) + '\\n') except Exception: print('line %s decode error'", "parse_result_dir = 'parse_result' parse_result_dir = os.path.join(train_dir, parse_result_dir) if not os.path.exists(parse_result_dir):", "= os.path.join(root_path, train_dir) if not os.path.exists(train_dir): os.makedirs(train_dir) # 解析出parse result", "'sosweety_root_anchor.py')): root_path = this_path break par_path = os.path.dirname(this_path) # print(par_path)", "os, sys import json # 获取当前路径, 通过anchor文件获取项目root路径 this_file_path = os.path.split(os.path.realpath(__file__))[0]", "file_path = os.path.join(root_path, file_path) file = open(file_path) line = file.readline()", "import json # 获取当前路径, 通过anchor文件获取项目root路径 this_file_path = os.path.split(os.path.realpath(__file__))[0] this_path =", "os.path.join(root_path, train_dir) if not os.path.exists(train_dir): os.makedirs(train_dir) # 解析出parse result file", "%s sentence' % count) text = line.strip() try: ss_pos_tags =", "parser.text2ss_pos_tags(text) for pos_tags in ss_pos_tags: pos_tags_file.write(json.dumps(pos_tags, ensure_ascii=False) + '\\n') except", "import os, sys import json # 获取当前路径, 通过anchor文件获取项目root路径 this_file_path =", "open(file_path) line = file.readline() count = 0 while line: count", "= os.path.join(parse_result_dir, pos_tags_file_name) KB = KnowledgeBase() parser = sParser(KB) with", "# 打开语料文件 file_path = 'data/corpus/zh_wiki/wiki_test' file_path = os.path.join(root_path, file_path) file", "break else: this_path = par_path sys.path.append(root_path) from modules.sParser.sParser import sParser", "1 if count % 5000 == 0: print('parsed %s sentence'", "if count % 5000 == 0: print('parsed %s sentence' %", "as pos_tags_file: # 打开语料文件 file_path = 'data/corpus/zh_wiki/wiki_test' file_path = os.path.join(root_path,", "train_dir = 'data/train_zh_wiki' train_dir = os.path.join(root_path, train_dir) if not os.path.exists(train_dir):", "this_file_path = os.path.split(os.path.realpath(__file__))[0] this_path = this_file_path root_path = this_file_path while", "text = line.strip() try: ss_pos_tags = parser.text2ss_pos_tags(text) for pos_tags in", "try: ss_pos_tags = parser.text2ss_pos_tags(text) for pos_tags in ss_pos_tags: pos_tags_file.write(json.dumps(pos_tags, ensure_ascii=False)", "if par_path == this_path: break else: this_path = par_path sys.path.append(root_path)", "parse_result_dir) if not os.path.exists(parse_result_dir): os.makedirs(parse_result_dir) pos_tags_file_name = 'pos_tags_file' pos_tags_file_path =", "if os.path.exists(os.path.join(this_path, 'sosweety_root_anchor.py')): root_path = this_path break par_path = os.path.dirname(this_path)", "获取当前路径, 通过anchor文件获取项目root路径 this_file_path = os.path.split(os.path.realpath(__file__))[0] this_path = this_file_path root_path =", "os.path.exists(train_dir): os.makedirs(train_dir) # 解析出parse result file parse_result_dir = 'parse_result' parse_result_dir", "modules.sParser.sParser import sParser from modules.knowledgebase.kb import KnowledgeBase train_dir = 'data/train_zh_wiki'", "打开语料文件 file_path = 'data/corpus/zh_wiki/wiki_test' file_path = os.path.join(root_path, file_path) file =", "from modules.knowledgebase.kb import KnowledgeBase train_dir = 'data/train_zh_wiki' train_dir = os.path.join(root_path,", "= KnowledgeBase() parser = sParser(KB) with open(pos_tags_file_path, 'w') as pos_tags_file:", "'parse_result' parse_result_dir = os.path.join(train_dir, parse_result_dir) if not os.path.exists(parse_result_dir): os.makedirs(parse_result_dir) pos_tags_file_name", "= open(file_path) line = file.readline() count = 0 while line:", "this_file_path root_path = this_file_path while this_path: if os.path.exists(os.path.join(this_path, 'sosweety_root_anchor.py')): root_path", "sParser(KB) with open(pos_tags_file_path, 'w') as pos_tags_file: # 打开语料文件 file_path =", "if not os.path.exists(train_dir): os.makedirs(train_dir) # 解析出parse result file parse_result_dir =", "= os.path.dirname(this_path) # print(par_path) if par_path == this_path: break else:", "this_path = this_file_path root_path = this_file_path while this_path: if os.path.exists(os.path.join(this_path,", "par_path = os.path.dirname(this_path) # print(par_path) if par_path == this_path: break", "% count) text = line.strip() try: ss_pos_tags = parser.text2ss_pos_tags(text) for", "while this_path: if os.path.exists(os.path.join(this_path, 'sosweety_root_anchor.py')): root_path = this_path break par_path", "this_path break par_path = os.path.dirname(this_path) # print(par_path) if par_path ==", "通过anchor文件获取项目root路径 this_file_path = os.path.split(os.path.realpath(__file__))[0] this_path = this_file_path root_path = this_file_path", "= this_path break par_path = os.path.dirname(this_path) # print(par_path) if par_path", "print('line %s decode error' % count) line = file.readline() file.close()", "0 while line: count += 1 if count % 5000", "not os.path.exists(parse_result_dir): os.makedirs(parse_result_dir) pos_tags_file_name = 'pos_tags_file' pos_tags_file_path = os.path.join(parse_result_dir, pos_tags_file_name)", "count % 5000 == 0: print('parsed %s sentence' % count)", "this_path: break else: this_path = par_path sys.path.append(root_path) from modules.sParser.sParser import", "os.path.split(os.path.realpath(__file__))[0] this_path = this_file_path root_path = this_file_path while this_path: if", "root_path = this_file_path while this_path: if os.path.exists(os.path.join(this_path, 'sosweety_root_anchor.py')): root_path =", "= this_file_path while this_path: if os.path.exists(os.path.join(this_path, 'sosweety_root_anchor.py')): root_path = this_path", "os.path.exists(os.path.join(this_path, 'sosweety_root_anchor.py')): root_path = this_path break par_path = os.path.dirname(this_path) #", "with open(pos_tags_file_path, 'w') as pos_tags_file: # 打开语料文件 file_path = 'data/corpus/zh_wiki/wiki_test'", "+ '\\n') except Exception: print('line %s decode error' % count)", "+= 1 if count % 5000 == 0: print('parsed %s", "import KnowledgeBase train_dir = 'data/train_zh_wiki' train_dir = os.path.join(root_path, train_dir) if", "os.path.join(train_dir, parse_result_dir) if not os.path.exists(parse_result_dir): os.makedirs(parse_result_dir) pos_tags_file_name = 'pos_tags_file' pos_tags_file_path", "KnowledgeBase train_dir = 'data/train_zh_wiki' train_dir = os.path.join(root_path, train_dir) if not", "train_dir = os.path.join(root_path, train_dir) if not os.path.exists(train_dir): os.makedirs(train_dir) # 解析出parse", "file_path = 'data/corpus/zh_wiki/wiki_test' file_path = os.path.join(root_path, file_path) file = open(file_path)", "= par_path sys.path.append(root_path) from modules.sParser.sParser import sParser from modules.knowledgebase.kb import", "ensure_ascii=False) + '\\n') except Exception: print('line %s decode error' %", "'data/train_zh_wiki' train_dir = os.path.join(root_path, train_dir) if not os.path.exists(train_dir): os.makedirs(train_dir) #", "os.path.join(parse_result_dir, pos_tags_file_name) KB = KnowledgeBase() parser = sParser(KB) with open(pos_tags_file_path,", "解析出parse result file parse_result_dir = 'parse_result' parse_result_dir = os.path.join(train_dir, parse_result_dir)", "parser = sParser(KB) with open(pos_tags_file_path, 'w') as pos_tags_file: # 打开语料文件", "par_path == this_path: break else: this_path = par_path sys.path.append(root_path) from", "Exception: print('line %s decode error' % count) line = file.readline()", "= 'parse_result' parse_result_dir = os.path.join(train_dir, parse_result_dir) if not os.path.exists(parse_result_dir): os.makedirs(parse_result_dir)", "= line.strip() try: ss_pos_tags = parser.text2ss_pos_tags(text) for pos_tags in ss_pos_tags:", "os.makedirs(parse_result_dir) pos_tags_file_name = 'pos_tags_file' pos_tags_file_path = os.path.join(parse_result_dir, pos_tags_file_name) KB =", "'w') as pos_tags_file: # 打开语料文件 file_path = 'data/corpus/zh_wiki/wiki_test' file_path =", "while line: count += 1 if count % 5000 ==", "ss_pos_tags = parser.text2ss_pos_tags(text) for pos_tags in ss_pos_tags: pos_tags_file.write(json.dumps(pos_tags, ensure_ascii=False) +", "json # 获取当前路径, 通过anchor文件获取项目root路径 this_file_path = os.path.split(os.path.realpath(__file__))[0] this_path = this_file_path", "os.path.exists(parse_result_dir): os.makedirs(parse_result_dir) pos_tags_file_name = 'pos_tags_file' pos_tags_file_path = os.path.join(parse_result_dir, pos_tags_file_name) KB", "'\\n') except Exception: print('line %s decode error' % count) line", "not os.path.exists(train_dir): os.makedirs(train_dir) # 解析出parse result file parse_result_dir = 'parse_result'", "sys.path.append(root_path) from modules.sParser.sParser import sParser from modules.knowledgebase.kb import KnowledgeBase train_dir", "parse_result_dir = os.path.join(train_dir, parse_result_dir) if not os.path.exists(parse_result_dir): os.makedirs(parse_result_dir) pos_tags_file_name =", "file = open(file_path) line = file.readline() count = 0 while", "line.strip() try: ss_pos_tags = parser.text2ss_pos_tags(text) for pos_tags in ss_pos_tags: pos_tags_file.write(json.dumps(pos_tags,", "pos_tags_file_name) KB = KnowledgeBase() parser = sParser(KB) with open(pos_tags_file_path, 'w')", "= 'data/train_zh_wiki' train_dir = os.path.join(root_path, train_dir) if not os.path.exists(train_dir): os.makedirs(train_dir)", "= os.path.join(train_dir, parse_result_dir) if not os.path.exists(parse_result_dir): os.makedirs(parse_result_dir) pos_tags_file_name = 'pos_tags_file'", "import sParser from modules.knowledgebase.kb import KnowledgeBase train_dir = 'data/train_zh_wiki' train_dir", "'data/corpus/zh_wiki/wiki_test' file_path = os.path.join(root_path, file_path) file = open(file_path) line =", "= file.readline() count = 0 while line: count += 1", "this_path: if os.path.exists(os.path.join(this_path, 'sosweety_root_anchor.py')): root_path = this_path break par_path =", "pos_tags_file_path = os.path.join(parse_result_dir, pos_tags_file_name) KB = KnowledgeBase() parser = sParser(KB)", "result file parse_result_dir = 'parse_result' parse_result_dir = os.path.join(train_dir, parse_result_dir) if", "sParser from modules.knowledgebase.kb import KnowledgeBase train_dir = 'data/train_zh_wiki' train_dir =", "for pos_tags in ss_pos_tags: pos_tags_file.write(json.dumps(pos_tags, ensure_ascii=False) + '\\n') except Exception:", "in ss_pos_tags: pos_tags_file.write(json.dumps(pos_tags, ensure_ascii=False) + '\\n') except Exception: print('line %s", "root_path = this_path break par_path = os.path.dirname(this_path) # print(par_path) if", "= 0 while line: count += 1 if count %", "count = 0 while line: count += 1 if count", "5000 == 0: print('parsed %s sentence' % count) text =", "== this_path: break else: this_path = par_path sys.path.append(root_path) from modules.sParser.sParser", "except Exception: print('line %s decode error' % count) line =", "pos_tags in ss_pos_tags: pos_tags_file.write(json.dumps(pos_tags, ensure_ascii=False) + '\\n') except Exception: print('line", "print(par_path) if par_path == this_path: break else: this_path = par_path", "this_path = par_path sys.path.append(root_path) from modules.sParser.sParser import sParser from modules.knowledgebase.kb", "else: this_path = par_path sys.path.append(root_path) from modules.sParser.sParser import sParser from", "= 'pos_tags_file' pos_tags_file_path = os.path.join(parse_result_dir, pos_tags_file_name) KB = KnowledgeBase() parser", "'pos_tags_file' pos_tags_file_path = os.path.join(parse_result_dir, pos_tags_file_name) KB = KnowledgeBase() parser =", "par_path sys.path.append(root_path) from modules.sParser.sParser import sParser from modules.knowledgebase.kb import KnowledgeBase", "pos_tags_file: # 打开语料文件 file_path = 'data/corpus/zh_wiki/wiki_test' file_path = os.path.join(root_path, file_path)", "train_dir) if not os.path.exists(train_dir): os.makedirs(train_dir) # 解析出parse result file parse_result_dir", "modules.knowledgebase.kb import KnowledgeBase train_dir = 'data/train_zh_wiki' train_dir = os.path.join(root_path, train_dir)", "line = file.readline() count = 0 while line: count +=", "if not os.path.exists(parse_result_dir): os.makedirs(parse_result_dir) pos_tags_file_name = 'pos_tags_file' pos_tags_file_path = os.path.join(parse_result_dir,", "= 'data/corpus/zh_wiki/wiki_test' file_path = os.path.join(root_path, file_path) file = open(file_path) line", "sentence' % count) text = line.strip() try: ss_pos_tags = parser.text2ss_pos_tags(text)" ]
[ "- self.boundary_t)) ) def set_initial_x_in_session(self, x, session=None): if session is", "import numpy as np import tensorflow as tf class NetForHypinv(Model):", "bias] :param function: tf function for propagation. For example tf.nn.sigmoid,", "self.boundary_t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_boundary_output\") with tf.name_scope(\"FC_net\"): flowing_x =", "of weights for layers][0 weight, 1 bias] :param function: tf", "True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] = False x0 = full_out[:,self.base_class_index] x1 =", "binary classificaitons class_index and other classes if not self.eval_session: self.eval_session", "/ self.center[init_factor!=0] self.factor = tf.Variable(init_factor.reshape((1, len(self.center))), dtype=tf.float64, name=\"factor\") else: self.point_weights", "self.boundary_loss = list() if self.use_modified_loss: for i in range(self.num_classes): self.boundary_loss.append(", "if session is None: self.set_initial_x(x) else: pass # overide this", "# overided methods from gtrain.Model def get_loss(self): if self.training_class_index is", "return self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def has_modified_loss(self): return self.use_modified_loss def name(self):", "flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b)) y = flowing_x self.out =", "# sets center point self.center = center / np.linalg.norm(center) def", "used in HypINV rule extraction algorithm The task is simplified", "not self.grad_session: self.grad_session = tf.Session() with self.grad_session.as_default(): self.build_for_eval() self.grad =", "shape=[None, 2], name=\"Target_boundary_output\") with tf.name_scope(\"FC_net\"): flowing_x = self.x for i,", "x in certain session if session is None: self.set_initial_x(x) else:", "self.layer_sizes = [len(self.weights[0][0])] for bias in weights[1]: self.layer_sizes.append(len(bias)) self.num_classes =", "- x1_constant)) ) else: for i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]", "is used as the base class :param function: tf function", "use_modified_loss self.mu = mu def build(self): with tf.name_scope(\"Input\"): self.init_point =", "of purposes of modified loss function def __del__(self): # close", "False x0 = full_out[:,self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1)", "axis=1) self.boundary_out.append(self.out) self.boundary_out.append(tf.stack([x1/s, x0/s], axis=1)) with tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean(", "arr sessions if self.eval_session: self.eval_session.close() if self.grad_session: self.grad_session.close() def set_initial_x(self,", "name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.initial_x))), dtype=tf.float64, name=\"factor\") self.x = self.init_point", "tf.Variable(init_factor.reshape((1, len(self.center))), dtype=tf.float64, name=\"factor\") else: self.point_weights = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64,", "the penalty terms that specified the distance between x0 and", "= tf.placeholder(tf.float64, shape=[None, self.num_classes], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64, shape=[None, 2],", "boundary_eval(self, x, class_index): # evaluates binary classificaitons class_index and other", "of tf tensorf for each class of softmax class vs", "= None # list of tf tensorf for each class", "others output self.loss = None self.boundary_loss = None self.t =", "FCNetForHypinv(NetForHypinv): \"\"\" Implementation of multi layer perceptron to by used", "other classes \"\"\" def __init__(self, weights, base_class_index, function=tf.sigmoid, use_modified_loss=False, mu", "dtype=tf.float64) self.t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64,", "= self.function(tf.nn.xw_plus_b(flowing_x, W, b)) y = flowing_x self.out = tf.nn.softmax(y)", "loss should be used :param mu: factor of the penalty", "tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() for i in range(self.num_classes):", "self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def has_modified_loss(self): return self.use_modified_loss def", "its subclass, for example see FCNetForHypinv \"\"\" def __init__(self, weights):", "the search of the closest point self.initial_x = initial_x def", "self.factor = tf.Variable(np.ones((1, len(self.center))), dtype=tf.float64, name=\"factor\") self.x = self.point_weights *", "= tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(self.out) self.boundary_out.append(tf.stack([x1/s, x0/s], axis=1)) with tf.name_scope(\"Loss_functions\"):", "base_class_index self.function = function self.layer_sizes = [len(self.weights[0][0])] for bias in", "to be filled in build method) self.x_for_eval = None self.out", "x1_constant)) ) else: for i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] -", "in build method) self.x_for_eval = None self.out = None self.boundary_out", "with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.out_for_eval, {self.x_for_eval: x}) def boundary_eval(self,", "class FCNetForHypinvBinary(FCNetForHypinv): \"\"\" Implementation of multi layer perceptron to by", "task is simplified to the binary classificaiton base_class_index against the", "sets starting point for the search of the closest point", "# tf variable for inversion (going to be filled in", "self.grad_session = tf.Session() with self.grad_session.as_default(): self.build_for_eval() self.grad = list() for", "self.eval_session: self.eval_session = tf.Session() with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.out_for_eval,", "classes if not self.eval_session: self.eval_session = tf.Session() with self.eval_session.as_default(): self.build_for_eval()", "= None #(going to be filled in build_for_eval method) self.boundary_out_for_eval", "session=None): if session is None: self.set_initial_x(x) else: if self.center is", "be filled in build_for_eval method) self.boundary_out_for_eval = None self.trained_x =", "x0/s], axis=1)) def get_boundary_gradient(self, x, class_index): if not self.grad_session: self.grad_session", "the HypINV algorithm. Warning: Do not use this class but", "return [self.boundary_t] #________________________________________EXAMPLES_OF_NetForHypinv_CLASS_____________________________________________ class FCNetForHypinv(NetForHypinv): \"\"\" Implementation of multi layer", "get_hits(self): return self.get_loss() def get_count(self): return self.get_loss() def get_train_summaries(self): return", "with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.boundary_out_for_eval[class_index], {self.x_for_eval: x}) def get_boundary_gradient(self,", "if session is None: self.set_initial_x(x) else: if self.center is None:", "self.grad_session: self.grad_session.close() def set_initial_x(self, initial_x): # sets starting point for", "self.point_weights = tf.Variable(self.center.reshape((1, len(self.center))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") init_factor = self.center", "self.center[init_factor!=0] session.run(self.factor.assign(init_factor.reshape((1,len(init_factor))))) def build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval = tf.placeholder(tf.float32, shape=[None,", "shape=[None, 2], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_boundary_output\") with", "perceptron to by used in HypINV rule extraction algorithm \"\"\"", "of modified loss function def __del__(self): # close arr sessions", "for example see FCNetForHypinv \"\"\" def __init__(self, weights): self.eval_session =", "loss function def __del__(self): # close arr sessions if self.eval_session:", "self.training_class_index is None: return self.loss else: return self.boundary_loss[self.training_class_index] def get_hits(self):", "class_index): if not self.grad_session: self.grad_session = tf.Session() with self.grad_session.as_default(): self.build_for_eval()", "self.out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(self.out) self.boundary_out.append(tf.stack([x1/s, x0/s], axis=1)) with", "self.boundary_out_for_eval = None self.trained_x = None self.training_class_index = None self.x", "def get_placeholders(self): if self.training_class_index is None: return [self.t] else: return", "with tf.name_scope(\"Input\"): self.init_point = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor", "= flowing_x full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list()", "list() for i in range(2): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x = self.x_for_eval", "in weights[1]: self.layer_sizes.append(len(bias)) self.num_classes = self.layer_sizes[-1] self.initial_x = np.zeros([1, self.layer_sizes[0]])", "\"\"\" Implementaion of the crutial function for the HypINV algorithm.", "self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval", "loss then it returns true def set_initial_x_in_session(self, x, session=None): #", "class of the x1 self.training_class_index = class_index # overided methods", "def get_hits(self): return self.get_loss() def get_count(self): return self.get_loss() def get_train_summaries(self):", "y = flowing_x self.out_for_eval = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval =", "tf.name_scope(\"layer_{}\".format(i)): W = tf.constant(self.weights[0][i], name=\"Weight_{}\".format(i), dtype=tf.float64) b = tf.constant(self.weights[1][i], name=\"Bias_{}\".format(i),", "subclass, for example see FCNetForHypinv \"\"\" def __init__(self, weights): self.eval_session", "axis=1), axis=1) s = x0+x1 out = tf.stack([x0/s, x1/s], axis=1)", "]) else: init_factor = self.center init_factor[init_factor!=0] = x[init_factor!=0] / self.center[init_factor!=0]", "tf.nn.l2_loss(self.out-self.t), name=\"loss\") with tf.name_scope(\"Binary_class_loss\"): self.boundary_loss = list() if self.use_modified_loss: for", "None self.weights = weights self.out_for_eval = None #(going to be", "super(FCNetForHypinvBinary, self).__init__(weights) self.base_class_index = base_class_index self.function = function self.layer_sizes =", "in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def set_initial_x_in_session(self, x,", "= None self.boundary_loss = None self.t = None #target self.boundary_t", "x): if len(x.shape) == 1: x = x.reshape((1,len(x))) if not", "range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant)) )", "as the base class :param function: tf function for propagation.", "None: self.set_initial_x(x) else: pass # overide this method def eval(self,", "len(self.initial_x))), dtype=tf.float64, name=\"factor\") self.x = self.init_point * self.factor with tf.name_scope(\"Target\"):", "weights): self.eval_session = None self.grad_session = None self.initial_x = None", "for i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def", "for i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def", "\"\"\" :param weights: saved as [list of weights for layers][0", "= tf.reduce_mean( tf.nn.l2_loss(self.out-self.t), name=\"loss\") with tf.name_scope(\"Binary_class_loss\"): self.boundary_loss = list() if", "x1 self.training_class_index = class_index # overided methods from gtrain.Model def", "x1 from the boundary \"\"\" super(FCNetForHypinvBinary, self).__init__(weights) self.base_class_index = base_class_index", "i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x -", "each class of softmax class vs others output self.loss =", "for propagation. For example tf.nn.sigmoid, tf.atan :param use_modified_loss: weather the", "self.boundary_out.append(out) with tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean( tf.nn.l2_loss(self.out-self.t), name=\"loss\") with tf.name_scope(\"Binary_class_loss\"):", "= list() if self.use_modified_loss: for i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t))", "returns true def set_initial_x_in_session(self, x, session=None): # sets initial x", "train_ended(self, session): self.trained_x = session.run(self.x) def build(self): # build model", "self.center init_factor[init_factor!=0] = self.initial_x[init_factor!=0] / self.center[init_factor!=0] self.factor = tf.Variable(init_factor.reshape((1, len(self.center))),", "self.function(tf.nn.xw_plus_b(flowing_x, W, b)) y = flowing_x full_out = tf.nn.softmax(y) with", "session is None: self.set_initial_x(x) else: if self.center is None: session.run([", "def get_count(self): return self.get_loss() def get_train_summaries(self): return [] def get_dev_summaries(self):", "dtype=np.bool) mask[i] = False x0 = self.out_for_eval[:, i] x1 =", "False x0 = self.out[:,i] x1 = tf.reduce_max(tf.boolean_mask(self.out, mask, axis=1), axis=1)", "x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s = x0+x1 self.out_for_eval", "tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] =", "= True+np.zeros(self.num_classes, dtype=np.bool) mask[i] = False x0 = self.out[:,i] x1", "_ in enumerate(self.weights[0]): with tf.name_scope(\"layer_{}\".format(i)): W = tf.constant(self.weights[0][i], name=\"Weight_{}\".format(i), dtype=tf.float64)", "None self.boundary_loss = None self.t = None #target self.boundary_t =", "is not None: self.point_weights = tf.Variable(self.center.reshape((1, len(self.center))), dtype=tf.float64, trainable=False, name=\"Boundary_point\")", "#(going to be filled in build_for_eval method) self.boundary_out_for_eval = None", "initial x in certain session if session is None: self.set_initial_x(x)", "= None self.weights = weights self.out_for_eval = None #(going to", "self.use_modified_loss = use_modified_loss self.mu = mu def build(self): with tf.name_scope(\"Input\"):", "tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() for i in range(self.num_classes):", "get_train_summaries(self): return [] def get_dev_summaries(self): return [] def get_placeholders(self): if", "tf.reduce_max(tf.boolean_mask(self.out_for_eval, mask, axis=1), axis=1) s = x0+x1 out = tf.stack([x0/s,", "__del__(self): # close arr sessions if self.eval_session: self.eval_session.close() if self.grad_session:", "list() if self.use_modified_loss: for i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) +", "tf.constant(self.x1.reshape((1, len(self.x1))), dtype=tf.float64) self.t = tf.placeholder(tf.float64, shape=[None, self.num_classes], name=\"Target_output\") self.boundary_t", "self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.boundary_out_for_eval[class_index], {self.x_for_eval: x}) def get_boundary_gradient(self, x,", "center): # sets center point self.center = center / np.linalg.norm(center)", "distance between x0 and x1 and the distance x1 from", "y = flowing_x full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval =", "overided methods from gtrain.Model def get_loss(self): if self.training_class_index is None:", "if self.center is None: session.run([ self.point_weights.assign(x.reshape((1, len(x)))), self.factor.assign(np.ones((1, len(x)))) ])", "self.weights = weights self.out_for_eval = None #(going to be filled", "= tf.Session() with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.boundary_out_for_eval[class_index], {self.x_for_eval: x})", "b = tf.constant(self.weights[1][i], name=\"eBias_{}\".format(i)) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b), name=\"elayer_{}\".format(i))", "self.use_modified_loss def name(self): return \"Hypinv_FC_net_{}\".format(\"-\".join([str(ls) for ls in self.layer_sizes])) class", "def train_ended(self, session): self.trained_x = session.run(self.x) def build(self): # build", "self.out[:,i] x1 = tf.reduce_max(tf.boolean_mask(self.out, mask, axis=1), axis=1) s = x0+x1", "self.use_modified_loss: x1_constant = tf.constant(self.x1.reshape((1, len(self.x1))), dtype=tf.float64) self.t = tf.placeholder(tf.float64, shape=[None,", "flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b), name=\"elayer_{}\".format(i)) y = flowing_x full_out", "tf.name_scope(\"Binary_class_loss\"): self.boundary_loss = list() if self.use_modified_loss: for i in range(self.num_classes):", "return self.use_modified_loss def name(self): return \"Hypinv_FC_net_{}\".format(\"-\".join([str(ls) for ls in self.layer_sizes]))", "self.eval_session: self.eval_session.close() if self.grad_session: self.grad_session.close() def set_initial_x(self, initial_x): # sets", "for the search of the closest point self.initial_x = initial_x", "x1 def has_modified_loss(self): pass # if uses modified loss then", "point self.initial_x = initial_x def set_center(self, center): # sets center", "method (fill self.x, self.out) def set_train_class(self, class_index): # sets class", "None: return [self.t] else: return [self.boundary_t] #________________________________________EXAMPLES_OF_NetForHypinv_CLASS_____________________________________________ class FCNetForHypinv(NetForHypinv): \"\"\"", "self.factor = tf.Variable(np.ones((1, len(self.initial_x))), dtype=tf.float64, name=\"factor\") self.x = self.init_point *", "self.point_weights = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1,", "pass # overide this method def eval(self, x): if len(x.shape)", "self.out) def set_train_class(self, class_index): # sets class of the x1", "mask[i] = False x0 = self.out_for_eval[:, i] x1 = tf.reduce_max(tf.boolean_mask(self.out_for_eval,", "self.out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() for i", "= None self.x = None # tf variable for inversion", "= list() for i in range(self.num_classes): mask = True+np.zeros(self.num_classes, dtype=np.bool)", "list of tf tensorf for each class of softmax class", "initial_x def set_center(self, center): # sets center point self.center =", "name=\"Boundary_point\") init_factor = self.center init_factor[init_factor!=0] = self.initial_x[init_factor!=0] / self.center[init_factor!=0] self.factor", "session.run([ self.point_weights.assign(x.reshape((1, len(x)))), self.factor.assign(np.ones((1, len(x)))) ]) else: init_factor = self.center", "None: session.run([ self.point_weights.assign(x.reshape((1, len(x)))), self.factor.assign(np.ones((1, len(x)))) ]) else: init_factor =", "rule extraction algorithm The task is simplified to the binary", "= None self.grad_session = None self.initial_x = None self.center =", "s = x0+x1 self.out_for_eval = tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(self.out_for_eval) self.boundary_out_for_eval.append(tf.stack([x1/s,", "return self.eval_session.run(self.boundary_out_for_eval[class_index], {self.x_for_eval: x}) def get_boundary_gradient(self, x, class_index): # computes", "x, class_index): if not self.grad_session: self.grad_session = tf.Session() with self.grad_session.as_default():", "def get_train_summaries(self): return [] def get_dev_summaries(self): return [] def get_placeholders(self):", "else: for i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) )", "= None self.trained_x = None self.training_class_index = None self.x =", "build(self): with tf.name_scope(\"Input\"): self.init_point = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\")", "= None self.training_class_index = None self.x = None # tf", "uses modified loss then it returns true def set_initial_x_in_session(self, x,", "self.num_classes], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_boundary_output\") with tf.name_scope(\"FC_net\"):", "tf.name_scope(\"eInput\"): self.x_for_eval = tf.placeholder(tf.float32, shape=[None, len(self.weights[0][0])])#tf.Variable(tf.constant(self.initial_x), name=\"Boundary_point\") with tf.name_scope(\"eFC_net\"): flowing_x", "binary classificaiton base_class_index against the other classes \"\"\" def __init__(self,", "= function self.layer_sizes = [len(self.weights[0][0])] for bias in weights[1]: self.layer_sizes.append(len(bias))", "self.out_for_eval = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() for i", "[] def get_placeholders(self): if self.training_class_index is None: return [self.t] else:", "mu def build(self): with tf.name_scope(\"Input\"): if self.center is not None:", "session is None: self.set_initial_x(x) else: pass # overide this method", "function=tf.sigmoid, use_modified_loss=False, mu = 0.01): \"\"\" :param weights: saved as", "flowing_x = self.x_for_eval for i, _ in enumerate(self.weights[0]): W =", "session if session is None: self.set_initial_x(x) else: pass # overide", "self.eval_session.close() if self.grad_session: self.grad_session.close() def set_initial_x(self, initial_x): # sets starting", "def boundary_eval(self, x, class_index): # evaluates binary classificaitons class_index and", "full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() mask =", "= tf.Variable(self.center.reshape((1, len(self.center))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") init_factor = self.center init_factor[init_factor!=0]", "pass #override this method (fill self.x, self.out) def set_train_class(self, class_index):", "out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(out) def has_modified_loss(self): return self.use_modified_loss", "self.mu = mu def build(self): with tf.name_scope(\"Input\"): if self.center is", "in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant))", "np.zeros([1, self.layer_sizes[0]]) self.use_modified_loss = use_modified_loss self.mu = mu def build(self):", "self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def build_for_eval(self): # build model for evaluation", "def set_initial_x_in_session(self, x, session=None): # sets initial x in certain", "# build model for evaluation pass #override this method (fill", "self.out_for_eval) def train_ended(self, session): self.trained_x = session.run(self.x) def build(self): #", "implement its subclass, for example see FCNetForHypinv \"\"\" def __init__(self,", "method) self.boundary_out_for_eval = None self.trained_x = None self.training_class_index = None", "if self.eval_session: self.eval_session.close() if self.grad_session: self.grad_session.close() def set_initial_x(self, initial_x): #", "= tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.initial_x))),", "x0+x1 self.out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(self.out) self.boundary_out.append(tf.stack([x1/s, x0/s], axis=1))", "x1_constant = tf.constant(self.x1.reshape((1, len(self.x1))), dtype=tf.float64) self.t = tf.placeholder(tf.float64, shape=[None, self.num_classes],", "def name(self): return \"Hypinv_FC_net_{}\".format(\"-\".join([str(ls) for ls in self.layer_sizes])) class FCNetForHypinvBinary(FCNetForHypinv):", "method (fill self.out_for_eval) def train_ended(self, session): self.trained_x = session.run(self.x) def", "for i, _ in enumerate(self.weights[0]): W = tf.constant(self.weights[0][i], name=\"eWeight_{}\".format(i)) b", "the other classes \"\"\" def __init__(self, weights, base_class_index, function=tf.sigmoid, use_modified_loss=False,", "self.use_modified_loss: for i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu *", "x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s = x0+x1 self.out", "if self.training_class_index is None: return [self.t] else: return [self.boundary_t] #________________________________________EXAMPLES_OF_NetForHypinv_CLASS_____________________________________________", "with tf.name_scope(\"Input\"): if self.center is not None: self.point_weights = tf.Variable(self.center.reshape((1,", "self.loss else: return self.boundary_loss[self.training_class_index] def get_hits(self): return self.get_loss() def get_count(self):", "base_class_index against the other classes \"\"\" def __init__(self, weights, base_class_index,", "def eval(self, x): if len(x.shape) == 1: x = x.reshape((1,len(x)))", "self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.boundary_out_for_eval[class_index], {self.x_for_eval: x}) def get_boundary_gradient(self, x, class_index): #", "self.grad_session: self.grad_session = tf.Session() with self.grad_session.as_default(): self.build_for_eval() self.grad = list()", "if len(x.shape) == 1: x = x.reshape((1,len(x))) if not self.eval_session:", "session): self.trained_x = session.run(self.x) def build(self): # build model for", "mask, axis=1), axis=1) s = x0+x1 out = tf.stack([x0/s, x1/s],", "purposes of modified loss function def __del__(self): # close arr", "it returns true def set_initial_x_in_session(self, x, session=None): # sets initial", "set_initial_x_in_session(self, x, session=None): if session is None: self.set_initial_x(x) else: if", "= self.layer_sizes[-1] self.initial_x = np.zeros([1, self.layer_sizes[0]]) self.use_modified_loss = use_modified_loss self.mu", "tf.constant(self.weights[0][i], name=\"eWeight_{}\".format(i)) b = tf.constant(self.weights[1][i], name=\"eBias_{}\".format(i)) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W,", "x}) def has_modified_loss(self): return self.use_modified_loss def name(self): return \"Hypinv_FC_net_{}\".format(\"-\".join([str(ls) for", "gtrain import Model import numpy as np import tensorflow as", "saved as [list of weights for layers][0 weight, 1 bias]", "self.x, self.out) def set_train_class(self, class_index): # sets class of the", "dtype=tf.float64, trainable=False, name=\"Boundary_point\") init_factor = self.center init_factor[init_factor!=0] = self.initial_x[init_factor!=0] /", "= np.zeros([1, self.layer_sizes[0]]) self.use_modified_loss = use_modified_loss self.mu = mu def", "i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def build_for_eval(self):", "closest point self.initial_x = initial_x def set_center(self, center): # sets", "x, session=None): if session is None: self.set_initial_x(x) else: if self.center", "None # this attribute is used of purposes of modified", "self.eval_session = tf.Session() with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.out_for_eval, {self.x_for_eval:", "from gtrain.Model def get_loss(self): if self.training_class_index is None: return self.loss", "mask[i] = False x0 = self.out[:,i] x1 = tf.reduce_max(tf.boolean_mask(self.out, mask,", "def build_for_eval(self): # build model for evaluation pass #override this", "gradient of the boundary for specified class_index if not self.grad_session:", "for evaluation pass #override this method (fill self.out_for_eval) def train_ended(self,", "y = flowing_x self.out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out =", "def has_modified_loss(self): pass # if uses modified loss then it", "with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index]", "= x0+x1 self.out_for_eval = tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(self.out_for_eval) self.boundary_out_for_eval.append(tf.stack([x1/s, x0/s],", "should be used :param mu: factor of the penalty terms", "boundary \"\"\" super(FCNetForHypinv, self).__init__(weights) self.function = function self.layer_sizes = [len(self.weights[0][0])]", "= tf.constant(self.weights[0][i], name=\"eWeight_{}\".format(i)) b = tf.constant(self.weights[1][i], name=\"eBias_{}\".format(i)) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x,", "weights self.out_for_eval = None #(going to be filled in build_for_eval", "for i in range(2): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x = self.x_for_eval return", "= tf.placeholder(tf.float32, shape=[None, len(self.weights[0][0])])#tf.Variable(tf.constant(self.initial_x), name=\"Boundary_point\") with tf.name_scope(\"eFC_net\"): flowing_x = self.x_for_eval", "with tf.name_scope(\"layer_{}\".format(i)): W = tf.constant(self.weights[0][i], name=\"Weight_{}\".format(i), dtype=tf.float64) b = tf.constant(self.weights[1][i],", "x0+x1 self.out_for_eval = tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(self.out_for_eval) self.boundary_out_for_eval.append(tf.stack([x1/s, x0/s], axis=1))", "modified loss then it returns true def set_initial_x_in_session(self, x, session=None):", "len(x)))) ]) else: init_factor = self.center init_factor[init_factor!=0] = x[init_factor!=0] /", "tf class NetForHypinv(Model): \"\"\" Implementaion of the crutial function for", "else: return [self.boundary_t] #________________________________________EXAMPLES_OF_NetForHypinv_CLASS_____________________________________________ class FCNetForHypinv(NetForHypinv): \"\"\" Implementation of multi", "if not self.eval_session: self.eval_session = tf.Session() with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer())", "tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def set_initial_x_in_session(self, x, session=None): if session", "is None: session.run([ self.point_weights.assign(x.reshape((1, len(x)))), self.factor.assign(np.ones((1, len(x)))) ]) else: init_factor", "of the x1 self.training_class_index = class_index # overided methods from", "tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant)) ) else: for i in range(2): self.boundary_loss.append(", "i in range(2): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x = self.x_for_eval return self.grad_session.run(self.grad[class_index],", "tf.reduce_max(tf.boolean_mask(self.out, mask, axis=1), axis=1) s = x0+x1 out = tf.stack([x0/s,", "self.initial_x = None self.center = None self.weights = weights self.out_for_eval", "extraction algorithm \"\"\" def __init__(self, weights, function=tf.sigmoid, use_modified_loss=False, mu =", "[self.t] else: return [self.boundary_t] #________________________________________EXAMPLES_OF_NetForHypinv_CLASS_____________________________________________ class FCNetForHypinv(NetForHypinv): \"\"\" Implementation of", "flowing_x full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() mask", "None: return self.loss else: return self.boundary_loss[self.training_class_index] def get_hits(self): return self.get_loss()", "len(x)))), self.factor.assign(np.ones((1, len(x)))) ]) else: init_factor = self.center init_factor[init_factor!=0] =", "base_class_index, function=tf.sigmoid, use_modified_loss=False, mu = 0.01): \"\"\" :param weights: saved", "= self.x_for_eval for i, _ in enumerate(self.weights[0]): W = tf.constant(self.weights[0][i],", "weights, base_class_index, function=tf.sigmoid, use_modified_loss=False, mu = 0.01): \"\"\" :param weights:", "def set_x1(self, x1): # sets x1 to which we want", "name=\"factor\") else: self.point_weights = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor", "self.loss = None self.boundary_loss = None self.t = None #target", "self.get_loss() def get_count(self): return self.get_loss() def get_train_summaries(self): return [] def", "method) self.x_for_eval = None self.out = None self.boundary_out = None", "self.eval_session = None self.grad_session = None self.initial_x = None self.center", "__init__(self, weights, function=tf.sigmoid, use_modified_loss=False, mu = 0.01): \"\"\" :param weights:", "# this attribute is used of purposes of modified loss", "for i in range(self.num_classes): mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[i] =", "else: if self.center is None: session.run([ self.point_weights.assign(x.reshape((1, len(x)))), self.factor.assign(np.ones((1, len(x))))", "= x[init_factor!=0] / self.center[init_factor!=0] session.run(self.factor.assign(init_factor.reshape((1,len(init_factor))))) def build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval", "W = tf.constant(self.weights[0][i], name=\"eWeight_{}\".format(i)) b = tf.constant(self.weights[1][i], name=\"eBias_{}\".format(i)) flowing_x =", "flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b)) y = flowing_x full_out =", "self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s = x0+x1", "be used :param mu: factor of the penalty terms that", "we want to found the cosest point x0 self.x1 =", "if uses modified loss then it returns true def set_initial_x_in_session(self,", "tf.Variable(np.ones((1, len(self.initial_x))), dtype=tf.float64, name=\"factor\") self.x = self.init_point * self.factor with", "# if uses modified loss then it returns true def", "# computes gradient of the boundary for specified class_index if", "range(len(self.weights[0][-1][0])): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x = self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x: x})", "self.factor.assign(np.ones((1, len(x)))) ]) else: init_factor = self.center init_factor[init_factor!=0] = x[init_factor!=0]", "axis=1), axis=1) s = x0+x1 self.out_for_eval = tf.stack([x0/s, x1/s], axis=1)", "np.linalg.norm(center) def set_x1(self, x1): # sets x1 to which we", "pass #override this method (fill self.out_for_eval) def train_ended(self, session): self.trained_x", "of multi layer perceptron to by used in HypINV rule", "dtype=tf.float64, name=\"factor\") self.x = self.point_weights * self.factor with tf.name_scope(\"Target\"): if", "self.function(tf.nn.xw_plus_b(flowing_x, W, b), name=\"elayer_{}\".format(i)) y = flowing_x self.out_for_eval = tf.nn.softmax(y)", "def set_train_class(self, class_index): # sets class of the x1 self.training_class_index", "= full_out[:, self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s", "in build_for_eval method) self.boundary_out_for_eval = None self.trained_x = None self.training_class_index", "= session.run(self.x) def build(self): # build model for training pass", "crutial function for the HypINV algorithm. Warning: Do not use", "len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.center))), dtype=tf.float64, name=\"factor\")", "function self.layer_sizes = [len(self.weights[0][0])] for bias in weights[1]: self.layer_sizes.append(len(bias)) self.num_classes", "get_boundary_gradient(self, x, class_index): # computes gradient of the boundary for", "full_out[:,self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s = x0+x1", "classificaitons class_index and other classes if not self.eval_session: self.eval_session =", "self.set_initial_x(x) else: pass # overide this method def eval(self, x):", "return self.get_loss() def get_train_summaries(self): return [] def get_dev_summaries(self): return []", "self.layer_sizes[0]]) self.use_modified_loss = use_modified_loss self.mu = mu def build(self): with", "x0 and x1 and the distance x1 from the boundary", "this method (fill self.out_for_eval) def train_ended(self, session): self.trained_x = session.run(self.x)", "dtype=np.bool) mask[self.base_class_index] = False x0 = full_out[:, self.base_class_index] x1 =", "self.grad_x = self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def has_modified_loss(self): return", "#override this method (fill self.out_for_eval) def train_ended(self, session): self.trained_x =", "with tf.name_scope(\"eInput\"): self.x_for_eval = tf.placeholder(tf.float32, shape=[None, len(self.weights[0][0])])#tf.Variable(tf.constant(self.initial_x), name=\"Boundary_point\") with tf.name_scope(\"eFC_net\"):", "[list of weights for layers][0 weight, 1 bias] :param function:", "not self.eval_session: self.eval_session = tf.Session() with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return", "tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval =", "if self.center is not None: self.point_weights = tf.Variable(self.center.reshape((1, len(self.center))), dtype=tf.float64,", "self.base_class_index = base_class_index self.function = function self.layer_sizes = [len(self.weights[0][0])] for", "self.boundary_t = None self.x1 = None # this attribute is", "inversion (going to be filled in build method) self.x_for_eval =", "None #(going to be filled in build_for_eval method) self.boundary_out_for_eval =", "the distance x1 from the boundary \"\"\" super(FCNetForHypinvBinary, self).__init__(weights) self.base_class_index", "used in HypINV rule extraction algorithm \"\"\" def __init__(self, weights,", "b)) y = flowing_x full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out", "[] def get_dev_summaries(self): return [] def get_placeholders(self): if self.training_class_index is", "= x0+x1 self.out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(self.out) self.boundary_out.append(tf.stack([x1/s, x0/s],", "the crutial function for the HypINV algorithm. Warning: Do not", "None # tf variable for inversion (going to be filled", "= None self.boundary_out = None # list of tf tensorf", "self).__init__(weights) self.base_class_index = base_class_index self.function = function self.layer_sizes = [len(self.weights[0][0])]", "The task is simplified to the binary classificaiton base_class_index against", "\"Hypinv_FC_net_{}\".format(\"-\".join([str(ls) for ls in self.layer_sizes])) class FCNetForHypinvBinary(FCNetForHypinv): \"\"\" Implementation of", "self.factor = tf.Variable(init_factor.reshape((1, len(self.center))), dtype=tf.float64, name=\"factor\") else: self.point_weights = tf.Variable(self.initial_x.reshape((1,", "layers][0 weight, 1 bias] :param base_class_index: an index of the", "weight, 1 bias] :param base_class_index: an index of the class", "x.reshape((1,len(x))) if not self.eval_session: self.eval_session = tf.Session() with self.eval_session.as_default(): self.build_for_eval()", "weights: saved as [list of weights for layers][0 weight, 1", ") def build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval = tf.placeholder(tf.float32, shape=[None, len(self.weights[0][0])])#tf.Variable(tf.constant(self.initial_x),", "of the closest point self.initial_x = initial_x def set_center(self, center):", "the distance between x0 and x1 and the distance x1", "self.center init_factor[init_factor!=0] = x[init_factor!=0] / self.center[init_factor!=0] session.run(self.factor.assign(init_factor.reshape((1,len(init_factor))))) def build_for_eval(self): with", "tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(out) def has_modified_loss(self): return self.use_modified_loss def name(self):", "# sets x1 to which we want to found the", "session=None): # sets initial x in certain session if session", "pass # if uses modified loss then it returns true", "None self.x = None # tf variable for inversion (going", "set_train_class(self, class_index): # sets class of the x1 self.training_class_index =", "self.out_for_eval[:, i] x1 = tf.reduce_max(tf.boolean_mask(self.out_for_eval, mask, axis=1), axis=1) s =", "in HypINV rule extraction algorithm The task is simplified to", "name=\"Boundary_point\") with tf.name_scope(\"eFC_net\"): flowing_x = self.x_for_eval for i, _ in", "= tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(out) def has_modified_loss(self): return self.use_modified_loss def", "from gtrain import Model import numpy as np import tensorflow", "mu def build(self): with tf.name_scope(\"Input\"): self.init_point = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64,", "self.eval_session.run(self.boundary_out_for_eval[class_index], {self.x_for_eval: x}) def get_boundary_gradient(self, x, class_index): # computes gradient", "for layers][0 weight, 1 bias] :param function: tf function for", "name=\"factor\") self.x = self.point_weights * self.factor with tf.name_scope(\"Target\"): if self.use_modified_loss:", "= use_modified_loss self.mu = mu def build(self): with tf.name_scope(\"Input\"): if", "= tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() for i in", "self.point_weights * self.factor with tf.name_scope(\"Target\"): if self.use_modified_loss: x1_constant = tf.constant(self.x1.reshape((1,", "x}) def boundary_eval(self, x, class_index): # evaluates binary classificaitons class_index", "self.num_classes = self.layer_sizes[-1] self.initial_x = np.zeros([1, self.layer_sizes[0]]) self.use_modified_loss = use_modified_loss", "self.x = self.init_point * self.factor with tf.name_scope(\"Target\"): if self.use_modified_loss: x1_constant", "self.init_point = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1,", "mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] = False x0 = full_out[:,", "as np import tensorflow as tf class NetForHypinv(Model): \"\"\" Implementaion", "tf.name_scope(\"Target\"): if self.use_modified_loss: x1_constant = tf.constant(self.x1.reshape((1, len(self.x1))), dtype=tf.float64) self.t =", "= self.out_for_eval[:, i] x1 = tf.reduce_max(tf.boolean_mask(self.out_for_eval, mask, axis=1), axis=1) s", "= base_class_index self.function = function self.layer_sizes = [len(self.weights[0][0])] for bias", "= self.center init_factor[init_factor!=0] = x[init_factor!=0] / self.center[init_factor!=0] session.run(self.factor.assign(init_factor.reshape((1,len(init_factor))))) def build_for_eval(self):", "cosest point x0 self.x1 = x1 def has_modified_loss(self): pass #", "enumerate(self.weights[0]): with tf.name_scope(\"layer_{}\".format(i)): W = tf.constant(self.weights[0][i], name=\"Weight_{}\".format(i), dtype=tf.float64) b =", "function for propagation. For example tf.nn.sigmoid, tf.atan :param use_modified_loss: weather", "self.use_modified_loss: for i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu *", "tf.Session() with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.out_for_eval, {self.x_for_eval: x}) def", "init_factor = self.center init_factor[init_factor!=0] = self.initial_x[init_factor!=0] / self.center[init_factor!=0] self.factor =", "* tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant)) ) else: for i in range(2):", "x, session=None): # sets initial x in certain session if", "by used in HypINV rule extraction algorithm The task is", "name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.center))), dtype=tf.float64, name=\"factor\") self.x = self.point_weights", "= tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() mask = True+np.zeros(self.num_classes,", "the cosest point x0 self.x1 = x1 def has_modified_loss(self): pass", ":param mu: factor of the penalty terms that specified the", "{self.grad_x: x}) def build_for_eval(self): # build model for evaluation pass", "get_placeholders(self): if self.training_class_index is None: return [self.t] else: return [self.boundary_t]", "# overide this method def eval(self, x): if len(x.shape) ==", "self.x = self.point_weights * self.factor with tf.name_scope(\"Target\"): if self.use_modified_loss: x1_constant", "def get_boundary_gradient(self, x, class_index): if not self.grad_session: self.grad_session = tf.Session()", "name=\"Weight_{}\".format(i), dtype=tf.float64) b = tf.constant(self.weights[1][i], name=\"Bias_{}\".format(i), dtype=tf.float64) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x,", "= False x0 = self.out_for_eval[:, i] x1 = tf.reduce_max(tf.boolean_mask(self.out_for_eval, mask,", "get_boundary_gradient(self, x, class_index): if not self.grad_session: self.grad_session = tf.Session() with", "terms that specified the distance between x0 and x1 and", "with tf.name_scope(\"Target\"): if self.use_modified_loss: x1_constant = tf.constant(self.x1.reshape((1, len(self.x1))), dtype=tf.float64) self.t", "axis=1) s = x0+x1 out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(out)", "= False x0 = full_out[:,self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1),", "tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.center))), dtype=tf.float64,", "len(x.shape) == 1: x = x.reshape((1,len(x))) if not self.eval_session: self.eval_session", "= None self.out = None self.boundary_out = None # list", "distance x1 from the boundary \"\"\" super(FCNetForHypinv, self).__init__(weights) self.function =", "self.function(tf.nn.xw_plus_b(flowing_x, W, b), name=\"elayer_{}\".format(i)) y = flowing_x full_out = tf.nn.softmax(y)", "= flowing_x self.out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list()", "Do not use this class but implement its subclass, for", "sets center point self.center = center / np.linalg.norm(center) def set_x1(self,", "= tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(self.out_for_eval) self.boundary_out_for_eval.append(tf.stack([x1/s, x0/s], axis=1)) def get_boundary_gradient(self,", "self.layer_sizes.append(len(bias)) self.num_classes = self.layer_sizes[-1] self.initial_x = np.zeros([1, self.layer_sizes[0]]) self.use_modified_loss =", "= tf.constant(self.x1.reshape((1, len(self.x1))), dtype=tf.float64) self.t = tf.placeholder(tf.float64, shape=[None, self.num_classes], name=\"Target_output\")", "\"\"\" Implementation of multi layer perceptron to by used in", "mu: factor of the penalty terms that specified the distance", "self.x for i, _ in enumerate(self.weights[0]): with tf.name_scope(\"layer_{}\".format(i)): W =", "None #target self.boundary_t = None self.x1 = None # this", "weights for layers][0 weight, 1 bias] :param base_class_index: an index", "self).__init__(weights) self.function = function self.layer_sizes = [len(self.weights[0][0])] for bias in", "dtype=tf.float64) b = tf.constant(self.weights[1][i], name=\"Bias_{}\".format(i), dtype=tf.float64) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W,", "shape=[None, len(self.weights[0][0])])#tf.Variable(tf.constant(self.initial_x), name=\"Boundary_point\") with tf.name_scope(\"eFC_net\"): flowing_x = self.x_for_eval for i,", "= tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s = x0+x1 self.out_for_eval =", "distance x1 from the boundary \"\"\" super(FCNetForHypinvBinary, self).__init__(weights) self.base_class_index =", "(fill self.x, self.out) def set_train_class(self, class_index): # sets class of", "tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s = x0+x1 self.out_for_eval = tf.stack([x0/s,", "= tf.reduce_max(tf.boolean_mask(self.out_for_eval, mask, axis=1), axis=1) s = x0+x1 out =", "= self.center init_factor[init_factor!=0] = self.initial_x[init_factor!=0] / self.center[init_factor!=0] self.factor = tf.Variable(init_factor.reshape((1,", ":param base_class_index: an index of the class which is used", "# evaluates binary classificaitons class_index and other classes if not", "for specified class_index if not self.grad_session: self.grad_session = tf.Session() with", "self.grad = list() for i in range(len(self.weights[0][-1][0])): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x", "axis=1) self.boundary_out.append(out) with tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean( tf.nn.l2_loss(self.out-self.t), name=\"loss\") with", "classificaiton base_class_index against the other classes \"\"\" def __init__(self, weights,", "self.layer_sizes[-1] self.initial_x = np.zeros([1, self.layer_sizes[0]]) self.use_modified_loss = use_modified_loss self.mu =", "tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean( tf.nn.l2_loss(self.out-self.t), name=\"loss\") with tf.name_scope(\"Binary_class_loss\"): self.boundary_loss =", "return self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def build_for_eval(self): # build model for", "build(self): with tf.name_scope(\"Input\"): if self.center is not None: self.point_weights =", "self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant)) ) else:", "self.boundary_out = list() mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] = False", "* self.factor with tf.name_scope(\"Target\"): if self.use_modified_loss: x1_constant = tf.constant(self.x1.reshape((1, len(self.x1))),", "i, _ in enumerate(self.weights[0]): W = tf.constant(self.weights[0][i], name=\"eWeight_{}\".format(i)) b =", "tf.name_scope(\"Input\"): if self.center is not None: self.point_weights = tf.Variable(self.center.reshape((1, len(self.center))),", "layer perceptron to by used in HypINV rule extraction algorithm", "self.eval_session = tf.Session() with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.boundary_out_for_eval[class_index], {self.x_for_eval:", "trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.initial_x))), dtype=tf.float64, name=\"factor\") self.x =", "close arr sessions if self.eval_session: self.eval_session.close() if self.grad_session: self.grad_session.close() def", "x1_constant = tf.constant(self.x1.reshape((1, len(self.x1))), dtype=tf.float64) self.t = tf.placeholder(tf.float64, shape=[None, 2],", "i, _ in enumerate(self.weights[0]): with tf.name_scope(\"layer_{}\".format(i)): W = tf.constant(self.weights[0][i], name=\"Weight_{}\".format(i),", "super(FCNetForHypinv, self).__init__(weights) self.function = function self.layer_sizes = [len(self.weights[0][0])] for bias", "mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[i] = False x0 = self.out_for_eval[:,", "[len(self.weights[0][0])] for bias in weights[1]: self.layer_sizes.append(len(bias)) self.num_classes = self.layer_sizes[-1] self.initial_x", "set_center(self, center): # sets center point self.center = center /", "[self.x_for_eval])[0]) self.grad_x = self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def has_modified_loss(self):", "def get_loss(self): if self.training_class_index is None: return self.loss else: return", "softmax class vs others output self.loss = None self.boundary_loss =", "s = x0+x1 self.out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(self.out) self.boundary_out.append(tf.stack([x1/s,", "= tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() mask = True+np.zeros(self.num_classes,", "def get_boundary_gradient(self, x, class_index): # computes gradient of the boundary", "None self.initial_x = None self.center = None self.weights = weights", "* tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant)) ) else: for i in range(self.num_classes):", "= list() for i in range(len(self.weights[0][-1][0])): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x =", "trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.center))), dtype=tf.float64, name=\"factor\") self.x =", "tf tensorf for each class of softmax class vs others", "dtype=np.bool) mask[i] = False x0 = self.out[:,i] x1 = tf.reduce_max(tf.boolean_mask(self.out,", "else: return self.boundary_loss[self.training_class_index] def get_hits(self): return self.get_loss() def get_count(self): return", "x[init_factor!=0] / self.center[init_factor!=0] session.run(self.factor.assign(init_factor.reshape((1,len(init_factor))))) def build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval =", "with self.grad_session.as_default(): self.build_for_eval() self.grad = list() for i in range(len(self.weights[0][-1][0])):", "None: self.set_initial_x(x) else: if self.center is None: session.run([ self.point_weights.assign(x.reshape((1, len(x)))),", "x1 and the distance x1 from the boundary \"\"\" super(FCNetForHypinvBinary,", "algorithm \"\"\" def __init__(self, weights, function=tf.sigmoid, use_modified_loss=False, mu = 0.01):", "full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() mask =", "self.center = None self.weights = weights self.out_for_eval = None #(going", "= list() for i in range(2): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x =", "mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[i] = False x0 = self.out[:,i]", "get_loss(self): if self.training_class_index is None: return self.loss else: return self.boundary_loss[self.training_class_index]", "factor of the penalty terms that specified the distance between", "list() for i in range(self.num_classes): mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[i]", "with tf.name_scope(\"FC_net\"): flowing_x = self.x for i, _ in enumerate(self.weights[0]):", "2], name=\"Target_boundary_output\") with tf.name_scope(\"FC_net\"): flowing_x = self.x for i, _", "x0 = full_out[:,self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s", "W, b), name=\"elayer_{}\".format(i)) y = flowing_x full_out = tf.nn.softmax(y) with", "= tf.Session() with self.grad_session.as_default(): self.build_for_eval() self.grad = list() for i", "NetForHypinv(Model): \"\"\" Implementaion of the crutial function for the HypINV", "tf.reduce_mean( tf.nn.l2_loss(self.out-self.t), name=\"loss\") with tf.name_scope(\"Binary_class_loss\"): self.boundary_loss = list() if self.use_modified_loss:", "tf variable for inversion (going to be filled in build", "tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant)) ) else: for i in range(self.num_classes): self.boundary_loss.append(", "tf.constant(self.weights[0][i], name=\"Weight_{}\".format(i), dtype=tf.float64) b = tf.constant(self.weights[1][i], name=\"Bias_{}\".format(i), dtype=tf.float64) flowing_x =", "true def set_initial_x_in_session(self, x, session=None): # sets initial x in", "Warning: Do not use this class but implement its subclass,", "but implement its subclass, for example see FCNetForHypinv \"\"\" def", "x0 = full_out[:, self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1)", "# close arr sessions if self.eval_session: self.eval_session.close() if self.grad_session: self.grad_session.close()", "x1): # sets x1 to which we want to found", "def has_modified_loss(self): return self.use_modified_loss def name(self): return \"Hypinv_FC_net_{}\".format(\"-\".join([str(ls) for ls", "= self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def has_modified_loss(self): return self.use_modified_loss", "session.run(self.factor.assign(init_factor.reshape((1,len(init_factor))))) def build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval = tf.placeholder(tf.float32, shape=[None, len(self.weights[0][0])])#tf.Variable(tf.constant(self.initial_x),", "tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() mask = True+np.zeros(self.num_classes, dtype=np.bool)", "= tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.center))),", "name=\"Bias_{}\".format(i), dtype=tf.float64) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b)) y = flowing_x", "x0+x1 out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(out) def has_modified_loss(self): return", "of weights for layers][0 weight, 1 bias] :param base_class_index: an", "None: self.point_weights = tf.Variable(self.center.reshape((1, len(self.center))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") init_factor =", "= tf.Variable(np.ones((1, len(self.initial_x))), dtype=tf.float64, name=\"factor\") self.x = self.init_point * self.factor", "self.loss = tf.reduce_mean( tf.nn.l2_loss(self.out-self.t), name=\"loss\") with tf.name_scope(\"Binary_class_loss\"): self.boundary_loss = list()", "for i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x", "self.get_loss() def get_train_summaries(self): return [] def get_dev_summaries(self): return [] def", "to by used in HypINV rule extraction algorithm The task", "= list() if self.use_modified_loss: for i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t))", "0.01): \"\"\" :param weights: saved as [list of weights for", "self.x_for_eval = tf.placeholder(tf.float32, shape=[None, len(self.weights[0][0])])#tf.Variable(tf.constant(self.initial_x), name=\"Boundary_point\") with tf.name_scope(\"eFC_net\"): flowing_x =", "= tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() for i in", "= 0.01): \"\"\" :param weights: saved as [list of weights", "= self.function(tf.nn.xw_plus_b(flowing_x, W, b), name=\"elayer_{}\".format(i)) y = flowing_x full_out =", "the closest point self.initial_x = initial_x def set_center(self, center): #", "tensorflow as tf class NetForHypinv(Model): \"\"\" Implementaion of the crutial", "build_for_eval(self): # build model for evaluation pass #override this method", "self.factor with tf.name_scope(\"Target\"): if self.use_modified_loss: x1_constant = tf.constant(self.x1.reshape((1, len(self.x1))), dtype=tf.float64)", "= None # tf variable for inversion (going to be", "name=\"factor\") self.x = self.init_point * self.factor with tf.name_scope(\"Target\"): if self.use_modified_loss:", "gtrain.Model def get_loss(self): if self.training_class_index is None: return self.loss else:", "is None: return [self.t] else: return [self.boundary_t] #________________________________________EXAMPLES_OF_NetForHypinv_CLASS_____________________________________________ class FCNetForHypinv(NetForHypinv):", "axis=1), axis=1) s = x0+x1 self.out = tf.stack([x0/s, x1/s], axis=1)", "self.boundary_out.append(self.out) self.boundary_out.append(tf.stack([x1/s, x0/s], axis=1)) with tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean( tf.nn.l2_loss(self.out-self.t),", "and the distance x1 from the boundary \"\"\" super(FCNetForHypinv, self).__init__(weights)", "init_factor = self.center init_factor[init_factor!=0] = x[init_factor!=0] / self.center[init_factor!=0] session.run(self.factor.assign(init_factor.reshape((1,len(init_factor))))) def", "boundary \"\"\" super(FCNetForHypinvBinary, self).__init__(weights) self.base_class_index = base_class_index self.function = function", "= tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(out) with tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean(", "range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def set_initial_x_in_session(self, x, session=None):", "[list of weights for layers][0 weight, 1 bias] :param base_class_index:", "with tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean( tf.nn.l2_loss(self.out-self.t), name=\"loss\") with tf.name_scope(\"Binary_class_loss\"): self.boundary_loss", "self.function(tf.nn.xw_plus_b(flowing_x, W, b)) y = flowing_x self.out = tf.nn.softmax(y) with", "self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant)) ) else: for i in", "classes \"\"\" def __init__(self, weights, base_class_index, function=tf.sigmoid, use_modified_loss=False, mu =", "class_index): # computes gradient of the boundary for specified class_index", "axis=1)) with tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean( tf.nn.l2_loss(self.out-self.t), name=\"loss\") with tf.name_scope(\"Binary_class_loss\"):", "self.eval_session: self.eval_session = tf.Session() with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.boundary_out_for_eval[class_index],", "self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def has_modified_loss(self): return self.use_modified_loss def name(self): return", "self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.boundary_out_for_eval[class_index], {self.x_for_eval: x}) def get_boundary_gradient(self, x, class_index):", "for training pass #override this method (fill self.x, self.out) def", "self.build_for_eval() self.grad = list() for i in range(2): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0])", "i in range(self.num_classes): mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[i] = False", "class_index): # evaluates binary classificaitons class_index and other classes if", "True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] = False x0 = full_out[:, self.base_class_index] x1", "class :param function: tf function for propagation. For example tf.nn.sigmoid,", "session.run(self.x) def build(self): # build model for training pass #override", "the boundary \"\"\" super(FCNetForHypinv, self).__init__(weights) self.function = function self.layer_sizes =", "x0 = self.out[:,i] x1 = tf.reduce_max(tf.boolean_mask(self.out, mask, axis=1), axis=1) s", "weight, 1 bias] :param function: tf function for propagation. For", "tf.Session() with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.boundary_out_for_eval[class_index], {self.x_for_eval: x}) def", "= tf.Variable(np.ones((1, len(self.center))), dtype=tf.float64, name=\"factor\") self.x = self.point_weights * self.factor", "set_initial_x_in_session(self, x, session=None): # sets initial x in certain session", "np import tensorflow as tf class NetForHypinv(Model): \"\"\" Implementaion of", "# build model for training pass #override this method (fill", "len(self.weights[0][0])])#tf.Variable(tf.constant(self.initial_x), name=\"Boundary_point\") with tf.name_scope(\"eFC_net\"): flowing_x = self.x_for_eval for i, _", "x, class_index): # computes gradient of the boundary for specified", "= tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s = x0+x1 self.out =", "axis=1)) def get_boundary_gradient(self, x, class_index): if not self.grad_session: self.grad_session =", "self.eval_session.run(self.out_for_eval, {self.x_for_eval: x}) def boundary_eval(self, x, class_index): # evaluates binary", "return self.boundary_loss[self.training_class_index] def get_hits(self): return self.get_loss() def get_count(self): return self.get_loss()", "methods from gtrain.Model def get_loss(self): if self.training_class_index is None: return", "tf.constant(self.weights[1][i], name=\"eBias_{}\".format(i)) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b), name=\"elayer_{}\".format(i)) y =", "= full_out[:,self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s =", "= None self.center = None self.weights = weights self.out_for_eval =", "filled in build method) self.x_for_eval = None self.out = None", "tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.initial_x))), dtype=tf.float64,", "x0 self.x1 = x1 def has_modified_loss(self): pass # if uses", "want to found the cosest point x0 self.x1 = x1", "x1/s], axis=1) self.boundary_out.append(out) with tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean( tf.nn.l2_loss(self.out-self.t), name=\"loss\")", "= use_modified_loss self.mu = mu def build(self): with tf.name_scope(\"Input\"): self.init_point", "x1_constant)) ) else: for i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] -", "None # list of tf tensorf for each class of", "tf.placeholder(tf.float64, shape=[None, self.num_classes], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_boundary_output\")", "HypINV rule extraction algorithm The task is simplified to the", "self.boundary_loss = None self.t = None #target self.boundary_t = None", "1: x = x.reshape((1,len(x))) if not self.eval_session: self.eval_session = tf.Session()", "def set_initial_x_in_session(self, x, session=None): if session is None: self.set_initial_x(x) else:", "None self.grad_session = None self.initial_x = None self.center = None", "/ np.linalg.norm(center) def set_x1(self, x1): # sets x1 to which", "tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() for i in range(self.num_classes): mask =", "self.x_for_eval for i, _ in enumerate(self.weights[0]): W = tf.constant(self.weights[0][i], name=\"eWeight_{}\".format(i))", ") else: for i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t))", "output self.loss = None self.boundary_loss = None self.t = None", "with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index]", "= self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def build_for_eval(self): # build", "for i in range(len(self.weights[0][-1][0])): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x = self.x_for_eval return", "with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() for i in range(self.num_classes): mask", "None self.x1 = None # this attribute is used of", "HypINV rule extraction algorithm \"\"\" def __init__(self, weights, function=tf.sigmoid, use_modified_loss=False,", "self.t = None #target self.boundary_t = None self.x1 = None", "def __init__(self, weights): self.eval_session = None self.grad_session = None self.initial_x", "to which we want to found the cosest point x0", "/ self.center[init_factor!=0] session.run(self.factor.assign(init_factor.reshape((1,len(init_factor))))) def build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval = tf.placeholder(tf.float32,", "len(self.x1))), dtype=tf.float64) self.t = tf.placeholder(tf.float64, shape=[None, self.num_classes], name=\"Target_output\") self.boundary_t =", "axis=1) s = x0+x1 self.out_for_eval = tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(self.out_for_eval)", "self.center[init_factor!=0] self.factor = tf.Variable(init_factor.reshape((1, len(self.center))), dtype=tf.float64, name=\"factor\") else: self.point_weights =", "= None # this attribute is used of purposes of", "len(self.x1))), dtype=tf.float64) self.t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_output\") self.boundary_t =", "self.center is not None: self.point_weights = tf.Variable(self.center.reshape((1, len(self.center))), dtype=tf.float64, trainable=False,", "self.layer_sizes])) class FCNetForHypinvBinary(FCNetForHypinv): \"\"\" Implementation of multi layer perceptron to", "def build(self): # build model for training pass #override this", "flowing_x self.out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() for", "tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(out) with tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean( tf.nn.l2_loss(self.out-self.t),", "boundary for specified class_index if not self.grad_session: self.grad_session = tf.Session()", "name=\"elayer_{}\".format(i)) y = flowing_x full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval", "self.trained_x = None self.training_class_index = None self.x = None #", "True+np.zeros(self.num_classes, dtype=np.bool) mask[i] = False x0 = self.out[:,i] x1 =", "sets initial x in certain session if session is None:", "an index of the class which is used as the", "= tf.Variable(init_factor.reshape((1, len(self.center))), dtype=tf.float64, name=\"factor\") else: self.point_weights = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))),", "in HypINV rule extraction algorithm \"\"\" def __init__(self, weights, function=tf.sigmoid,", "shape=[None, self.num_classes], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_boundary_output\") with", "None self.trained_x = None self.training_class_index = None self.x = None", "x1/s], axis=1) self.boundary_out_for_eval.append(out) def has_modified_loss(self): return self.use_modified_loss def name(self): return", "self.training_class_index is None: return [self.t] else: return [self.boundary_t] #________________________________________EXAMPLES_OF_NetForHypinv_CLASS_____________________________________________ class", "= True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] = False x0 = full_out[:, self.base_class_index]", "to be filled in build_for_eval method) self.boundary_out_for_eval = None self.trained_x", "True+np.zeros(self.num_classes, dtype=np.bool) mask[i] = False x0 = self.out_for_eval[:, i] x1", "tf.name_scope(\"Input\"): self.init_point = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor =", "= self.function(tf.nn.xw_plus_b(flowing_x, W, b), name=\"elayer_{}\".format(i)) y = flowing_x self.out_for_eval =", "= flowing_x full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list()", "init_factor[init_factor!=0] = x[init_factor!=0] / self.center[init_factor!=0] session.run(self.factor.assign(init_factor.reshape((1,len(init_factor))))) def build_for_eval(self): with tf.name_scope(\"eInput\"):", "= [len(self.weights[0][0])] for bias in weights[1]: self.layer_sizes.append(len(bias)) self.num_classes = self.layer_sizes[-1]", "= tf.constant(self.weights[0][i], name=\"Weight_{}\".format(i), dtype=tf.float64) b = tf.constant(self.weights[1][i], name=\"Bias_{}\".format(i), dtype=tf.float64) flowing_x", "list() if self.use_modified_loss: for i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) +", "algorithm The task is simplified to the binary classificaiton base_class_index", "__init__(self, weights, base_class_index, function=tf.sigmoid, use_modified_loss=False, mu = 0.01): \"\"\" :param", "tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant)) ) else: for", "self.boundary_out_for_eval.append(tf.stack([x1/s, x0/s], axis=1)) def get_boundary_gradient(self, x, class_index): if not self.grad_session:", "build model for evaluation pass #override this method (fill self.out_for_eval)", "other classes if not self.eval_session: self.eval_session = tf.Session() with self.eval_session.as_default():", "to by used in HypINV rule extraction algorithm \"\"\" def", "def __init__(self, weights, function=tf.sigmoid, use_modified_loss=False, mu = 0.01): \"\"\" :param", "if self.use_modified_loss: for i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu", "as tf class NetForHypinv(Model): \"\"\" Implementaion of the crutial function", "the class which is used as the base class :param", "dtype=tf.float64, name=\"factor\") else: self.point_weights = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\")", "in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant))", "used :param mu: factor of the penalty terms that specified", "modified loss should be used :param mu: factor of the", "the distance x1 from the boundary \"\"\" super(FCNetForHypinv, self).__init__(weights) self.function", "return self.loss else: return self.boundary_loss[self.training_class_index] def get_hits(self): return self.get_loss() def", "model for training pass #override this method (fill self.x, self.out)", "self.center is None: session.run([ self.point_weights.assign(x.reshape((1, len(x)))), self.factor.assign(np.ones((1, len(x)))) ]) else:", "x0/s], axis=1)) with tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean( tf.nn.l2_loss(self.out-self.t), name=\"loss\") with", "is None: self.set_initial_x(x) else: pass # overide this method def", "dtype=tf.float64) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b)) y = flowing_x self.out", "in range(len(self.weights[0][-1][0])): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x = self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x:", "x0 = self.out_for_eval[:, i] x1 = tf.reduce_max(tf.boolean_mask(self.out_for_eval, mask, axis=1), axis=1)", "is simplified to the binary classificaiton base_class_index against the other", ":param function: tf function for propagation. For example tf.nn.sigmoid, tf.atan", "mask, axis=1), axis=1) s = x0+x1 self.out_for_eval = tf.stack([x0/s, x1/s],", "base class :param function: tf function for propagation. For example", "class of softmax class vs others output self.loss = None", "self.build_for_eval() self.grad = list() for i in range(len(self.weights[0][-1][0])): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0])", "list() mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] = False x0 =", "this attribute is used of purposes of modified loss function", "of the crutial function for the HypINV algorithm. Warning: Do", "x1 = tf.reduce_max(tf.boolean_mask(self.out_for_eval, mask, axis=1), axis=1) s = x0+x1 out", "W, b)) y = flowing_x full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"):", "self.grad_session.as_default(): self.build_for_eval() self.grad = list() for i in range(2): self.grad.append(tf.gradients(self.boundary_out_for_eval[i],", "HypINV algorithm. Warning: Do not use this class but implement", "point for the search of the closest point self.initial_x =", "build model for training pass #override this method (fill self.x,", "tf.constant(self.x1.reshape((1, len(self.x1))), dtype=tf.float64) self.t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_output\") self.boundary_t", "= False x0 = self.out[:,i] x1 = tf.reduce_max(tf.boolean_mask(self.out, mask, axis=1),", "out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(out) with tf.name_scope(\"Loss_functions\"): self.loss =", "found the cosest point x0 self.x1 = x1 def has_modified_loss(self):", "name=\"eBias_{}\".format(i)) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b), name=\"elayer_{}\".format(i)) y = flowing_x", "in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def build_for_eval(self): with", "\"\"\" super(FCNetForHypinv, self).__init__(weights) self.function = function self.layer_sizes = [len(self.weights[0][0])] for", "tf.constant(self.weights[1][i], name=\"Bias_{}\".format(i), dtype=tf.float64) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b)) y =", "self.initial_x[init_factor!=0] / self.center[init_factor!=0] self.factor = tf.Variable(init_factor.reshape((1, len(self.center))), dtype=tf.float64, name=\"factor\") else:", "tf.Variable(np.ones((1, len(self.center))), dtype=tf.float64, name=\"factor\") self.x = self.point_weights * self.factor with", "return [] def get_placeholders(self): if self.training_class_index is None: return [self.t]", "to found the cosest point x0 self.x1 = x1 def", "self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.out_for_eval, {self.x_for_eval: x}) def boundary_eval(self, x, class_index):", "W, b)) y = flowing_x self.out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"):", "dtype=tf.float64, name=\"factor\") self.x = self.init_point * self.factor with tf.name_scope(\"Target\"): if", "mask[self.base_class_index] = False x0 = full_out[:,self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask,", "tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(self.out) self.boundary_out.append(tf.stack([x1/s, x0/s], axis=1)) with tf.name_scope(\"Loss_functions\"): self.loss", "len(self.center))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") init_factor = self.center init_factor[init_factor!=0] = self.initial_x[init_factor!=0]", "# list of tf tensorf for each class of softmax", "and other classes if not self.eval_session: self.eval_session = tf.Session() with", "self.training_class_index = class_index # overided methods from gtrain.Model def get_loss(self):", "self.boundary_out_for_eval.append(self.out_for_eval) self.boundary_out_for_eval.append(tf.stack([x1/s, x0/s], axis=1)) def get_boundary_gradient(self, x, class_index): if not", "= None #target self.boundary_t = None self.x1 = None #", "i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x -", "x}) def get_boundary_gradient(self, x, class_index): # computes gradient of the", "(fill self.out_for_eval) def train_ended(self, session): self.trained_x = session.run(self.x) def build(self):", "class FCNetForHypinv(NetForHypinv): \"\"\" Implementation of multi layer perceptron to by", "[self.x_for_eval])[0]) self.grad_x = self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def build_for_eval(self):", "= tf.constant(self.weights[1][i], name=\"eBias_{}\".format(i)) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b), name=\"elayer_{}\".format(i)) y", "weights[1]: self.layer_sizes.append(len(bias)) self.num_classes = self.layer_sizes[-1] self.initial_x = np.zeros([1, self.layer_sizes[0]]) self.use_modified_loss", "tf.name_scope(\"Binary_class_loss\"): self.boundary_loss = list() if self.use_modified_loss: for i in range(2):", "For example tf.nn.sigmoid, tf.atan :param use_modified_loss: weather the modified loss", "tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_boundary_output\") with tf.name_scope(\"FC_net\"): flowing_x = self.x for", "self.boundary_t)) ) def build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval = tf.placeholder(tf.float32, shape=[None,", "not use this class but implement its subclass, for example", "list() for i in range(len(self.weights[0][-1][0])): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x = self.x_for_eval", "by used in HypINV rule extraction algorithm \"\"\" def __init__(self,", "= x1 def has_modified_loss(self): pass # if uses modified loss", "is None: return self.loss else: return self.boundary_loss[self.training_class_index] def get_hits(self): return", "against the other classes \"\"\" def __init__(self, weights, base_class_index, function=tf.sigmoid,", "dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.initial_x))), dtype=tf.float64, name=\"factor\") self.x", "rule extraction algorithm \"\"\" def __init__(self, weights, function=tf.sigmoid, use_modified_loss=False, mu", "which we want to found the cosest point x0 self.x1", "flowing_x = self.x for i, _ in enumerate(self.weights[0]): with tf.name_scope(\"layer_{}\".format(i)):", "this method def eval(self, x): if len(x.shape) == 1: x", "tf.atan :param use_modified_loss: weather the modified loss should be used", "training pass #override this method (fill self.x, self.out) def set_train_class(self,", "if self.use_modified_loss: x1_constant = tf.constant(self.x1.reshape((1, len(self.x1))), dtype=tf.float64) self.t = tf.placeholder(tf.float64,", "#target self.boundary_t = None self.x1 = None # this attribute", "bias in weights[1]: self.layer_sizes.append(len(bias)) self.num_classes = self.layer_sizes[-1] self.initial_x = np.zeros([1,", "self.boundary_loss[self.training_class_index] def get_hits(self): return self.get_loss() def get_count(self): return self.get_loss() def", "len(self.center))), dtype=tf.float64, name=\"factor\") self.x = self.point_weights * self.factor with tf.name_scope(\"Target\"):", "in enumerate(self.weights[0]): with tf.name_scope(\"layer_{}\".format(i)): W = tf.constant(self.weights[0][i], name=\"Weight_{}\".format(i), dtype=tf.float64) b", "name=\"loss\") with tf.name_scope(\"Binary_class_loss\"): self.boundary_loss = list() if self.use_modified_loss: for i", "get_count(self): return self.get_loss() def get_train_summaries(self): return [] def get_dev_summaries(self): return", "weights, function=tf.sigmoid, use_modified_loss=False, mu = 0.01): \"\"\" :param weights: saved", "build method) self.x_for_eval = None self.out = None self.boundary_out =", "in self.layer_sizes])) class FCNetForHypinvBinary(FCNetForHypinv): \"\"\" Implementation of multi layer perceptron", "set_initial_x(self, initial_x): # sets starting point for the search of", "len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.initial_x))), dtype=tf.float64, name=\"factor\")", "self.t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64, shape=[None,", "function for the HypINV algorithm. Warning: Do not use this", "self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def build_for_eval(self): # build model", "False x0 = self.out_for_eval[:, i] x1 = tf.reduce_max(tf.boolean_mask(self.out_for_eval, mask, axis=1),", "tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] =", "tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s = x0+x1 self.out = tf.stack([x0/s,", "= initial_x def set_center(self, center): # sets center point self.center", "with tf.name_scope(\"Binary_class_loss\"): self.boundary_loss = list() if self.use_modified_loss: for i in", "sets x1 to which we want to found the cosest", "self.x1 = None # this attribute is used of purposes", "with self.grad_session.as_default(): self.build_for_eval() self.grad = list() for i in range(2):", "has_modified_loss(self): return self.use_modified_loss def name(self): return \"Hypinv_FC_net_{}\".format(\"-\".join([str(ls) for ls in", "class_index): # sets class of the x1 self.training_class_index = class_index", "class_index # overided methods from gtrain.Model def get_loss(self): if self.training_class_index", "if self.grad_session: self.grad_session.close() def set_initial_x(self, initial_x): # sets starting point", "W, b), name=\"elayer_{}\".format(i)) y = flowing_x self.out_for_eval = tf.nn.softmax(y) with", "for inversion (going to be filled in build method) self.x_for_eval", "this method (fill self.x, self.out) def set_train_class(self, class_index): # sets", "use_modified_loss self.mu = mu def build(self): with tf.name_scope(\"Input\"): if self.center", "perceptron to by used in HypINV rule extraction algorithm The", "propagation. For example tf.nn.sigmoid, tf.atan :param use_modified_loss: weather the modified", "= True+np.zeros(self.num_classes, dtype=np.bool) mask[i] = False x0 = self.out_for_eval[:, i]", "b = tf.constant(self.weights[1][i], name=\"Bias_{}\".format(i), dtype=tf.float64) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b))", "index of the class which is used as the base", "be filled in build method) self.x_for_eval = None self.out =", "tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() for i in range(self.num_classes): mask =", "Implementaion of the crutial function for the HypINV algorithm. Warning:", "y = flowing_x full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out =", "name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_boundary_output\") with tf.name_scope(\"FC_net\"): flowing_x", "init_factor[init_factor!=0] = self.initial_x[init_factor!=0] / self.center[init_factor!=0] self.factor = tf.Variable(init_factor.reshape((1, len(self.center))), dtype=tf.float64,", "class_index if not self.grad_session: self.grad_session = tf.Session() with self.grad_session.as_default(): self.build_for_eval()", "tf.Variable(self.center.reshape((1, len(self.center))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") init_factor = self.center init_factor[init_factor!=0] =", "the binary classificaiton base_class_index against the other classes \"\"\" def", "self.boundary_out_for_eval = list() for i in range(self.num_classes): mask = True+np.zeros(self.num_classes,", "self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x = self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def", "center point self.center = center / np.linalg.norm(center) def set_x1(self, x1):", "== 1: x = x.reshape((1,len(x))) if not self.eval_session: self.eval_session =", "use_modified_loss=False, mu = 0.01): \"\"\" :param weights: saved as [list", "class NetForHypinv(Model): \"\"\" Implementaion of the crutial function for the", "function: tf function for propagation. For example tf.nn.sigmoid, tf.atan :param", "overide this method def eval(self, x): if len(x.shape) == 1:", "= mu def build(self): with tf.name_scope(\"Input\"): if self.center is not", "trainable=False, name=\"Boundary_point\") init_factor = self.center init_factor[init_factor!=0] = self.initial_x[init_factor!=0] / self.center[init_factor!=0]", "self.out_for_eval = tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(self.out_for_eval) self.boundary_out_for_eval.append(tf.stack([x1/s, x0/s], axis=1)) def", "1 bias] :param function: tf function for propagation. For example", "with tf.name_scope(\"eFC_net\"): flowing_x = self.x_for_eval for i, _ in enumerate(self.weights[0]):", "#override this method (fill self.x, self.out) def set_train_class(self, class_index): #", "is used of purposes of modified loss function def __del__(self):", "self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.out_for_eval, {self.x_for_eval: x}) def boundary_eval(self, x,", "x}) def build_for_eval(self): # build model for evaluation pass #override", "search of the closest point self.initial_x = initial_x def set_center(self,", "starting point for the search of the closest point self.initial_x", "tf function for propagation. For example tf.nn.sigmoid, tf.atan :param use_modified_loss:", "tf.placeholder(tf.float32, shape=[None, len(self.weights[0][0])])#tf.Variable(tf.constant(self.initial_x), name=\"Boundary_point\") with tf.name_scope(\"eFC_net\"): flowing_x = self.x_for_eval for", "- x1_constant)) ) else: for i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]", "tensorf for each class of softmax class vs others output", "self.boundary_out.append(tf.stack([x1/s, x0/s], axis=1)) with tf.name_scope(\"Loss_functions\"): self.loss = tf.reduce_mean( tf.nn.l2_loss(self.out-self.t), name=\"loss\")", "# sets starting point for the search of the closest", "= tf.reduce_max(tf.boolean_mask(self.out, mask, axis=1), axis=1) s = x0+x1 out =", "self.boundary_out_for_eval = list() mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] = False", "FCNetForHypinv \"\"\" def __init__(self, weights): self.eval_session = None self.grad_session =", "\"\"\" super(FCNetForHypinvBinary, self).__init__(weights) self.base_class_index = base_class_index self.function = function self.layer_sizes", "in range(2): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x = self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x:", "eval(self, x): if len(x.shape) == 1: x = x.reshape((1,len(x))) if", "= None self.t = None #target self.boundary_t = None self.x1", "self.init_point * self.factor with tf.name_scope(\"Target\"): if self.use_modified_loss: x1_constant = tf.constant(self.x1.reshape((1,", "vs others output self.loss = None self.boundary_loss = None self.t", "= center / np.linalg.norm(center) def set_x1(self, x1): # sets x1", "2], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_boundary_output\") with tf.name_scope(\"FC_net\"):", "None self.t = None #target self.boundary_t = None self.x1 =", "self.initial_x = initial_x def set_center(self, center): # sets center point", "else: self.point_weights = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor =", "base_class_index: an index of the class which is used as", "this class but implement its subclass, for example see FCNetForHypinv", "modified loss function def __del__(self): # close arr sessions if", "tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() mask = True+np.zeros(self.num_classes, dtype=np.bool)", "function def __del__(self): # close arr sessions if self.eval_session: self.eval_session.close()", "ls in self.layer_sizes])) class FCNetForHypinvBinary(FCNetForHypinv): \"\"\" Implementation of multi layer", "bias] :param base_class_index: an index of the class which is", "+ self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant)) ) else: for i", "= self.function(tf.nn.xw_plus_b(flowing_x, W, b)) y = flowing_x full_out = tf.nn.softmax(y)", "i in range(len(self.weights[0][-1][0])): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x = self.x_for_eval return self.grad_session.run(self.grad[class_index],", "name=\"elayer_{}\".format(i)) y = flowing_x self.out_for_eval = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval", "\"\"\" def __init__(self, weights, base_class_index, function=tf.sigmoid, use_modified_loss=False, mu = 0.01):", "mu = 0.01): \"\"\" :param weights: saved as [list of", "= tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64, shape=[None, 2],", "name(self): return \"Hypinv_FC_net_{}\".format(\"-\".join([str(ls) for ls in self.layer_sizes])) class FCNetForHypinvBinary(FCNetForHypinv): \"\"\"", "if self.training_class_index is None: return self.loss else: return self.boundary_loss[self.training_class_index] def", "None self.center = None self.weights = weights self.out_for_eval = None", "dtype=tf.float64, trainable=False, name=\"Boundary_point\") self.factor = tf.Variable(np.ones((1, len(self.center))), dtype=tf.float64, name=\"factor\") self.x", "self.x1 = x1 def has_modified_loss(self): pass # if uses modified", "tf.name_scope(\"FC_net\"): flowing_x = self.x for i, _ in enumerate(self.weights[0]): with", ":param use_modified_loss: weather the modified loss should be used :param", "None self.boundary_out = None # list of tf tensorf for", "class_index and other classes if not self.eval_session: self.eval_session = tf.Session()", "model for evaluation pass #override this method (fill self.out_for_eval) def", "# sets initial x in certain session if session is", "def set_center(self, center): # sets center point self.center = center", "in certain session if session is None: self.set_initial_x(x) else: pass", "for bias in weights[1]: self.layer_sizes.append(len(bias)) self.num_classes = self.layer_sizes[-1] self.initial_x =", "len(self.center))), dtype=tf.float64, name=\"factor\") else: self.point_weights = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False,", "evaluates binary classificaitons class_index and other classes if not self.eval_session:", "self.t = tf.placeholder(tf.float64, shape=[None, self.num_classes], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64, shape=[None,", "i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def set_initial_x_in_session(self,", "flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b), name=\"elayer_{}\".format(i)) y = flowing_x self.out_for_eval", "def __init__(self, weights, base_class_index, function=tf.sigmoid, use_modified_loss=False, mu = 0.01): \"\"\"", "method def eval(self, x): if len(x.shape) == 1: x =", "return self.eval_session.run(self.out_for_eval, {self.x_for_eval: x}) def boundary_eval(self, x, class_index): # evaluates", "for ls in self.layer_sizes])) class FCNetForHypinvBinary(FCNetForHypinv): \"\"\" Implementation of multi", "axis=1) self.boundary_out_for_eval.append(self.out_for_eval) self.boundary_out_for_eval.append(tf.stack([x1/s, x0/s], axis=1)) def get_boundary_gradient(self, x, class_index): if", "computes gradient of the boundary for specified class_index if not", "def set_initial_x(self, initial_x): # sets starting point for the search", "initial_x): # sets starting point for the search of the", "center / np.linalg.norm(center) def set_x1(self, x1): # sets x1 to", ":param weights: saved as [list of weights for layers][0 weight,", "mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] = False x0 = full_out[:,self.base_class_index]", "b)) y = flowing_x self.out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out", "- self.boundary_t)) ) def build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval = tf.placeholder(tf.float32,", "= None self.x1 = None # this attribute is used", "def __del__(self): # close arr sessions if self.eval_session: self.eval_session.close() if", "tf.nn.sigmoid, tf.atan :param use_modified_loss: weather the modified loss should be", "def get_dev_summaries(self): return [] def get_placeholders(self): if self.training_class_index is None:", "in enumerate(self.weights[0]): W = tf.constant(self.weights[0][i], name=\"eWeight_{}\".format(i)) b = tf.constant(self.weights[1][i], name=\"eBias_{}\".format(i))", "1 bias] :param base_class_index: an index of the class which", "the modified loss should be used :param mu: factor of", "= mu def build(self): with tf.name_scope(\"Input\"): self.init_point = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))),", "for each class of softmax class vs others output self.loss", "of softmax class vs others output self.loss = None self.boundary_loss", "= self.x for i, _ in enumerate(self.weights[0]): with tf.name_scope(\"layer_{}\".format(i)): W", "from the boundary \"\"\" super(FCNetForHypinv, self).__init__(weights) self.function = function self.layer_sizes", "class which is used as the base class :param function:", "flowing_x full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out = list() mask", "range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x - x1_constant)) )", "from the boundary \"\"\" super(FCNetForHypinvBinary, self).__init__(weights) self.base_class_index = base_class_index self.function", "numpy as np import tensorflow as tf class NetForHypinv(Model): \"\"\"", "else: for i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) )", "#________________________________________EXAMPLES_OF_NetForHypinv_CLASS_____________________________________________ class FCNetForHypinv(NetForHypinv): \"\"\" Implementation of multi layer perceptron to", "= tf.constant(self.weights[1][i], name=\"Bias_{}\".format(i), dtype=tf.float64) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b)) y", "tf.name_scope(\"eFC_net\"): flowing_x = self.x_for_eval for i, _ in enumerate(self.weights[0]): W", "layers][0 weight, 1 bias] :param function: tf function for propagation.", "for i, _ in enumerate(self.weights[0]): with tf.name_scope(\"layer_{}\".format(i)): W = tf.constant(self.weights[0][i],", "self.out = None self.boundary_out = None # list of tf", "= self.out[:,i] x1 = tf.reduce_max(tf.boolean_mask(self.out, mask, axis=1), axis=1) s =", "axis=1) s = x0+x1 out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(out)", "self.boundary_out = list() for i in range(self.num_classes): mask = True+np.zeros(self.num_classes,", "used as the base class :param function: tf function for", "name=\"Target_boundary_output\") with tf.name_scope(\"FC_net\"): flowing_x = self.x for i, _ in", "point self.center = center / np.linalg.norm(center) def set_x1(self, x1): #", "{self.x_for_eval: x}) def get_boundary_gradient(self, x, class_index): # computes gradient of", "self.out_for_eval = None #(going to be filled in build_for_eval method)", "is None: self.set_initial_x(x) else: if self.center is None: session.run([ self.point_weights.assign(x.reshape((1,", "self.boundary_out_for_eval.append(out) def has_modified_loss(self): return self.use_modified_loss def name(self): return \"Hypinv_FC_net_{}\".format(\"-\".join([str(ls) for", "which is used as the base class :param function: tf", "use_modified_loss: weather the modified loss should be used :param mu:", "with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() for i in range(self.num_classes): mask", "Implementation of multi layer perceptron to by used in HypINV", "FCNetForHypinvBinary(FCNetForHypinv): \"\"\" Implementation of multi layer perceptron to by used", "not None: self.point_weights = tf.Variable(self.center.reshape((1, len(self.center))), dtype=tf.float64, trainable=False, name=\"Boundary_point\") init_factor", "if self.use_modified_loss: for i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu", "x1 from the boundary \"\"\" super(FCNetForHypinv, self).__init__(weights) self.function = function", "used of purposes of modified loss function def __del__(self): #", "variable for inversion (going to be filled in build method)", "x1 = tf.reduce_max(tf.boolean_mask(self.out, mask, axis=1), axis=1) s = x0+x1 out", "= x.reshape((1,len(x))) if not self.eval_session: self.eval_session = tf.Session() with self.eval_session.as_default():", "self.set_initial_x(x) else: if self.center is None: session.run([ self.point_weights.assign(x.reshape((1, len(x)))), self.factor.assign(np.ones((1,", "name=\"eWeight_{}\".format(i)) b = tf.constant(self.weights[1][i], name=\"eBias_{}\".format(i)) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b),", "axis=1) s = x0+x1 self.out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(self.out)", "= tf.constant(self.x1.reshape((1, len(self.x1))), dtype=tf.float64) self.t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_output\")", "self.grad_session.close() def set_initial_x(self, initial_x): # sets starting point for the", "enumerate(self.weights[0]): W = tf.constant(self.weights[0][i], name=\"eWeight_{}\".format(i)) b = tf.constant(self.weights[1][i], name=\"eBias_{}\".format(i)) flowing_x", "for the HypINV algorithm. Warning: Do not use this class", "{self.x_for_eval: x}) def boundary_eval(self, x, class_index): # evaluates binary classificaitons", "see FCNetForHypinv \"\"\" def __init__(self, weights): self.eval_session = None self.grad_session", "return [] def get_dev_summaries(self): return [] def get_placeholders(self): if self.training_class_index", "self.initial_x = np.zeros([1, self.layer_sizes[0]]) self.use_modified_loss = use_modified_loss self.mu = mu", ") def set_initial_x_in_session(self, x, session=None): if session is None: self.set_initial_x(x)", "s = x0+x1 out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(out) def", ") else: for i in range(self.num_classes): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t))", "b), name=\"elayer_{}\".format(i)) y = flowing_x self.out_for_eval = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"):", "self.grad_session.as_default(): self.build_for_eval() self.grad = list() for i in range(len(self.weights[0][-1][0])): self.grad.append(tf.gradients(self.boundary_out_for_eval[i],", "as [list of weights for layers][0 weight, 1 bias] :param", "the boundary for specified class_index if not self.grad_session: self.grad_session =", "for layers][0 weight, 1 bias] :param base_class_index: an index of", "specified the distance between x0 and x1 and the distance", "\"\"\" def __init__(self, weights, function=tf.sigmoid, use_modified_loss=False, mu = 0.01): \"\"\"", "# sets class of the x1 self.training_class_index = class_index #", "self.function = function self.layer_sizes = [len(self.weights[0][0])] for bias in weights[1]:", "flowing_x self.out_for_eval = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list() for", "i] x1 = tf.reduce_max(tf.boolean_mask(self.out_for_eval, mask, axis=1), axis=1) s = x0+x1", "[self.boundary_t] #________________________________________EXAMPLES_OF_NetForHypinv_CLASS_____________________________________________ class FCNetForHypinv(NetForHypinv): \"\"\" Implementation of multi layer perceptron", "self.x_for_eval = None self.out = None self.boundary_out = None #", "use this class but implement its subclass, for example see", "def build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval = tf.placeholder(tf.float32, shape=[None, len(self.weights[0][0])])#tf.Variable(tf.constant(self.initial_x), name=\"Boundary_point\")", "None self.training_class_index = None self.x = None # tf variable", "extraction algorithm The task is simplified to the binary classificaiton", "x, class_index): # evaluates binary classificaitons class_index and other classes", "return self.get_loss() def get_count(self): return self.get_loss() def get_train_summaries(self): return []", "tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_boundary_output\")", "= None self.initial_x = None self.center = None self.weights =", "example tf.nn.sigmoid, tf.atan :param use_modified_loss: weather the modified loss should", "of the penalty terms that specified the distance between x0", "then it returns true def set_initial_x_in_session(self, x, session=None): # sets", "build_for_eval(self): with tf.name_scope(\"eInput\"): self.x_for_eval = tf.placeholder(tf.float32, shape=[None, len(self.weights[0][0])])#tf.Variable(tf.constant(self.initial_x), name=\"Boundary_point\") with", "point x0 self.x1 = x1 def has_modified_loss(self): pass # if", "algorithm. Warning: Do not use this class but implement its", "else: pass # overide this method def eval(self, x): if", "= class_index # overided methods from gtrain.Model def get_loss(self): if", "return \"Hypinv_FC_net_{}\".format(\"-\".join([str(ls) for ls in self.layer_sizes])) class FCNetForHypinvBinary(FCNetForHypinv): \"\"\" Implementation", "self.point_weights.assign(x.reshape((1, len(x)))), self.factor.assign(np.ones((1, len(x)))) ]) else: init_factor = self.center init_factor[init_factor!=0]", "certain session if session is None: self.set_initial_x(x) else: pass #", "self.boundary_out = None # list of tf tensorf for each", "= tf.Session() with self.eval_session.as_default(): self.build_for_eval() self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.out_for_eval, {self.x_for_eval: x})", "example see FCNetForHypinv \"\"\" def __init__(self, weights): self.eval_session = None", "of the boundary for specified class_index if not self.grad_session: self.grad_session", "= x0+x1 out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(out) def has_modified_loss(self):", "def build(self): with tf.name_scope(\"Input\"): if self.center is not None: self.point_weights", "\"\"\" def __init__(self, weights): self.eval_session = None self.grad_session = None", "range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def build_for_eval(self): with tf.name_scope(\"eInput\"):", "range(self.num_classes): mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[i] = False x0 =", "and x1 and the distance x1 from the boundary \"\"\"", "dtype=tf.float64) flowing_x = self.function(tf.nn.xw_plus_b(flowing_x, W, b)) y = flowing_x full_out", "for i in range(2): self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i]-self.boundary_t)) + self.mu * tf.reduce_mean(tf.nn.l2_loss(self.x", "self.boundary_t)) ) def set_initial_x_in_session(self, x, session=None): if session is None:", "between x0 and x1 and the distance x1 from the", "class vs others output self.loss = None self.boundary_loss = None", "(going to be filled in build method) self.x_for_eval = None", "range(2): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x = self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x: x})", "and the distance x1 from the boundary \"\"\" super(FCNetForHypinvBinary, self).__init__(weights)", "= tf.placeholder(tf.float64, shape=[None, 2], name=\"Target_boundary_output\") with tf.name_scope(\"FC_net\"): flowing_x = self.x", "tf.stack([x0/s, x1/s], axis=1) self.boundary_out_for_eval.append(self.out_for_eval) self.boundary_out_for_eval.append(tf.stack([x1/s, x0/s], axis=1)) def get_boundary_gradient(self, x,", "import Model import numpy as np import tensorflow as tf", "x1/s], axis=1) self.boundary_out.append(self.out) self.boundary_out.append(tf.stack([x1/s, x0/s], axis=1)) with tf.name_scope(\"Loss_functions\"): self.loss =", "the x1 self.training_class_index = class_index # overided methods from gtrain.Model", "evaluation pass #override this method (fill self.out_for_eval) def train_ended(self, session):", "x1 to which we want to found the cosest point", "else: init_factor = self.center init_factor[init_factor!=0] = x[init_factor!=0] / self.center[init_factor!=0] session.run(self.factor.assign(init_factor.reshape((1,len(init_factor)))))", "simplified to the binary classificaiton base_class_index against the other classes", "import tensorflow as tf class NetForHypinv(Model): \"\"\" Implementaion of the", "to the binary classificaiton base_class_index against the other classes \"\"\"", "mask, axis=1), axis=1) s = x0+x1 self.out = tf.stack([x0/s, x1/s],", "has_modified_loss(self): pass # if uses modified loss then it returns", "None self.out = None self.boundary_out = None # list of", "mask[self.base_class_index] = False x0 = full_out[:, self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out,", "= self.point_weights * self.factor with tf.name_scope(\"Target\"): if self.use_modified_loss: x1_constant =", "False x0 = full_out[:, self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1),", "self.x = None # tf variable for inversion (going to", "s = x0+x1 out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(out) with", "self.training_class_index = None self.x = None # tf variable for", "specified class_index if not self.grad_session: self.grad_session = tf.Session() with self.grad_session.as_default():", "build_for_eval method) self.boundary_out_for_eval = None self.trained_x = None self.training_class_index =", "= self.init_point * self.factor with tf.name_scope(\"Target\"): if self.use_modified_loss: x1_constant =", "x0+x1 out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(out) with tf.name_scope(\"Loss_functions\"): self.loss", "self.grad = list() for i in range(2): self.grad.append(tf.gradients(self.boundary_out_for_eval[i], [self.x_for_eval])[0]) self.grad_x", "{self.grad_x: x}) def has_modified_loss(self): return self.use_modified_loss def name(self): return \"Hypinv_FC_net_{}\".format(\"-\".join([str(ls)", "self.eval_session.run(tf.global_variables_initializer()) return self.eval_session.run(self.out_for_eval, {self.x_for_eval: x}) def boundary_eval(self, x, class_index): #", "W = tf.constant(self.weights[0][i], name=\"Weight_{}\".format(i), dtype=tf.float64) b = tf.constant(self.weights[1][i], name=\"Bias_{}\".format(i), dtype=tf.float64)", "self.center = center / np.linalg.norm(center) def set_x1(self, x1): # sets", "= True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] = False x0 = full_out[:,self.base_class_index] x1", "build(self): # build model for training pass #override this method", "b), name=\"elayer_{}\".format(i)) y = flowing_x full_out = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"):", "x1/s], axis=1) self.boundary_out_for_eval.append(self.out_for_eval) self.boundary_out_for_eval.append(tf.stack([x1/s, x0/s], axis=1)) def get_boundary_gradient(self, x, class_index):", "attribute is used of purposes of modified loss function def", "dtype=np.bool) mask[self.base_class_index] = False x0 = full_out[:,self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out,", "x = x.reshape((1,len(x))) if not self.eval_session: self.eval_session = tf.Session() with", "= weights self.out_for_eval = None #(going to be filled in", "self.trained_x = session.run(self.x) def build(self): # build model for training", "= list() mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[self.base_class_index] = False x0", "penalty terms that specified the distance between x0 and x1", "x1 and the distance x1 from the boundary \"\"\" super(FCNetForHypinv,", "_ in enumerate(self.weights[0]): W = tf.constant(self.weights[0][i], name=\"eWeight_{}\".format(i)) b = tf.constant(self.weights[1][i],", "axis=1) self.boundary_out_for_eval.append(out) def has_modified_loss(self): return self.use_modified_loss def name(self): return \"Hypinv_FC_net_{}\".format(\"-\".join([str(ls)", "filled in build_for_eval method) self.boundary_out_for_eval = None self.trained_x = None", "self.mu = mu def build(self): with tf.name_scope(\"Input\"): self.init_point = tf.Variable(self.initial_x.reshape((1,", "that specified the distance between x0 and x1 and the", "self.grad_x = self.x_for_eval return self.grad_session.run(self.grad[class_index], {self.grad_x: x}) def build_for_eval(self): #", "sessions if self.eval_session: self.eval_session.close() if self.grad_session: self.grad_session.close() def set_initial_x(self, initial_x):", "dtype=tf.float64) self.t = tf.placeholder(tf.float64, shape=[None, self.num_classes], name=\"Target_output\") self.boundary_t = tf.placeholder(tf.float64,", "of the class which is used as the base class", "self.grad_session = None self.initial_x = None self.center = None self.weights", "multi layer perceptron to by used in HypINV rule extraction", "the boundary \"\"\" super(FCNetForHypinvBinary, self).__init__(weights) self.base_class_index = base_class_index self.function =", "if not self.grad_session: self.grad_session = tf.Session() with self.grad_session.as_default(): self.build_for_eval() self.grad", "tf.Session() with self.grad_session.as_default(): self.build_for_eval() self.grad = list() for i in", "= self.initial_x[init_factor!=0] / self.center[init_factor!=0] self.factor = tf.Variable(init_factor.reshape((1, len(self.center))), dtype=tf.float64, name=\"factor\")", "= x0+x1 out = tf.stack([x0/s, x1/s], axis=1) self.boundary_out.append(out) with tf.name_scope(\"Loss_functions\"):", "def build(self): with tf.name_scope(\"Input\"): self.init_point = tf.Variable(self.initial_x.reshape((1, len(self.initial_x))), dtype=tf.float64, trainable=False,", "= flowing_x self.out_for_eval = tf.nn.softmax(y) with tf.name_scope(\"Binary_class_output\"): self.boundary_out_for_eval = list()", "= False x0 = full_out[:, self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask,", "sets class of the x1 self.training_class_index = class_index # overided", "full_out[:, self.base_class_index] x1 = tf.reduce_max(tf.boolean_mask(full_out, mask, axis=1), axis=1) s =", "get_dev_summaries(self): return [] def get_placeholders(self): if self.training_class_index is None: return", "Model import numpy as np import tensorflow as tf class", "weights for layers][0 weight, 1 bias] :param function: tf function", "class but implement its subclass, for example see FCNetForHypinv \"\"\"", "self.boundary_loss.append( tf.reduce_mean(tf.nn.l2_loss(self.boundary_out[i] - self.boundary_t)) ) def set_initial_x_in_session(self, x, session=None): if", "self.boundary_loss = list() if self.use_modified_loss: for i in range(2): self.boundary_loss.append(", "weather the modified loss should be used :param mu: factor", "in range(self.num_classes): mask = True+np.zeros(self.num_classes, dtype=np.bool) mask[i] = False x0", "set_x1(self, x1): # sets x1 to which we want to", "the base class :param function: tf function for propagation. For", "return [self.t] else: return [self.boundary_t] #________________________________________EXAMPLES_OF_NetForHypinv_CLASS_____________________________________________ class FCNetForHypinv(NetForHypinv): \"\"\" Implementation", "__init__(self, weights): self.eval_session = None self.grad_session = None self.initial_x =" ]
[ "import Method class getChatMember(Method): chat_id = None # type: \"int53\"", "getChatMember(Method): chat_id = None # type: \"int53\" user_id = None", "from ..factory import Method class getChatMember(Method): chat_id = None #", "..factory import Method class getChatMember(Method): chat_id = None # type:", "chat_id = None # type: \"int53\" user_id = None #", "Method class getChatMember(Method): chat_id = None # type: \"int53\" user_id", "None # type: \"int53\" user_id = None # type: \"int32\"", "class getChatMember(Method): chat_id = None # type: \"int53\" user_id =", "= None # type: \"int53\" user_id = None # type:" ]
[ "10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o':", "= tokenizer.texts_to_sequences(self.test_phrases) x_train = sequence.pad_sequences(x_train_sequence, maxlen=word_max_length, padding='post', truncating='post') x_test =", "'~': 57, '`': 58, '+': 59, '=': 61, '<': 62,", "def _read_train_phrases(self): pass def _read_test_phrases(self): pass class Phrase: def __init__(self,", "texts): vector_sequence = self.get_tokenizer().texts_to_sequences(texts) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post')", "dtype='int64') y_train = numpy.array(self.train_labels, dtype='float32') x_test = [] for i", "49, '@': 50, '#': 51, '$': 52, '%': 53, '^':", "'/': 46, '\\\\': 47, '|': 48, '_': 49, '@': 50,", "== support.WORD_LEVEL: return self._word_process(self.configuration[support.WORD_MAX_LENGTH]) elif level == support.CHAR_LEVEL: return self._char_process(self.configuration[support.CHAR_MAX_LENGTH])", "y_train, x_test, y_test def _doc_process(self, doc, embedding_dic, max_length): min_length =", "= numpy.asarray(result, dtype=\"int64\") del embedding_w, embedding_dic return result def _get_embedding_dictionary(self):", "numpy.array(self.test_labels) return x_train, y_train, x_test, y_test def _char_process(self, max_length): embedding_w,", "in range(len(self.train_phrases)): doc_vec = self._doc_process(self.train_phrases[i].lower(), embedding_dic, max_length) x_train.append(doc_vec) x_train =", "for j in range(min_length): if doc[j] in embedding_dic: doc_vec[j] =", "= numpy.zeros(max_length, dtype=\"int64\") for j in range(min_length): if text[j] in", "self.classification = classification def __str__(self): return \"Classification: \" + str(self.classification)", "class PhraseManager: def __init__(self, configuration): self.train_phrases, self.train_labels = self._read_train_phrases() self.test_phrases,", "= self._onehot_dic_build() x_train = [] for i in range(len(self.train_phrases)): doc_vec", "50, '#': 51, '$': 52, '%': 53, '^': 54, '&':", "from keras.preprocessing.text import Tokenizer from src.support import support class PhraseManager:", "= tokenizer.texts_to_sequences(self.train_phrases) x_test_sequence = tokenizer.texts_to_sequences(self.test_phrases) x_train = sequence.pad_sequences(x_train_sequence, maxlen=word_max_length, padding='post',", "'.': 40, '!': 41, '?': 42, ':': 43, \"'\": 44,", "in range(len(texts)): doc_vec = self.text_to_vector_char(texts[i].lower()) result.append(doc_vec) result = numpy.asarray(result, dtype=\"int64\")", "max_length): embedding_w, embedding_dic = self._onehot_dic_build() x_train = [] for i", "enumerate(alphabet): onehot = numpy.zeros(len(alphabet), dtype='float32') embedding_dic[alpha] = i + 1", "return result def _get_embedding_dictionary(self): return {'UNK': 0, 'a': 1, 'b':", "'8': 35, '9': 36, '-': 60, ',': 38, ';': 39,", "\"'\": 44, '\"': 45, '/': 46, '\\\\': 47, '|': 48,", "text[j] in embedding_dictionary: text_vector[j] = embedding_dictionary[text[j]] else: text_vector[j] = embedding_dictionary[\"UNK\"]", "x_test = sequence.pad_sequences(x_test_sequence, maxlen=word_max_length, padding='post', truncating='post') y_train = numpy.array(self.train_labels) y_test", "= numpy.zeros(len(alphabet), dtype='float32') embedding_dic[alpha] = i + 1 onehot[i] =", "= embedding_dictionary[text[j]] else: text_vector[j] = embedding_dictionary[\"UNK\"] return text_vector def text_to_vector_char_all(self,", "in range(min_length): if text[j] in embedding_dictionary: text_vector[j] = embedding_dictionary[text[j]] else:", "return text_vector def text_to_vector_char_all(self, texts): embedding_w, embedding_dic = self._onehot_dic_build() result", "'!': 41, '?': 42, ':': 43, \"'\": 44, '\"': 45,", "self.train_phrases, self.train_labels = self._read_train_phrases() self.test_phrases, self.test_labels = self._read_test_phrases() self.configuration =", "= sequence.pad_sequences(x_test_sequence, maxlen=word_max_length, padding='post', truncating='post') y_train = numpy.array(self.train_labels) y_test =", "'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6,", "j in range(min_length): if text[j] in embedding_dictionary: text_vector[j] = embedding_dictionary[text[j]]", "56, '~': 57, '`': 58, '+': 59, '=': 61, '<':", "range(min_length): if doc[j] in embedding_dic: doc_vec[j] = embedding_dic[doc[j]] else: doc_vec[j]", "is None: self.tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) self.tokenizer.fit_on_texts(self.train_phrases) return self.tokenizer def text_to_vector_word(self,", "= numpy.array(embedding_w, dtype='float32') return embedding_w, embedding_dic def get_tokenizer(self): if self.tokenizer", "self.test_labels def get_dataset(self, level = None): if level == support.WORD_LEVEL:", "return \"Classification: \" + str(self.classification) + \"\\nText: \" + self.text", "import support class PhraseManager: def __init__(self, configuration): self.train_phrases, self.train_labels =", "classification): self.text = text self.classification = classification def __str__(self): return", "embedding_dictionary[text[j]] else: text_vector[j] = embedding_dictionary[\"UNK\"] return text_vector def text_to_vector_char_all(self, texts):", "embedding_dictionary: text_vector[j] = embedding_dictionary[text[j]] else: text_vector[j] = embedding_dictionary[\"UNK\"] return text_vector", "9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n':", "69} def get_classes(self): pass def _read_train_phrases(self): pass def _read_test_phrases(self): pass", "doc[j] in embedding_dic: doc_vec[j] = embedding_dic[doc[j]] else: doc_vec[j] = embedding_dic['UNK']", "sequence from keras.preprocessing.text import Tokenizer from src.support import support class", "word_max_length): tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) tokenizer.fit_on_texts(self.train_phrases) x_train_sequence = tokenizer.texts_to_sequences(self.train_phrases) x_test_sequence =", "'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12,", "x_test, y_test def _char_process(self, max_length): embedding_w, embedding_dic = self._onehot_dic_build() x_train", "dtype=\"int64\") del embedding_w, embedding_dic return result def _get_embedding_dictionary(self): return {'UNK':", "if text[j] in embedding_dictionary: text_vector[j] = embedding_dictionary[text[j]] else: text_vector[j] =", "self.text = text self.classification = classification def __str__(self): return \"Classification:", "embedding_w = numpy.array(embedding_w, dtype='float32') return embedding_w, embedding_dic def get_tokenizer(self): if", "48, '_': 49, '@': 50, '#': 51, '$': 52, '%':", "max_length) x_test.append(doc_vec) x_test = numpy.asarray(x_test, dtype='int64') y_test = numpy.array(self.test_labels, dtype='float32')", "'+': 59, '=': 61, '<': 62, '>': 63, '(': 64,", "= sequence.pad_sequences(x_train_sequence, maxlen=word_max_length, padding='post', truncating='post') x_test = sequence.pad_sequences(x_test_sequence, maxlen=word_max_length, padding='post',", "= 1 embedding_w.append(onehot) embedding_w = numpy.array(embedding_w, dtype='float32') return embedding_w, embedding_dic", "support class PhraseManager: def __init__(self, configuration): self.train_phrases, self.train_labels = self._read_train_phrases()", "text): vector_sequence = self.get_tokenizer().texts_to_sequences([text]) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post')", "65, '[': 66, ']': 67, '{': 68, '}': 69} def", "'9': 36, '-': 60, ',': 38, ';': 39, '.': 40,", "def get_tokenizer(self): if self.tokenizer is None: self.tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) self.tokenizer.fit_on_texts(self.train_phrases)", "29, '3': 30, '4': 31, '5': 32, '6': 33, '7':", "28, '2': 29, '3': 30, '4': 31, '5': 32, '6':", "[] for i in range(len( self.test_phrases)): doc_vec = self._doc_process( self.test_phrases[i].lower(),", "+ 1 onehot[i] = 1 embedding_w.append(onehot) embedding_w = numpy.array(embedding_w, dtype='float32')", "self.test_phrases, self.test_labels def _word_process(self, word_max_length): tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) tokenizer.fit_on_texts(self.train_phrases) x_train_sequence", "padding='post', truncating='post') y_train = numpy.array(self.train_labels) y_test = numpy.array(self.test_labels) return x_train,", "'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22,", "embedding_w, embedding_dic = self._onehot_dic_build() x_train = [] for i in", "def text_to_vector_word(self, text): vector_sequence = self.get_tokenizer().texts_to_sequences([text]) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH],", "return x_train, y_train, x_test, y_test def _char_process(self, max_length): embedding_w, embedding_dic", "i in range(len(texts)): doc_vec = self.text_to_vector_char(texts[i].lower()) result.append(doc_vec) result = numpy.asarray(result,", "get_phrases_test(self): return self.test_phrases, self.test_labels def get_dataset(self, level = None): if", "'#': 51, '$': 52, '%': 53, '^': 54, '&': 55,", "import Tokenizer from src.support import support class PhraseManager: def __init__(self,", "= self.get_tokenizer().texts_to_sequences([text]) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result", "x_test_sequence = tokenizer.texts_to_sequences(self.test_phrases) x_train = sequence.pad_sequences(x_train_sequence, maxlen=word_max_length, padding='post', truncating='post') x_test", "def _read_test_phrases(self): pass class Phrase: def __init__(self, text, classification): self.text", "0 embedding_w.append(numpy.zeros(len(alphabet), dtype='float32')) for i, alpha in enumerate(alphabet): onehot =", "result = [] for i in range(len(texts)): doc_vec = self.text_to_vector_char(texts[i].lower())", "62, '>': 63, '(': 64, ')': 65, '[': 66, ']':", "min_length = min(max_length, len(doc)) doc_vec = numpy.zeros(max_length, dtype='int64') for j", "self.test_labels def _word_process(self, word_max_length): tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) tokenizer.fit_on_texts(self.train_phrases) x_train_sequence =", "return {'UNK': 0, 'a': 1, 'b': 2, 'c': 3, 'd':", "y_test = numpy.array(self.test_labels) return x_train, y_train, x_test, y_test def _char_process(self,", "y_test def _char_process(self, max_length): embedding_w, embedding_dic = self._onehot_dic_build() x_train =", "return embedding_w, embedding_dic def get_tokenizer(self): if self.tokenizer is None: self.tokenizer", "elif level == support.CHAR_LEVEL: return self._char_process(self.configuration[support.CHAR_MAX_LENGTH]) else: return self.train_phrases, self.train_labels,", "def text_to_vector_char_all(self, texts): embedding_w, embedding_dic = self._onehot_dic_build() result = []", "20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y':", "self.train_phrases, self.train_labels def get_phrases_test(self): return self.test_phrases, self.test_labels def get_dataset(self, level", "41, '?': 42, ':': 43, \"'\": 44, '\"': 45, '/':", "= min(max_length, len(text)) text_vector = numpy.zeros(max_length, dtype=\"int64\") for j in", "sequence.pad_sequences(x_train_sequence, maxlen=word_max_length, padding='post', truncating='post') x_test = sequence.pad_sequences(x_test_sequence, maxlen=word_max_length, padding='post', truncating='post')", "self.get_tokenizer().texts_to_sequences([text]) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result def", "'w': 23, 'x': 24, 'y': 25, 'z': 26, '0': 27,", "= self._doc_process( self.test_phrases[i].lower(), embedding_dic, max_length) x_test.append(doc_vec) x_test = numpy.asarray(x_test, dtype='int64')", "= self._read_test_phrases() self.configuration = configuration self.tokenizer = None def get_phrases_train(self):", "numpy.zeros(len(alphabet), dtype='float32') embedding_dic[alpha] = i + 1 onehot[i] = 1", "None: self.tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) self.tokenizer.fit_on_texts(self.train_phrases) return self.tokenizer def text_to_vector_word(self, text):", "support.CHAR_LEVEL: return self._char_process(self.configuration[support.CHAR_MAX_LENGTH]) else: return self.train_phrases, self.train_labels, self.test_phrases, self.test_labels def", "maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result def text_to_vector_word_all(self, texts): vector_sequence =", "= sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result def text_to_vector_char(self, text):", "x_test, y_test def _doc_process(self, doc, embedding_dic, max_length): min_length = min(max_length,", "return x_train, y_train, x_test, y_test def _doc_process(self, doc, embedding_dic, max_length):", "11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p':", "_read_test_phrases(self): pass class Phrase: def __init__(self, text, classification): self.text =", "self.train_labels def get_phrases_test(self): return self.test_phrases, self.test_labels def get_dataset(self, level =", "min(max_length, len(text)) text_vector = numpy.zeros(max_length, dtype=\"int64\") for j in range(min_length):", "Phrase: def __init__(self, text, classification): self.text = text self.classification =", "numpy.array(self.test_labels, dtype='float32') del embedding_w, embedding_dic return x_train, y_train, x_test, y_test", "self.tokenizer.fit_on_texts(self.train_phrases) return self.tokenizer def text_to_vector_word(self, text): vector_sequence = self.get_tokenizer().texts_to_sequences([text]) result", "None def get_phrases_train(self): return self.train_phrases, self.train_labels def get_phrases_test(self): return self.test_phrases,", "padding='post', truncating='post') return result def text_to_vector_char(self, text): embedding_dictionary = self._get_embedding_dictionary()", "src.support import support class PhraseManager: def __init__(self, configuration): self.train_phrases, self.train_labels", "numpy.asarray(x_train, dtype='int64') y_train = numpy.array(self.train_labels, dtype='float32') x_test = [] for", "maxlen=word_max_length, padding='post', truncating='post') y_train = numpy.array(self.train_labels) y_test = numpy.array(self.test_labels) return", "embedding_dic[alpha] = i + 1 onehot[i] = 1 embedding_w.append(onehot) embedding_w", "return self.train_phrases, self.train_labels def get_phrases_test(self): return self.test_phrases, self.test_labels def get_dataset(self,", "embedding_dictionary[\"UNK\"] return text_vector def text_to_vector_char_all(self, texts): embedding_w, embedding_dic = self._onehot_dic_build()", "23, 'x': 24, 'y': 25, 'z': 26, '0': 27, '1':", "text_vector = numpy.zeros(max_length, dtype=\"int64\") for j in range(min_length): if text[j]", "__init__(self, text, classification): self.text = text self.classification = classification def", "return self.tokenizer def text_to_vector_word(self, text): vector_sequence = self.get_tokenizer().texts_to_sequences([text]) result =", "= self._read_train_phrases() self.test_phrases, self.test_labels = self._read_test_phrases() self.configuration = configuration self.tokenizer", "self.test_labels = self._read_test_phrases() self.configuration = configuration self.tokenizer = None def", "= [] for i in range(len(self.train_phrases)): doc_vec = self._doc_process(self.train_phrases[i].lower(), embedding_dic,", "'>': 63, '(': 64, ')': 65, '[': 66, ']': 67,", "embedding_w = [] embedding_dic[\"UNK\"] = 0 embedding_w.append(numpy.zeros(len(alphabet), dtype='float32')) for i,", "14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's':", "i in range(len( self.test_phrases)): doc_vec = self._doc_process( self.test_phrases[i].lower(), embedding_dic, max_length)", "= numpy.array(self.train_labels, dtype='float32') x_test = [] for i in range(len(", "embedding_w.append(numpy.zeros(len(alphabet), dtype='float32')) for i, alpha in enumerate(alphabet): onehot = numpy.zeros(len(alphabet),", "= self._get_embedding_dictionary() max_length = self.configuration[support.CHAR_MAX_LENGTH] min_length = min(max_length, len(text)) text_vector", "embedding_w, embedding_dic = self._onehot_dic_build() result = [] for i in", "dtype=\"int64\") for j in range(min_length): if text[j] in embedding_dictionary: text_vector[j]", "'<': 62, '>': 63, '(': 64, ')': 65, '[': 66,", "'7': 34, '8': 35, '9': 36, '-': 60, ',': 38,", "dtype='int64') y_test = numpy.array(self.test_labels, dtype='float32') del embedding_w, embedding_dic return x_train,", "'`': 58, '+': 59, '=': 61, '<': 62, '>': 63,", "x_train = numpy.asarray(x_train, dtype='int64') y_train = numpy.array(self.train_labels, dtype='float32') x_test =", "embedding_dic = self._onehot_dic_build() result = [] for i in range(len(texts)):", "'6': 33, '7': 34, '8': 35, '9': 36, '-': 60,", "'-': 60, ',': 38, ';': 39, '.': 40, '!': 41,", "def _char_process(self, max_length): embedding_w, embedding_dic = self._onehot_dic_build() x_train = []", "42, ':': 43, \"'\": 44, '\"': 45, '/': 46, '\\\\':", "self.configuration[support.CHAR_MAX_LENGTH] min_length = min(max_length, len(text)) text_vector = numpy.zeros(max_length, dtype=\"int64\") for", "= configuration self.tokenizer = None def get_phrases_train(self): return self.train_phrases, self.train_labels", "')': 65, '[': 66, ']': 67, '{': 68, '}': 69}", "sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result def text_to_vector_char(self, text): embedding_dictionary", "= min(max_length, len(doc)) doc_vec = numpy.zeros(max_length, dtype='int64') for j in", "'_': 49, '@': 50, '#': 51, '$': 52, '%': 53,", "result def text_to_vector_char(self, text): embedding_dictionary = self._get_embedding_dictionary() max_length = self.configuration[support.CHAR_MAX_LENGTH]", "embedding_dic['UNK'] return doc_vec def _onehot_dic_build(self): alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\" embedding_dic =", "for i in range(len(texts)): doc_vec = self.text_to_vector_char(texts[i].lower()) result.append(doc_vec) result =", "x_train = sequence.pad_sequences(x_train_sequence, maxlen=word_max_length, padding='post', truncating='post') x_test = sequence.pad_sequences(x_test_sequence, maxlen=word_max_length,", "in range(len( self.test_phrases)): doc_vec = self._doc_process( self.test_phrases[i].lower(), embedding_dic, max_length) x_test.append(doc_vec)", "= numpy.array(self.test_labels) return x_train, y_train, x_test, y_test def _char_process(self, max_length):", "alpha in enumerate(alphabet): onehot = numpy.zeros(len(alphabet), dtype='float32') embedding_dic[alpha] = i", "59, '=': 61, '<': 62, '>': 63, '(': 64, ')':", "'{': 68, '}': 69} def get_classes(self): pass def _read_train_phrases(self): pass", "x_train = [] for i in range(len(self.train_phrases)): doc_vec = self._doc_process(self.train_phrases[i].lower(),", "if self.tokenizer is None: self.tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) self.tokenizer.fit_on_texts(self.train_phrases) return self.tokenizer", "sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result def text_to_vector_word_all(self, texts): vector_sequence", "def text_to_vector_word_all(self, texts): vector_sequence = self.get_tokenizer().texts_to_sequences(texts) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH],", "vector_sequence = self.get_tokenizer().texts_to_sequences(texts) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return", "range(len( self.test_phrases)): doc_vec = self._doc_process( self.test_phrases[i].lower(), embedding_dic, max_length) x_test.append(doc_vec) x_test", "19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x':", "doc_vec[j] = embedding_dic[doc[j]] else: doc_vec[j] = embedding_dic['UNK'] return doc_vec def", "tokenizer.fit_on_texts(self.train_phrases) x_train_sequence = tokenizer.texts_to_sequences(self.train_phrases) x_test_sequence = tokenizer.texts_to_sequences(self.test_phrases) x_train = sequence.pad_sequences(x_train_sequence,", "x_test = [] for i in range(len( self.test_phrases)): doc_vec =", "numpy.asarray(result, dtype=\"int64\") del embedding_w, embedding_dic return result def _get_embedding_dictionary(self): return", "result def text_to_vector_word_all(self, texts): vector_sequence = self.get_tokenizer().texts_to_sequences(texts) result = sequence.pad_sequences(vector_sequence,", "25, 'z': 26, '0': 27, '1': 28, '2': 29, '3':", "63, '(': 64, ')': 65, '[': 66, ']': 67, '{':", "_read_train_phrases(self): pass def _read_test_phrases(self): pass class Phrase: def __init__(self, text,", "dtype='float32') del embedding_w, embedding_dic return x_train, y_train, x_test, y_test def", "'[': 66, ']': 67, '{': 68, '}': 69} def get_classes(self):", "for i in range(len(self.train_phrases)): doc_vec = self._doc_process(self.train_phrases[i].lower(), embedding_dic, max_length) x_train.append(doc_vec)", "']': 67, '{': 68, '}': 69} def get_classes(self): pass def", "embedding_dic, max_length) x_test.append(doc_vec) x_test = numpy.asarray(x_test, dtype='int64') y_test = numpy.array(self.test_labels,", "get_dataset(self, level = None): if level == support.WORD_LEVEL: return self._word_process(self.configuration[support.WORD_MAX_LENGTH])", "self._doc_process( self.test_phrases[i].lower(), embedding_dic, max_length) x_test.append(doc_vec) x_test = numpy.asarray(x_test, dtype='int64') y_test", "self.configuration = configuration self.tokenizer = None def get_phrases_train(self): return self.train_phrases,", "54, '&': 55, '*': 56, '~': 57, '`': 58, '+':", "= text self.classification = classification def __str__(self): return \"Classification: \"", "doc_vec = self._doc_process(self.train_phrases[i].lower(), embedding_dic, max_length) x_train.append(doc_vec) x_train = numpy.asarray(x_train, dtype='int64')", "in enumerate(alphabet): onehot = numpy.zeros(len(alphabet), dtype='float32') embedding_dic[alpha] = i +", "self.tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) self.tokenizer.fit_on_texts(self.train_phrases) return self.tokenizer def text_to_vector_word(self, text): vector_sequence", "{'UNK': 0, 'a': 1, 'b': 2, 'c': 3, 'd': 4,", "get_tokenizer(self): if self.tokenizer is None: self.tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) self.tokenizer.fit_on_texts(self.train_phrases) return", "= self._doc_process(self.train_phrases[i].lower(), embedding_dic, max_length) x_train.append(doc_vec) x_train = numpy.asarray(x_train, dtype='int64') y_train", "text_vector[j] = embedding_dictionary[\"UNK\"] return text_vector def text_to_vector_char_all(self, texts): embedding_w, embedding_dic", "text_to_vector_word(self, text): vector_sequence = self.get_tokenizer().texts_to_sequences([text]) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post',", "self._word_process(self.configuration[support.WORD_MAX_LENGTH]) elif level == support.CHAR_LEVEL: return self._char_process(self.configuration[support.CHAR_MAX_LENGTH]) else: return self.train_phrases,", "'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7,", "numpy.zeros(max_length, dtype='int64') for j in range(min_length): if doc[j] in embedding_dic:", "embedding_dic: doc_vec[j] = embedding_dic[doc[j]] else: doc_vec[j] = embedding_dic['UNK'] return doc_vec", "embedding_w.append(onehot) embedding_w = numpy.array(embedding_w, dtype='float32') return embedding_w, embedding_dic def get_tokenizer(self):", "return self._char_process(self.configuration[support.CHAR_MAX_LENGTH]) else: return self.train_phrases, self.train_labels, self.test_phrases, self.test_labels def _word_process(self,", "45, '/': 46, '\\\\': 47, '|': 48, '_': 49, '@':", "i, alpha in enumerate(alphabet): onehot = numpy.zeros(len(alphabet), dtype='float32') embedding_dic[alpha] =", "text_vector[j] = embedding_dictionary[text[j]] else: text_vector[j] = embedding_dictionary[\"UNK\"] return text_vector def", "= self.configuration[support.CHAR_MAX_LENGTH] min_length = min(max_length, len(text)) text_vector = numpy.zeros(max_length, dtype=\"int64\")", "self.test_phrases, self.test_labels = self._read_test_phrases() self.configuration = configuration self.tokenizer = None", "y_train, x_test, y_test def _char_process(self, max_length): embedding_w, embedding_dic = self._onehot_dic_build()", "self.test_phrases)): doc_vec = self._doc_process( self.test_phrases[i].lower(), embedding_dic, max_length) x_test.append(doc_vec) x_test =", "'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5,", "_get_embedding_dictionary(self): return {'UNK': 0, 'a': 1, 'b': 2, 'c': 3,", "'\"': 45, '/': 46, '\\\\': 47, '|': 48, '_': 49,", "= numpy.asarray(x_test, dtype='int64') y_test = numpy.array(self.test_labels, dtype='float32') del embedding_w, embedding_dic", "= i + 1 onehot[i] = 1 embedding_w.append(onehot) embedding_w =", "tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) tokenizer.fit_on_texts(self.train_phrases) x_train_sequence = tokenizer.texts_to_sequences(self.train_phrases) x_test_sequence = tokenizer.texts_to_sequences(self.test_phrases)", "Tokenizer from src.support import support class PhraseManager: def __init__(self, configuration):", "== support.CHAR_LEVEL: return self._char_process(self.configuration[support.CHAR_MAX_LENGTH]) else: return self.train_phrases, self.train_labels, self.test_phrases, self.test_labels", "x_train.append(doc_vec) x_train = numpy.asarray(x_train, dtype='int64') y_train = numpy.array(self.train_labels, dtype='float32') x_test", "embedding_w, embedding_dic def get_tokenizer(self): if self.tokenizer is None: self.tokenizer =", "range(min_length): if text[j] in embedding_dictionary: text_vector[j] = embedding_dictionary[text[j]] else: text_vector[j]", "'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15,", "26, '0': 27, '1': 28, '2': 29, '3': 30, '4':", "pass def _read_train_phrases(self): pass def _read_test_phrases(self): pass class Phrase: def", "doc_vec = self._doc_process( self.test_phrases[i].lower(), embedding_dic, max_length) x_test.append(doc_vec) x_test = numpy.asarray(x_test,", "= Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) self.tokenizer.fit_on_texts(self.train_phrases) return self.tokenizer def text_to_vector_word(self, text): vector_sequence =", "self.test_phrases[i].lower(), embedding_dic, max_length) x_test.append(doc_vec) x_test = numpy.asarray(x_test, dtype='int64') y_test =", "'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18,", "del embedding_w, embedding_dic return x_train, y_train, x_test, y_test def _doc_process(self,", "= self.text_to_vector_char(texts[i].lower()) result.append(doc_vec) result = numpy.asarray(result, dtype=\"int64\") del embedding_w, embedding_dic", "y_test def _doc_process(self, doc, embedding_dic, max_length): min_length = min(max_length, len(doc))", "__str__(self): return \"Classification: \" + str(self.classification) + \"\\nText: \" +", "[] for i in range(len(self.train_phrases)): doc_vec = self._doc_process(self.train_phrases[i].lower(), embedding_dic, max_length)", "= self._onehot_dic_build() result = [] for i in range(len(texts)): doc_vec", "'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25,", "67, '{': 68, '}': 69} def get_classes(self): pass def _read_train_phrases(self):", "min(max_length, len(doc)) doc_vec = numpy.zeros(max_length, dtype='int64') for j in range(min_length):", "def text_to_vector_char(self, text): embedding_dictionary = self._get_embedding_dictionary() max_length = self.configuration[support.CHAR_MAX_LENGTH] min_length", "result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result def text_to_vector_word_all(self,", "numpy.array(self.train_labels, dtype='float32') x_test = [] for i in range(len( self.test_phrases)):", "2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g':", "range(len(texts)): doc_vec = self.text_to_vector_char(texts[i].lower()) result.append(doc_vec) result = numpy.asarray(result, dtype=\"int64\") del", "len(text)) text_vector = numpy.zeros(max_length, dtype=\"int64\") for j in range(min_length): if", "embedding_dictionary = self._get_embedding_dictionary() max_length = self.configuration[support.CHAR_MAX_LENGTH] min_length = min(max_length, len(text))", "embedding_w, embedding_dic return x_train, y_train, x_test, y_test def _doc_process(self, doc,", "'0': 27, '1': 28, '2': 29, '3': 30, '4': 31,", "for j in range(min_length): if text[j] in embedding_dictionary: text_vector[j] =", "doc_vec = self.text_to_vector_char(texts[i].lower()) result.append(doc_vec) result = numpy.asarray(result, dtype=\"int64\") del embedding_w,", "Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) self.tokenizer.fit_on_texts(self.train_phrases) return self.tokenizer def text_to_vector_word(self, text): vector_sequence = self.get_tokenizer().texts_to_sequences([text])", "7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l':", "'=': 61, '<': 62, '>': 63, '(': 64, ')': 65,", "66, ']': 67, '{': 68, '}': 69} def get_classes(self): pass", "_onehot_dic_build(self): alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\" embedding_dic = {} embedding_w = []", "i in range(len(self.train_phrases)): doc_vec = self._doc_process(self.train_phrases[i].lower(), embedding_dic, max_length) x_train.append(doc_vec) x_train", "configuration self.tokenizer = None def get_phrases_train(self): return self.train_phrases, self.train_labels def", "= embedding_dic['UNK'] return doc_vec def _onehot_dic_build(self): alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\" embedding_dic", "text_vector def text_to_vector_char_all(self, texts): embedding_w, embedding_dic = self._onehot_dic_build() result =", "{} embedding_w = [] embedding_dic[\"UNK\"] = 0 embedding_w.append(numpy.zeros(len(alphabet), dtype='float32')) for", "def __init__(self, text, classification): self.text = text self.classification = classification", "17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v':", "x_train_sequence = tokenizer.texts_to_sequences(self.train_phrases) x_test_sequence = tokenizer.texts_to_sequences(self.test_phrases) x_train = sequence.pad_sequences(x_train_sequence, maxlen=word_max_length,", "return self.train_phrases, self.train_labels, self.test_phrases, self.test_labels def _word_process(self, word_max_length): tokenizer =", "33, '7': 34, '8': 35, '9': 36, '-': 60, ',':", "_word_process(self, word_max_length): tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) tokenizer.fit_on_texts(self.train_phrases) x_train_sequence = tokenizer.texts_to_sequences(self.train_phrases) x_test_sequence", "57, '`': 58, '+': 59, '=': 61, '<': 62, '>':", "maxlen=word_max_length, padding='post', truncating='post') x_test = sequence.pad_sequences(x_test_sequence, maxlen=word_max_length, padding='post', truncating='post') y_train", "'}': 69} def get_classes(self): pass def _read_train_phrases(self): pass def _read_test_phrases(self):", "36, '-': 60, ',': 38, ';': 39, '.': 40, '!':", "def _doc_process(self, doc, embedding_dic, max_length): min_length = min(max_length, len(doc)) doc_vec", "43, \"'\": 44, '\"': 45, '/': 46, '\\\\': 47, '|':", "'t': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24,", "pass class Phrase: def __init__(self, text, classification): self.text = text", "51, '$': 52, '%': 53, '^': 54, '&': 55, '*':", "onehot[i] = 1 embedding_w.append(onehot) embedding_w = numpy.array(embedding_w, dtype='float32') return embedding_w,", "i + 1 onehot[i] = 1 embedding_w.append(onehot) embedding_w = numpy.array(embedding_w,", "30, '4': 31, '5': 32, '6': 33, '7': 34, '8':", "if level == support.WORD_LEVEL: return self._word_process(self.configuration[support.WORD_MAX_LENGTH]) elif level == support.CHAR_LEVEL:", "15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't':", "text): embedding_dictionary = self._get_embedding_dictionary() max_length = self.configuration[support.CHAR_MAX_LENGTH] min_length = min(max_length,", "result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result def text_to_vector_char(self,", "= 0 embedding_w.append(numpy.zeros(len(alphabet), dtype='float32')) for i, alpha in enumerate(alphabet): onehot", "= self.get_tokenizer().texts_to_sequences(texts) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result", "'s': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23,", "'5': 32, '6': 33, '7': 34, '8': 35, '9': 36,", "68, '}': 69} def get_classes(self): pass def _read_train_phrases(self): pass def", "j in range(min_length): if doc[j] in embedding_dic: doc_vec[j] = embedding_dic[doc[j]]", "\"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\" embedding_dic = {} embedding_w = [] embedding_dic[\"UNK\"] = 0", "__init__(self, configuration): self.train_phrases, self.train_labels = self._read_train_phrases() self.test_phrases, self.test_labels = self._read_test_phrases()", "numpy.array(self.train_labels) y_test = numpy.array(self.test_labels) return x_train, y_train, x_test, y_test def", "'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14,", "'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13,", "'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9,", "18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w':", "':': 43, \"'\": 44, '\"': 45, '/': 46, '\\\\': 47,", "sequence.pad_sequences(x_test_sequence, maxlen=word_max_length, padding='post', truncating='post') y_train = numpy.array(self.train_labels) y_test = numpy.array(self.test_labels)", "padding='post', truncating='post') return result def text_to_vector_word_all(self, texts): vector_sequence = self.get_tokenizer().texts_to_sequences(texts)", "self._doc_process(self.train_phrases[i].lower(), embedding_dic, max_length) x_train.append(doc_vec) x_train = numpy.asarray(x_train, dtype='int64') y_train =", "24, 'y': 25, 'z': 26, '0': 27, '1': 28, '2':", "6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k':", "else: text_vector[j] = embedding_dictionary[\"UNK\"] return text_vector def text_to_vector_char_all(self, texts): embedding_w,", "= embedding_dic[doc[j]] else: doc_vec[j] = embedding_dic['UNK'] return doc_vec def _onehot_dic_build(self):", "text_to_vector_char_all(self, texts): embedding_w, embedding_dic = self._onehot_dic_build() result = [] for", "result = numpy.asarray(result, dtype=\"int64\") del embedding_w, embedding_dic return result def", "truncating='post') return result def text_to_vector_char(self, text): embedding_dictionary = self._get_embedding_dictionary() max_length", "'x': 24, 'y': 25, 'z': 26, '0': 27, '1': 28,", "53, '^': 54, '&': 55, '*': 56, '~': 57, '`':", "def _word_process(self, word_max_length): tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) tokenizer.fit_on_texts(self.train_phrases) x_train_sequence = tokenizer.texts_to_sequences(self.train_phrases)", "doc_vec[j] = embedding_dic['UNK'] return doc_vec def _onehot_dic_build(self): alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\"", "58, '+': 59, '=': 61, '<': 62, '>': 63, '(':", "= numpy.zeros(max_length, dtype='int64') for j in range(min_length): if doc[j] in", "y_train = numpy.array(self.train_labels) y_test = numpy.array(self.test_labels) return x_train, y_train, x_test,", "in embedding_dictionary: text_vector[j] = embedding_dictionary[text[j]] else: text_vector[j] = embedding_dictionary[\"UNK\"] return", "else: return self.train_phrases, self.train_labels, self.test_phrases, self.test_labels def _word_process(self, word_max_length): tokenizer", "for i in range(len( self.test_phrases)): doc_vec = self._doc_process( self.test_phrases[i].lower(), embedding_dic,", "'z': 26, '0': 27, '1': 28, '2': 29, '3': 30,", "'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21,", "[] embedding_dic[\"UNK\"] = 0 embedding_w.append(numpy.zeros(len(alphabet), dtype='float32')) for i, alpha in", "self.tokenizer is None: self.tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) self.tokenizer.fit_on_texts(self.train_phrases) return self.tokenizer def", "truncating='post') y_train = numpy.array(self.train_labels) y_test = numpy.array(self.test_labels) return x_train, y_train,", "embedding_dic, max_length): min_length = min(max_length, len(doc)) doc_vec = numpy.zeros(max_length, dtype='int64')", "numpy from keras.preprocessing import sequence from keras.preprocessing.text import Tokenizer from", "'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16,", "return result def text_to_vector_word_all(self, texts): vector_sequence = self.get_tokenizer().texts_to_sequences(texts) result =", "def get_dataset(self, level = None): if level == support.WORD_LEVEL: return", "text self.classification = classification def __str__(self): return \"Classification: \" +", "embedding_dic = {} embedding_w = [] embedding_dic[\"UNK\"] = 0 embedding_w.append(numpy.zeros(len(alphabet),", "result def _get_embedding_dictionary(self): return {'UNK': 0, 'a': 1, 'b': 2,", "'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10,", "_doc_process(self, doc, embedding_dic, max_length): min_length = min(max_length, len(doc)) doc_vec =", "= numpy.asarray(x_train, dtype='int64') y_train = numpy.array(self.train_labels, dtype='float32') x_test = []", "61, '<': 62, '>': 63, '(': 64, ')': 65, '[':", "return self.test_phrases, self.test_labels def get_dataset(self, level = None): if level", "return doc_vec def _onehot_dic_build(self): alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\" embedding_dic = {}", "Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) tokenizer.fit_on_texts(self.train_phrases) x_train_sequence = tokenizer.texts_to_sequences(self.train_phrases) x_test_sequence = tokenizer.texts_to_sequences(self.test_phrases) x_train =", "self.train_labels = self._read_train_phrases() self.test_phrases, self.test_labels = self._read_test_phrases() self.configuration = configuration", "y_test = numpy.array(self.test_labels, dtype='float32') del embedding_w, embedding_dic return x_train, y_train,", "= classification def __str__(self): return \"Classification: \" + str(self.classification) +", "dtype='float32')) for i, alpha in enumerate(alphabet): onehot = numpy.zeros(len(alphabet), dtype='float32')", "= numpy.array(self.train_labels) y_test = numpy.array(self.test_labels) return x_train, y_train, x_test, y_test", "def get_phrases_test(self): return self.test_phrases, self.test_labels def get_dataset(self, level = None):", "def __init__(self, configuration): self.train_phrases, self.train_labels = self._read_train_phrases() self.test_phrases, self.test_labels =", "16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u':", "= {} embedding_w = [] embedding_dic[\"UNK\"] = 0 embedding_w.append(numpy.zeros(len(alphabet), dtype='float32'))", "self.train_phrases, self.train_labels, self.test_phrases, self.test_labels def _word_process(self, word_max_length): tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS])", "'m': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17,", "= None): if level == support.WORD_LEVEL: return self._word_process(self.configuration[support.WORD_MAX_LENGTH]) elif level", "'\\\\': 47, '|': 48, '_': 49, '@': 50, '#': 51,", "doc_vec def _onehot_dic_build(self): alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\" embedding_dic = {} embedding_w", "self.text_to_vector_char(texts[i].lower()) result.append(doc_vec) result = numpy.asarray(result, dtype=\"int64\") del embedding_w, embedding_dic return", "'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26,", "';': 39, '.': 40, '!': 41, '?': 42, ':': 43,", "13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r':", "def _onehot_dic_build(self): alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\" embedding_dic = {} embedding_w =", "text_to_vector_char(self, text): embedding_dictionary = self._get_embedding_dictionary() max_length = self.configuration[support.CHAR_MAX_LENGTH] min_length =", "embedding_dic, max_length) x_train.append(doc_vec) x_train = numpy.asarray(x_train, dtype='int64') y_train = numpy.array(self.train_labels,", "self._char_process(self.configuration[support.CHAR_MAX_LENGTH]) else: return self.train_phrases, self.train_labels, self.test_phrases, self.test_labels def _word_process(self, word_max_length):", "classification def __str__(self): return \"Classification: \" + str(self.classification) + \"\\nText:", "31, '5': 32, '6': 33, '7': 34, '8': 35, '9':", "truncating='post') x_test = sequence.pad_sequences(x_test_sequence, maxlen=word_max_length, padding='post', truncating='post') y_train = numpy.array(self.train_labels)", "'?': 42, ':': 43, \"'\": 44, '\"': 45, '/': 46,", "padding='post', truncating='post') x_test = sequence.pad_sequences(x_test_sequence, maxlen=word_max_length, padding='post', truncating='post') y_train =", "40, '!': 41, '?': 42, ':': 43, \"'\": 44, '\"':", "numpy.zeros(max_length, dtype=\"int64\") for j in range(min_length): if text[j] in embedding_dictionary:", "38, ';': 39, '.': 40, '!': 41, '?': 42, ':':", "'&': 55, '*': 56, '~': 57, '`': 58, '+': 59,", "self._onehot_dic_build() result = [] for i in range(len(texts)): doc_vec =", "1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f':", "level == support.WORD_LEVEL: return self._word_process(self.configuration[support.WORD_MAX_LENGTH]) elif level == support.CHAR_LEVEL: return", "x_test = numpy.asarray(x_test, dtype='int64') y_test = numpy.array(self.test_labels, dtype='float32') del embedding_w,", "level = None): if level == support.WORD_LEVEL: return self._word_process(self.configuration[support.WORD_MAX_LENGTH]) elif", "return result def text_to_vector_char(self, text): embedding_dictionary = self._get_embedding_dictionary() max_length =", "5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j':", "def _get_embedding_dictionary(self): return {'UNK': 0, 'a': 1, 'b': 2, 'c':", "27, '1': 28, '2': 29, '3': 30, '4': 31, '5':", "34, '8': 35, '9': 36, '-': 60, ',': 38, ';':", "x_train, y_train, x_test, y_test def _char_process(self, max_length): embedding_w, embedding_dic =", "maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result def text_to_vector_char(self, text): embedding_dictionary =", "'$': 52, '%': 53, '^': 54, '&': 55, '*': 56,", "del embedding_w, embedding_dic return result def _get_embedding_dictionary(self): return {'UNK': 0,", "if doc[j] in embedding_dic: doc_vec[j] = embedding_dic[doc[j]] else: doc_vec[j] =", "get_phrases_train(self): return self.train_phrases, self.train_labels def get_phrases_test(self): return self.test_phrases, self.test_labels def", "self._read_train_phrases() self.test_phrases, self.test_labels = self._read_test_phrases() self.configuration = configuration self.tokenizer =", "range(len(self.train_phrases)): doc_vec = self._doc_process(self.train_phrases[i].lower(), embedding_dic, max_length) x_train.append(doc_vec) x_train = numpy.asarray(x_train,", "dtype='int64') for j in range(min_length): if doc[j] in embedding_dic: doc_vec[j]", "self._get_embedding_dictionary() max_length = self.configuration[support.CHAR_MAX_LENGTH] min_length = min(max_length, len(text)) text_vector =", "x_test.append(doc_vec) x_test = numpy.asarray(x_test, dtype='int64') y_test = numpy.array(self.test_labels, dtype='float32') del", "'d': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8,", "embedding_dic[doc[j]] else: doc_vec[j] = embedding_dic['UNK'] return doc_vec def _onehot_dic_build(self): alphabet", "'|': 48, '_': 49, '@': 50, '#': 51, '$': 52,", "_char_process(self, max_length): embedding_w, embedding_dic = self._onehot_dic_build() x_train = [] for", "def __str__(self): return \"Classification: \" + str(self.classification) + \"\\nText: \"", "'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19,", "0, 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e':", "from src.support import support class PhraseManager: def __init__(self, configuration): self.train_phrases,", "texts): embedding_w, embedding_dic = self._onehot_dic_build() result = [] for i", "39, '.': 40, '!': 41, '?': 42, ':': 43, \"'\":", "self._read_test_phrases() self.configuration = configuration self.tokenizer = None def get_phrases_train(self): return", "'@': 50, '#': 51, '$': 52, '%': 53, '^': 54,", "x_train, y_train, x_test, y_test def _doc_process(self, doc, embedding_dic, max_length): min_length", "tokenizer.texts_to_sequences(self.test_phrases) x_train = sequence.pad_sequences(x_train_sequence, maxlen=word_max_length, padding='post', truncating='post') x_test = sequence.pad_sequences(x_test_sequence,", "44, '\"': 45, '/': 46, '\\\\': 47, '|': 48, '_':", "',': 38, ';': 39, '.': 40, '!': 41, '?': 42,", "'y': 25, 'z': 26, '0': 27, '1': 28, '2': 29,", "doc_vec = numpy.zeros(max_length, dtype='int64') for j in range(min_length): if doc[j]", "from keras.preprocessing import sequence from keras.preprocessing.text import Tokenizer from src.support", "configuration): self.train_phrases, self.train_labels = self._read_train_phrases() self.test_phrases, self.test_labels = self._read_test_phrases() self.configuration", "y_train = numpy.array(self.train_labels, dtype='float32') x_test = [] for i in", "self.test_phrases, self.test_labels def get_dataset(self, level = None): if level ==", "support.WORD_LEVEL: return self._word_process(self.configuration[support.WORD_MAX_LENGTH]) elif level == support.CHAR_LEVEL: return self._char_process(self.configuration[support.CHAR_MAX_LENGTH]) else:", "result.append(doc_vec) result = numpy.asarray(result, dtype=\"int64\") del embedding_w, embedding_dic return result", "'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20,", "PhraseManager: def __init__(self, configuration): self.train_phrases, self.train_labels = self._read_train_phrases() self.test_phrases, self.test_labels", "tokenizer.texts_to_sequences(self.train_phrases) x_test_sequence = tokenizer.texts_to_sequences(self.test_phrases) x_train = sequence.pad_sequences(x_train_sequence, maxlen=word_max_length, padding='post', truncating='post')", "22, 'w': 23, 'x': 24, 'y': 25, 'z': 26, '0':", "= None def get_phrases_train(self): return self.train_phrases, self.train_labels def get_phrases_test(self): return", "else: doc_vec[j] = embedding_dic['UNK'] return doc_vec def _onehot_dic_build(self): alphabet =", "vector_sequence = self.get_tokenizer().texts_to_sequences([text]) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return", "level == support.CHAR_LEVEL: return self._char_process(self.configuration[support.CHAR_MAX_LENGTH]) else: return self.train_phrases, self.train_labels, self.test_phrases,", "doc, embedding_dic, max_length): min_length = min(max_length, len(doc)) doc_vec = numpy.zeros(max_length,", "max_length = self.configuration[support.CHAR_MAX_LENGTH] min_length = min(max_length, len(text)) text_vector = numpy.zeros(max_length,", "'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11,", "self.train_labels, self.test_phrases, self.test_labels def _word_process(self, word_max_length): tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) tokenizer.fit_on_texts(self.train_phrases)", "dtype='float32') return embedding_w, embedding_dic def get_tokenizer(self): if self.tokenizer is None:", "[] for i in range(len(texts)): doc_vec = self.text_to_vector_char(texts[i].lower()) result.append(doc_vec) result", "52, '%': 53, '^': 54, '&': 55, '*': 56, '~':", "55, '*': 56, '~': 57, '`': 58, '+': 59, '=':", "embedding_dic return result def _get_embedding_dictionary(self): return {'UNK': 0, 'a': 1,", "def get_phrases_train(self): return self.train_phrases, self.train_labels def get_phrases_test(self): return self.test_phrases, self.test_labels", "21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z':", "self.tokenizer = None def get_phrases_train(self): return self.train_phrases, self.train_labels def get_phrases_test(self):", "keras.preprocessing import sequence from keras.preprocessing.text import Tokenizer from src.support import", "'4': 31, '5': 32, '6': 33, '7': 34, '8': 35,", "= [] embedding_dic[\"UNK\"] = 0 embedding_w.append(numpy.zeros(len(alphabet), dtype='float32')) for i, alpha", "alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\" embedding_dic = {} embedding_w = [] embedding_dic[\"UNK\"]", "return self._word_process(self.configuration[support.WORD_MAX_LENGTH]) elif level == support.CHAR_LEVEL: return self._char_process(self.configuration[support.CHAR_MAX_LENGTH]) else: return", "= Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS]) tokenizer.fit_on_texts(self.train_phrases) x_train_sequence = tokenizer.texts_to_sequences(self.train_phrases) x_test_sequence = tokenizer.texts_to_sequences(self.test_phrases) x_train", "None): if level == support.WORD_LEVEL: return self._word_process(self.configuration[support.WORD_MAX_LENGTH]) elif level ==", "= [] for i in range(len(texts)): doc_vec = self.text_to_vector_char(texts[i].lower()) result.append(doc_vec)", "embedding_w, embedding_dic return result def _get_embedding_dictionary(self): return {'UNK': 0, 'a':", "self._onehot_dic_build() x_train = [] for i in range(len(self.train_phrases)): doc_vec =", "in embedding_dic: doc_vec[j] = embedding_dic[doc[j]] else: doc_vec[j] = embedding_dic['UNK'] return", "in range(min_length): if doc[j] in embedding_dic: doc_vec[j] = embedding_dic[doc[j]] else:", "'2': 29, '3': 30, '4': 31, '5': 32, '6': 33,", "47, '|': 48, '_': 49, '@': 50, '#': 51, '$':", "pass def _read_test_phrases(self): pass class Phrase: def __init__(self, text, classification):", "embedding_dic = self._onehot_dic_build() x_train = [] for i in range(len(self.train_phrases)):", "46, '\\\\': 47, '|': 48, '_': 49, '@': 50, '#':", "max_length) x_train.append(doc_vec) x_train = numpy.asarray(x_train, dtype='int64') y_train = numpy.array(self.train_labels, dtype='float32')", "8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm':", "35, '9': 36, '-': 60, ',': 38, ';': 39, '.':", "32, '6': 33, '7': 34, '8': 35, '9': 36, '-':", "'*': 56, '~': 57, '`': 58, '+': 59, '=': 61,", "import numpy from keras.preprocessing import sequence from keras.preprocessing.text import Tokenizer", "max_length): min_length = min(max_length, len(doc)) doc_vec = numpy.zeros(max_length, dtype='int64') for", "min_length = min(max_length, len(text)) text_vector = numpy.zeros(max_length, dtype=\"int64\") for j", "len(doc)) doc_vec = numpy.zeros(max_length, dtype='int64') for j in range(min_length): if", "numpy.asarray(x_test, dtype='int64') y_test = numpy.array(self.test_labels, dtype='float32') del embedding_w, embedding_dic return", "def get_classes(self): pass def _read_train_phrases(self): pass def _read_test_phrases(self): pass class", "self.tokenizer def text_to_vector_word(self, text): vector_sequence = self.get_tokenizer().texts_to_sequences([text]) result = sequence.pad_sequences(vector_sequence,", "import sequence from keras.preprocessing.text import Tokenizer from src.support import support", "truncating='post') return result def text_to_vector_word_all(self, texts): vector_sequence = self.get_tokenizer().texts_to_sequences(texts) result", "class Phrase: def __init__(self, text, classification): self.text = text self.classification", "embedding_dic return x_train, y_train, x_test, y_test def _doc_process(self, doc, embedding_dic,", "= sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result def text_to_vector_word_all(self, texts):", "text, classification): self.text = text self.classification = classification def __str__(self):", "1 onehot[i] = 1 embedding_w.append(onehot) embedding_w = numpy.array(embedding_w, dtype='float32') return", "'(': 64, ')': 65, '[': 66, ']': 67, '{': 68,", "64, ')': 65, '[': 66, ']': 67, '{': 68, '}':", "for i, alpha in enumerate(alphabet): onehot = numpy.zeros(len(alphabet), dtype='float32') embedding_dic[alpha]", "onehot = numpy.zeros(len(alphabet), dtype='float32') embedding_dic[alpha] = i + 1 onehot[i]", "self.get_tokenizer().texts_to_sequences(texts) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post', truncating='post') return result def", "4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i':", "text_to_vector_word_all(self, texts): vector_sequence = self.get_tokenizer().texts_to_sequences(texts) result = sequence.pad_sequences(vector_sequence, maxlen=self.configuration[support.WORD_MAX_LENGTH], padding='post',", "'1': 28, '2': 29, '3': 30, '4': 31, '5': 32,", "'3': 30, '4': 31, '5': 32, '6': 33, '7': 34,", "numpy.array(embedding_w, dtype='float32') return embedding_w, embedding_dic def get_tokenizer(self): if self.tokenizer is", "dtype='float32') x_test = [] for i in range(len( self.test_phrases)): doc_vec", "60, ',': 38, ';': 39, '.': 40, '!': 41, '?':", "keras.preprocessing.text import Tokenizer from src.support import support class PhraseManager: def", "dtype='float32') embedding_dic[alpha] = i + 1 onehot[i] = 1 embedding_w.append(onehot)", "embedding_dic[\"UNK\"] = 0 embedding_w.append(numpy.zeros(len(alphabet), dtype='float32')) for i, alpha in enumerate(alphabet):", "3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h':", "12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q':", "= numpy.array(self.test_labels, dtype='float32') del embedding_w, embedding_dic return x_train, y_train, x_test,", "= \"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\" embedding_dic = {} embedding_w = [] embedding_dic[\"UNK\"] =", "= [] for i in range(len( self.test_phrases)): doc_vec = self._doc_process(", "1 embedding_w.append(onehot) embedding_w = numpy.array(embedding_w, dtype='float32') return embedding_w, embedding_dic def", "'%': 53, '^': 54, '&': 55, '*': 56, '~': 57,", "embedding_dic def get_tokenizer(self): if self.tokenizer is None: self.tokenizer = Tokenizer(num_words=self.configuration[support.QUANTITY_WORDS])", "get_classes(self): pass def _read_train_phrases(self): pass def _read_test_phrases(self): pass class Phrase:", "'^': 54, '&': 55, '*': 56, '~': 57, '`': 58,", "= embedding_dictionary[\"UNK\"] return text_vector def text_to_vector_char_all(self, texts): embedding_w, embedding_dic =" ]
[ "'Programming Language :: Python :: 2', 'Programming Language :: Python", "Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming", ":: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language", "to be used with code-generated projects. \"\"\" setup( name=\"paypalhttp\", long_description=long_description,", "used with code-generated projects. \"\"\" setup( name=\"paypalhttp\", long_description=long_description, version=version, author=\"PayPal\",", "Independent', 'Programming Language :: Python', 'Programming Language :: Python ::", "Python :: 3.5', 'Programming Language :: Python :: 3.7', 'Programming", "setuptools import setup version = \"1.0.0\" long_description = \"\"\" PayPalHttp", ":: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language", "projects. \"\"\" setup( name=\"paypalhttp\", long_description=long_description, version=version, author=\"PayPal\", packages=[\"paypalhttp\", \"paypalhttp/testutils\", \"paypalhttp/serializers\"],", "long_description = \"\"\" PayPalHttp is a generic http client designed", "Language :: Python :: 3', 'Programming Language :: Python ::", "code-generated projects. \"\"\" setup( name=\"paypalhttp\", long_description=long_description, version=version, author=\"PayPal\", packages=[\"paypalhttp\", \"paypalhttp/testutils\",", "from setuptools import setup version = \"1.0.0\" long_description = \"\"\"", "name=\"paypalhttp\", long_description=long_description, version=version, author=\"PayPal\", packages=[\"paypalhttp\", \"paypalhttp/testutils\", \"paypalhttp/serializers\"], install_requires=['requests>=2.0.0', 'six>=1.0.0', 'pyopenssl>=0.15'],", ":: Python :: 2.7', 'Programming Language :: Python :: 3',", ":: Python :: 3.4', 'Programming Language :: Python :: 3.5',", "Language :: Python :: 2.6', 'Programming Language :: Python ::", ":: Software Development :: Libraries :: Python Modules' ], )", "2.6', 'Programming Language :: Python :: 2.7', 'Programming Language ::", "Python', 'Programming Language :: Python :: 2', 'Programming Language ::", "version = \"1.0.0\" long_description = \"\"\" PayPalHttp is a generic", "PayPalHttp is a generic http client designed to be used", ":: OS Independent', 'Programming Language :: Python', 'Programming Language ::", "version=version, author=\"PayPal\", packages=[\"paypalhttp\", \"paypalhttp/testutils\", \"paypalhttp/serializers\"], install_requires=['requests>=2.0.0', 'six>=1.0.0', 'pyopenssl>=0.15'], license=\"MIT\", classifiers=[", "Python :: 3.7', 'Programming Language :: Python :: Implementation ::", "Audience :: Developers', 'Natural Language :: English', 'Operating System ::", "'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System", "'pyopenssl>=0.15'], license=\"MIT\", classifiers=[ 'Intended Audience :: Developers', 'Natural Language ::", "be used with code-generated projects. \"\"\" setup( name=\"paypalhttp\", long_description=long_description, version=version,", ":: 3.7', 'Programming Language :: Python :: Implementation :: PyPy',", "3.5', 'Programming Language :: Python :: 3.7', 'Programming Language ::", ":: Python :: 3.3', 'Programming Language :: Python :: 3.4',", ":: 2.7', 'Programming Language :: Python :: 3', 'Programming Language", "is a generic http client designed to be used with", "\"\"\" PayPalHttp is a generic http client designed to be", ":: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language", "Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming", "Language :: Python :: 2.7', 'Programming Language :: Python ::", "\"1.0.0\" long_description = \"\"\" PayPalHttp is a generic http client", "Language :: Python', 'Programming Language :: Python :: 2', 'Programming", "'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming", ":: Python :: 2.6', 'Programming Language :: Python :: 2.7',", "2.7', 'Programming Language :: Python :: 3', 'Programming Language ::", ":: PyPy', 'Topic :: Software Development :: Libraries :: Python", "Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming", "Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming", "author=\"PayPal\", packages=[\"paypalhttp\", \"paypalhttp/testutils\", \"paypalhttp/serializers\"], install_requires=['requests>=2.0.0', 'six>=1.0.0', 'pyopenssl>=0.15'], license=\"MIT\", classifiers=[ 'Intended", "Language :: Python :: 3.5', 'Programming Language :: Python ::", "client designed to be used with code-generated projects. \"\"\" setup(", "3.3', 'Programming Language :: Python :: 3.4', 'Programming Language ::", "Language :: English', 'Operating System :: OS Independent', 'Programming Language", "a generic http client designed to be used with code-generated", "setup( name=\"paypalhttp\", long_description=long_description, version=version, author=\"PayPal\", packages=[\"paypalhttp\", \"paypalhttp/testutils\", \"paypalhttp/serializers\"], install_requires=['requests>=2.0.0', 'six>=1.0.0',", "'Programming Language :: Python :: 3.3', 'Programming Language :: Python", "'Programming Language :: Python :: 2.7', 'Programming Language :: Python", "Language :: Python :: Implementation :: PyPy', 'Topic :: Software", "PyPy', 'Topic :: Software Development :: Libraries :: Python Modules'", "'Programming Language :: Python :: 3', 'Programming Language :: Python", ":: 2', 'Programming Language :: Python :: 2.6', 'Programming Language", "Developers', 'Natural Language :: English', 'Operating System :: OS Independent',", "packages=[\"paypalhttp\", \"paypalhttp/testutils\", \"paypalhttp/serializers\"], install_requires=['requests>=2.0.0', 'six>=1.0.0', 'pyopenssl>=0.15'], license=\"MIT\", classifiers=[ 'Intended Audience", "'Topic :: Software Development :: Libraries :: Python Modules' ],", "OS Independent', 'Programming Language :: Python', 'Programming Language :: Python", "'six>=1.0.0', 'pyopenssl>=0.15'], license=\"MIT\", classifiers=[ 'Intended Audience :: Developers', 'Natural Language", ":: 3', 'Programming Language :: Python :: 3.3', 'Programming Language", "Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming", "'Natural Language :: English', 'Operating System :: OS Independent', 'Programming", "= \"1.0.0\" long_description = \"\"\" PayPalHttp is a generic http", "3.7', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic", "'Programming Language :: Python :: 3.4', 'Programming Language :: Python", "classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating", ":: English', 'Operating System :: OS Independent', 'Programming Language ::", ":: Implementation :: PyPy', 'Topic :: Software Development :: Libraries", "install_requires=['requests>=2.0.0', 'six>=1.0.0', 'pyopenssl>=0.15'], license=\"MIT\", classifiers=[ 'Intended Audience :: Developers', 'Natural", "Python :: Implementation :: PyPy', 'Topic :: Software Development ::", "designed to be used with code-generated projects. \"\"\" setup( name=\"paypalhttp\",", "3', 'Programming Language :: Python :: 3.3', 'Programming Language ::", "2', 'Programming Language :: Python :: 2.6', 'Programming Language ::", "http client designed to be used with code-generated projects. \"\"\"", "'Programming Language :: Python :: Implementation :: PyPy', 'Topic ::", "\"paypalhttp/testutils\", \"paypalhttp/serializers\"], install_requires=['requests>=2.0.0', 'six>=1.0.0', 'pyopenssl>=0.15'], license=\"MIT\", classifiers=[ 'Intended Audience ::", "'Programming Language :: Python :: 3.7', 'Programming Language :: Python", "generic http client designed to be used with code-generated projects.", "Language :: Python :: 3.7', 'Programming Language :: Python ::", "long_description=long_description, version=version, author=\"PayPal\", packages=[\"paypalhttp\", \"paypalhttp/testutils\", \"paypalhttp/serializers\"], install_requires=['requests>=2.0.0', 'six>=1.0.0', 'pyopenssl>=0.15'], license=\"MIT\",", "\"paypalhttp/serializers\"], install_requires=['requests>=2.0.0', 'six>=1.0.0', 'pyopenssl>=0.15'], license=\"MIT\", classifiers=[ 'Intended Audience :: Developers',", "Language :: Python :: 3.3', 'Programming Language :: Python ::", "'Programming Language :: Python :: 3.5', 'Programming Language :: Python", ":: Python :: 3.7', 'Programming Language :: Python :: Implementation", "'Programming Language :: Python', 'Programming Language :: Python :: 2',", ":: Python :: 3.5', 'Programming Language :: Python :: 3.7',", ":: Python :: 2', 'Programming Language :: Python :: 2.6',", ":: 3.5', 'Programming Language :: Python :: 3.7', 'Programming Language", "'Programming Language :: Python :: 2.6', 'Programming Language :: Python", "= \"\"\" PayPalHttp is a generic http client designed to", "license=\"MIT\", classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English',", "setup version = \"1.0.0\" long_description = \"\"\" PayPalHttp is a", ":: Python', 'Programming Language :: Python :: 2', 'Programming Language", "Language :: Python :: 3.4', 'Programming Language :: Python ::", ":: Python :: Implementation :: PyPy', 'Topic :: Software Development", "3.4', 'Programming Language :: Python :: 3.5', 'Programming Language ::", "Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming", ":: Developers', 'Natural Language :: English', 'Operating System :: OS", "with code-generated projects. \"\"\" setup( name=\"paypalhttp\", long_description=long_description, version=version, author=\"PayPal\", packages=[\"paypalhttp\",", "English', 'Operating System :: OS Independent', 'Programming Language :: Python',", ":: Python :: 3', 'Programming Language :: Python :: 3.3',", "import setup version = \"1.0.0\" long_description = \"\"\" PayPalHttp is", "System :: OS Independent', 'Programming Language :: Python', 'Programming Language", "Implementation :: PyPy', 'Topic :: Software Development :: Libraries ::", "Language :: Python :: 2', 'Programming Language :: Python ::", "\"\"\" setup( name=\"paypalhttp\", long_description=long_description, version=version, author=\"PayPal\", packages=[\"paypalhttp\", \"paypalhttp/testutils\", \"paypalhttp/serializers\"], install_requires=['requests>=2.0.0'," ]
[ "from ...lo.xml.attribute_data import AttributeData as AttributeData from ...lo.xml.export_filter import ExportFilter", "AttributeData from ...lo.xml.export_filter import ExportFilter as ExportFilter from ...lo.xml.fast_attribute import", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "as NamespaceContainer from ...lo.xml.para_user_defined_attributes_supplier import ParaUserDefinedAttributesSupplier as ParaUserDefinedAttributesSupplier from ...lo.xml.text_user_defined_attributes_supplier", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "ParaUserDefinedAttributesSupplier as ParaUserDefinedAttributesSupplier from ...lo.xml.text_user_defined_attributes_supplier import TextUserDefinedAttributesSupplier as TextUserDefinedAttributesSupplier from", "as XImportFilter2 from ...lo.xml.xml_export_filter import XMLExportFilter as XMLExportFilter from ...lo.xml.xml_import_filter", "the License. # from ...lo.xml.attribute import Attribute as Attribute from", "utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # Licensed", "distributed under the License is distributed on an \"AS IS\"", "permissions and # limitations under the License. # from ...lo.xml.attribute", "from ...lo.xml.import_filter import ImportFilter as ImportFilter from ...lo.xml.namespace_container import NamespaceContainer", "of the License at # # http: // www.apache.org/licenses/LICENSE-2.0 #", "...lo.xml.namespace_container import NamespaceContainer as NamespaceContainer from ...lo.xml.para_user_defined_attributes_supplier import ParaUserDefinedAttributesSupplier as", "from ...lo.xml.export_filter import ExportFilter as ExportFilter from ...lo.xml.fast_attribute import FastAttribute", "as ImportFilter from ...lo.xml.namespace_container import NamespaceContainer as NamespaceContainer from ...lo.xml.para_user_defined_attributes_supplier", "the specific language governing permissions and # limitations under the", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "License at # # http: // www.apache.org/licenses/LICENSE-2.0 # # Unless", "XImportFilter2 from ...lo.xml.xml_export_filter import XMLExportFilter as XMLExportFilter from ...lo.xml.xml_import_filter import", "Version 2.0 (the \"License\") # you may not use this", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "as ParaUserDefinedAttributesSupplier from ...lo.xml.text_user_defined_attributes_supplier import TextUserDefinedAttributesSupplier as TextUserDefinedAttributesSupplier from ...lo.xml.user_defined_attributes_supplier", "except in compliance with the License. # You may obtain", "import XExportFilter as XExportFilter from ...lo.xml.x_import_filter import XImportFilter as XImportFilter", "NamespaceContainer from ...lo.xml.para_user_defined_attributes_supplier import ParaUserDefinedAttributesSupplier as ParaUserDefinedAttributesSupplier from ...lo.xml.text_user_defined_attributes_supplier import", "copy of the License at # # http: // www.apache.org/licenses/LICENSE-2.0", "not use this file except in compliance with the License.", "www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "writing, software # distributed under the License is distributed on", "\"License\") # you may not use this file except in", "in writing, software # distributed under the License is distributed", "you may not use this file except in compliance with", "as XImportFilter from ...lo.xml.x_import_filter2 import XImportFilter2 as XImportFilter2 from ...lo.xml.xml_export_filter", "from ...lo.xml.para_user_defined_attributes_supplier import ParaUserDefinedAttributesSupplier as ParaUserDefinedAttributesSupplier from ...lo.xml.text_user_defined_attributes_supplier import TextUserDefinedAttributesSupplier", "from ...lo.xml.user_defined_attributes_supplier import UserDefinedAttributesSupplier as UserDefinedAttributesSupplier from ...lo.xml.x_export_filter import XExportFilter", "a copy of the License at # # http: //", "UserDefinedAttributesSupplier as UserDefinedAttributesSupplier from ...lo.xml.x_export_filter import XExportFilter as XExportFilter from", "...lo.xml.x_import_filter2 import XImportFilter2 as XImportFilter2 from ...lo.xml.xml_export_filter import XMLExportFilter as", "...lo.xml.x_export_filter import XExportFilter as XExportFilter from ...lo.xml.x_import_filter import XImportFilter as", "the Apache License, Version 2.0 (the \"License\") # you may", "from ...lo.xml.attribute_container import AttributeContainer as AttributeContainer from ...lo.xml.attribute_data import AttributeData", "ParaUserDefinedAttributesSupplier from ...lo.xml.text_user_defined_attributes_supplier import TextUserDefinedAttributesSupplier as TextUserDefinedAttributesSupplier from ...lo.xml.user_defined_attributes_supplier import", "use this file except in compliance with the License. #", "// www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "under the License. # from ...lo.xml.attribute import Attribute as Attribute", "from ...lo.xml.text_user_defined_attributes_supplier import TextUserDefinedAttributesSupplier as TextUserDefinedAttributesSupplier from ...lo.xml.user_defined_attributes_supplier import UserDefinedAttributesSupplier", "AttributeContainer from ...lo.xml.attribute_data import AttributeData as AttributeData from ...lo.xml.export_filter import", "coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # #", "as ExportFilter from ...lo.xml.fast_attribute import FastAttribute as FastAttribute from ...lo.xml.import_filter", "CONDITIONS OF ANY KIND, either express or implied. # See", "import TextUserDefinedAttributesSupplier as TextUserDefinedAttributesSupplier from ...lo.xml.user_defined_attributes_supplier import UserDefinedAttributesSupplier as UserDefinedAttributesSupplier", "# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss #", "import XMLExportFilter as XMLExportFilter from ...lo.xml.xml_import_filter import XMLImportFilter as XMLImportFilter", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "...lo.xml.text_user_defined_attributes_supplier import TextUserDefinedAttributesSupplier as TextUserDefinedAttributesSupplier from ...lo.xml.user_defined_attributes_supplier import UserDefinedAttributesSupplier as", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "UserDefinedAttributesSupplier from ...lo.xml.x_export_filter import XExportFilter as XExportFilter from ...lo.xml.x_import_filter import", "# You may obtain a copy of the License at", "FastAttribute from ...lo.xml.import_filter import ImportFilter as ImportFilter from ...lo.xml.namespace_container import", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "2022 :Barry-Thomas-Paul: Moss # # Licensed under the Apache License,", "2.0 (the \"License\") # you may not use this file", "# # http: // www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "...lo.xml.attribute_container import AttributeContainer as AttributeContainer from ...lo.xml.attribute_data import AttributeData as", "obtain a copy of the License at # # http:", "under the License is distributed on an \"AS IS\" BASIS,", "ImportFilter from ...lo.xml.namespace_container import NamespaceContainer as NamespaceContainer from ...lo.xml.para_user_defined_attributes_supplier import", "# # Copyright 2022 :Barry-Thomas-Paul: Moss # # Licensed under", "License for the specific language governing permissions and # limitations", "ExportFilter as ExportFilter from ...lo.xml.fast_attribute import FastAttribute as FastAttribute from", "...lo.xml.fast_attribute import FastAttribute as FastAttribute from ...lo.xml.import_filter import ImportFilter as", "Licensed under the Apache License, Version 2.0 (the \"License\") #", "import NamespaceContainer as NamespaceContainer from ...lo.xml.para_user_defined_attributes_supplier import ParaUserDefinedAttributesSupplier as ParaUserDefinedAttributesSupplier", "import XImportFilter as XImportFilter from ...lo.xml.x_import_filter2 import XImportFilter2 as XImportFilter2", "the License for the specific language governing permissions and #", "License. # from ...lo.xml.attribute import Attribute as Attribute from ...lo.xml.attribute_container", "# Licensed under the Apache License, Version 2.0 (the \"License\")", "AttributeContainer as AttributeContainer from ...lo.xml.attribute_data import AttributeData as AttributeData from", "...lo.xml.attribute_data import AttributeData as AttributeData from ...lo.xml.export_filter import ExportFilter as", "import ExportFilter as ExportFilter from ...lo.xml.fast_attribute import FastAttribute as FastAttribute", "# you may not use this file except in compliance", "either express or implied. # See the License for the", "import AttributeData as AttributeData from ...lo.xml.export_filter import ExportFilter as ExportFilter", "OR CONDITIONS OF ANY KIND, either express or implied. #", "XExportFilter as XExportFilter from ...lo.xml.x_import_filter import XImportFilter as XImportFilter from", "NamespaceContainer as NamespaceContainer from ...lo.xml.para_user_defined_attributes_supplier import ParaUserDefinedAttributesSupplier as ParaUserDefinedAttributesSupplier from", "from ...lo.xml.x_import_filter2 import XImportFilter2 as XImportFilter2 from ...lo.xml.xml_export_filter import XMLExportFilter", "AttributeData as AttributeData from ...lo.xml.export_filter import ExportFilter as ExportFilter from", "the License is distributed on an \"AS IS\" BASIS, #", "in compliance with the License. # You may obtain a", "governing permissions and # limitations under the License. # from", "software # distributed under the License is distributed on an", "FastAttribute as FastAttribute from ...lo.xml.import_filter import ImportFilter as ImportFilter from", "import ImportFilter as ImportFilter from ...lo.xml.namespace_container import NamespaceContainer as NamespaceContainer", "from ...lo.xml.attribute import Attribute as Attribute from ...lo.xml.attribute_container import AttributeContainer", "# # Unless required by applicable law or agreed to", "and # limitations under the License. # from ...lo.xml.attribute import", "XExportFilter from ...lo.xml.x_import_filter import XImportFilter as XImportFilter from ...lo.xml.x_import_filter2 import", "(the \"License\") # you may not use this file except", "...lo.xml.para_user_defined_attributes_supplier import ParaUserDefinedAttributesSupplier as ParaUserDefinedAttributesSupplier from ...lo.xml.text_user_defined_attributes_supplier import TextUserDefinedAttributesSupplier as", "...lo.xml.user_defined_attributes_supplier import UserDefinedAttributesSupplier as UserDefinedAttributesSupplier from ...lo.xml.x_export_filter import XExportFilter as", "from ...lo.xml.namespace_container import NamespaceContainer as NamespaceContainer from ...lo.xml.para_user_defined_attributes_supplier import ParaUserDefinedAttributesSupplier", "Moss # # Licensed under the Apache License, Version 2.0", "http: // www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "import FastAttribute as FastAttribute from ...lo.xml.import_filter import ImportFilter as ImportFilter", "Attribute as Attribute from ...lo.xml.attribute_container import AttributeContainer as AttributeContainer from", "import AttributeContainer as AttributeContainer from ...lo.xml.attribute_data import AttributeData as AttributeData", "as AttributeData from ...lo.xml.export_filter import ExportFilter as ExportFilter from ...lo.xml.fast_attribute", "law or agreed to in writing, software # distributed under", "...lo.xml.attribute import Attribute as Attribute from ...lo.xml.attribute_container import AttributeContainer as", "import Attribute as Attribute from ...lo.xml.attribute_container import AttributeContainer as AttributeContainer", "...lo.xml.export_filter import ExportFilter as ExportFilter from ...lo.xml.fast_attribute import FastAttribute as", "# from ...lo.xml.attribute import Attribute as Attribute from ...lo.xml.attribute_container import", "import XImportFilter2 as XImportFilter2 from ...lo.xml.xml_export_filter import XMLExportFilter as XMLExportFilter", "implied. # See the License for the specific language governing", "as Attribute from ...lo.xml.attribute_container import AttributeContainer as AttributeContainer from ...lo.xml.attribute_data", "limitations under the License. # from ...lo.xml.attribute import Attribute as", "TextUserDefinedAttributesSupplier as TextUserDefinedAttributesSupplier from ...lo.xml.user_defined_attributes_supplier import UserDefinedAttributesSupplier as UserDefinedAttributesSupplier from", "# limitations under the License. # from ...lo.xml.attribute import Attribute", "# http: // www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "as UserDefinedAttributesSupplier from ...lo.xml.x_export_filter import XExportFilter as XExportFilter from ...lo.xml.x_import_filter", "as TextUserDefinedAttributesSupplier from ...lo.xml.user_defined_attributes_supplier import UserDefinedAttributesSupplier as UserDefinedAttributesSupplier from ...lo.xml.x_export_filter", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "...lo.xml.xml_export_filter import XMLExportFilter as XMLExportFilter from ...lo.xml.xml_import_filter import XMLImportFilter as", "XImportFilter as XImportFilter from ...lo.xml.x_import_filter2 import XImportFilter2 as XImportFilter2 from", "from ...lo.xml.x_export_filter import XExportFilter as XExportFilter from ...lo.xml.x_import_filter import XImportFilter", ":Barry-Thomas-Paul: Moss # # Licensed under the Apache License, Version", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "from ...lo.xml.x_import_filter import XImportFilter as XImportFilter from ...lo.xml.x_import_filter2 import XImportFilter2", "...lo.xml.x_import_filter import XImportFilter as XImportFilter from ...lo.xml.x_import_filter2 import XImportFilter2 as", "XImportFilter2 as XImportFilter2 from ...lo.xml.xml_export_filter import XMLExportFilter as XMLExportFilter from", "Apache License, Version 2.0 (the \"License\") # you may not", "the License. # You may obtain a copy of the", "for the specific language governing permissions and # limitations under", "from ...lo.xml.fast_attribute import FastAttribute as FastAttribute from ...lo.xml.import_filter import ImportFilter", "at # # http: // www.apache.org/licenses/LICENSE-2.0 # # Unless required", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "TextUserDefinedAttributesSupplier from ...lo.xml.user_defined_attributes_supplier import UserDefinedAttributesSupplier as UserDefinedAttributesSupplier from ...lo.xml.x_export_filter import", "to in writing, software # distributed under the License is", "import UserDefinedAttributesSupplier as UserDefinedAttributesSupplier from ...lo.xml.x_export_filter import XExportFilter as XExportFilter", "ExportFilter from ...lo.xml.fast_attribute import FastAttribute as FastAttribute from ...lo.xml.import_filter import", "under the Apache License, Version 2.0 (the \"License\") # you", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "<reponame>Amourspirit/ooo_uno_tmpl<filename>ooobuild/csslo/xml/__init__.py # coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss", "as XExportFilter from ...lo.xml.x_import_filter import XImportFilter as XImportFilter from ...lo.xml.x_import_filter2", "You may obtain a copy of the License at #", "import ParaUserDefinedAttributesSupplier as ParaUserDefinedAttributesSupplier from ...lo.xml.text_user_defined_attributes_supplier import TextUserDefinedAttributesSupplier as TextUserDefinedAttributesSupplier", "language governing permissions and # limitations under the License. #", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "as FastAttribute from ...lo.xml.import_filter import ImportFilter as ImportFilter from ...lo.xml.namespace_container", "Copyright 2022 :Barry-Thomas-Paul: Moss # # Licensed under the Apache", "...lo.xml.import_filter import ImportFilter as ImportFilter from ...lo.xml.namespace_container import NamespaceContainer as", "ImportFilter as ImportFilter from ...lo.xml.namespace_container import NamespaceContainer as NamespaceContainer from", "required by applicable law or agreed to in writing, software", "the License at # # http: // www.apache.org/licenses/LICENSE-2.0 # #", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "with the License. # You may obtain a copy of", "from ...lo.xml.xml_export_filter import XMLExportFilter as XMLExportFilter from ...lo.xml.xml_import_filter import XMLImportFilter", "# Copyright 2022 :Barry-Thomas-Paul: Moss # # Licensed under the", "this file except in compliance with the License. # You", "Attribute from ...lo.xml.attribute_container import AttributeContainer as AttributeContainer from ...lo.xml.attribute_data import", "License, Version 2.0 (the \"License\") # you may not use", "XImportFilter from ...lo.xml.x_import_filter2 import XImportFilter2 as XImportFilter2 from ...lo.xml.xml_export_filter import", "as AttributeContainer from ...lo.xml.attribute_data import AttributeData as AttributeData from ...lo.xml.export_filter" ]
[ "utf-8 -*- # Generated by Django 1.9.6 on 2016-09-27 15:35", "2016-09-27 15:35 from __future__ import unicode_literals from django.db import migrations", "# -*- coding: utf-8 -*- # Generated by Django 1.9.6", "from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):", "class Migration(migrations.Migration): dependencies = [ ('tasks', '0011_auto_20160919_1508'), ('tasks', '0011_auto_20160920_1019'), ]", "1.9.6 on 2016-09-27 15:35 from __future__ import unicode_literals from django.db", "-*- coding: utf-8 -*- # Generated by Django 1.9.6 on", "15:35 from __future__ import unicode_literals from django.db import migrations class", "[ ('tasks', '0011_auto_20160919_1508'), ('tasks', '0011_auto_20160920_1019'), ] operations = [ ]", "by Django 1.9.6 on 2016-09-27 15:35 from __future__ import unicode_literals", "unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [", "import migrations class Migration(migrations.Migration): dependencies = [ ('tasks', '0011_auto_20160919_1508'), ('tasks',", "coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-09-27", "django.db import migrations class Migration(migrations.Migration): dependencies = [ ('tasks', '0011_auto_20160919_1508'),", "from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('tasks',", "on 2016-09-27 15:35 from __future__ import unicode_literals from django.db import", "# Generated by Django 1.9.6 on 2016-09-27 15:35 from __future__", "import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies =", "-*- # Generated by Django 1.9.6 on 2016-09-27 15:35 from", "__future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies", "Generated by Django 1.9.6 on 2016-09-27 15:35 from __future__ import", "Django 1.9.6 on 2016-09-27 15:35 from __future__ import unicode_literals from", "Migration(migrations.Migration): dependencies = [ ('tasks', '0011_auto_20160919_1508'), ('tasks', '0011_auto_20160920_1019'), ] operations", "= [ ('tasks', '0011_auto_20160919_1508'), ('tasks', '0011_auto_20160920_1019'), ] operations = [", "migrations class Migration(migrations.Migration): dependencies = [ ('tasks', '0011_auto_20160919_1508'), ('tasks', '0011_auto_20160920_1019'),", "dependencies = [ ('tasks', '0011_auto_20160919_1508'), ('tasks', '0011_auto_20160920_1019'), ] operations =" ]
[ "returns precision: fraction of retrieved instances that are relevant. recall:", "= np.where(within_overlap[:, jj])[0] # get the indices of all valid", "recall[np.isnan(recall)] = 0 # pascal'12 way mprec = np.hstack((0, precision,", "all the probability values are the same therefore we will", "are relevant. recall: fraction of relevant instances that are retrieved.", "value true_pos_sum = true_pos_cat.sum() false_pos_sum = false_pos_cat.sum() recall = np.asarray([true_pos_sum", "produce a list of values true_pos_cum = np.cumsum(true_pos_cat) false_pos_cum =", "values are the same therefore we will not sweep #", "the number of files with each entry containing that file", "win_size is used to ignore predictions and ground truth at", "= np.asarray([true_pos_sum / float(num_gt)]) precision = np.asarray([(true_pos_sum / (false_pos_sum +", "are the same therefore we will not sweep # the", "the end of an audio file. returns precision: fraction of", "np.concatenate(nms_prob)[:, 0] num_gt = np.concatenate(gt_pos).shape[0] inds = np.argsort(conf)[::-1] true_pos_cat =", "numpy arrays specifying detection position, detection probability and GT position.", "nms_prob, gt_pos def prec_recall_1d(nms_pos_o, nms_prob_o, gt_pos_o, durations, detection_overlap, win_size, remove_eof=True):", "loop through each file true_pos = [] # correctly predicts", "nms_prob = [] gt_pos = [] for ii in range(len(nms_pos_o)):", "> 0: max_prob = np.argmax(nms_prob[ii][inds]) selected_pred = inds[max_prob] within_overlap[selected_pred, :]", "return nms_pos, nms_prob, gt_pos def prec_recall_1d(nms_pos_o, nms_prob_o, gt_pos_o, durations, detection_overlap,", "durations, detection_overlap, win_size, remove_eof=True): \"\"\" nms_pos, nms_prob, and gt_pos are", "mrec[inds-1])*mprec[inds]).sum() return ave_prec def remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size): #", "= durations[ii] - win_size gt_cur = gt_pos_o[ii] if gt_cur.shape[0] >", "that are too # close to the end of the", "% (class_acc, roc_auc) #return class_acc, roc_auc def calc_average_precision(recall, precision): precision[np.isnan(precision)]", "= true_pos_cum / float(num_gt) precision = (true_pos_cum / (false_pos_cum +", "ii in range(len(nms_pos)): num_preds = nms_pos[ii].shape[0] if num_preds > 0:", "= np.concatenate(true_pos)[inds].astype(float) false_pos_cat = np.concatenate(false_pos)[inds].astype(float) # i.e. 1-true_pos_cat if (conf", "ground truth at the end of an audio file. returns", "fraction of retrieved instances that are relevant. recall: fraction of", "false_pos_cum = np.cumsum(false_pos_cat) recall = true_pos_cum / float(num_gt) precision =", "duplicate detections - assign to valid detection with highest prob", "= np.argsort(conf)[::-1] true_pos_cat = np.concatenate(true_pos)[inds].astype(float) false_pos_cat = np.concatenate(false_pos)[inds].astype(float) # i.e.", "== conf[0]).sum() == conf.shape[0]: # all the probability values are", "roc_auc) #return class_acc, roc_auc def calc_average_precision(recall, precision): precision[np.isnan(precision)] = 0", "# check to make sure it contains something num_gt =", "error pred_int = (pred > prob).astype(np.int) class_acc = (pred_int ==", "bit messy because of the shapes of gt_pos_o nms_pos =", "# i.e. 1-true_pos_cat if (conf == conf[0]).sum() == conf.shape[0]: #", "predictions label them as true positive or false positive (i.e.", "0)) mrec = np.hstack((0, recall, 1)) for ii in range(mprec.shape[0]-2,", "remove_eof=True): \"\"\" nms_pos, nms_prob, and gt_pos are lists of numpy", "a different file. Each entry in nms_pos is an array", "nms_pos_o nms_prob = nms_prob_o gt_pos = gt_pos_o # loop through", "= gt_pos_o[ii] if gt_cur.shape[0] > 0: gt_pos.append(gt_cur[:, 0][gt_cur[:, 0] <", "curve fpr, tpr, thresholds = roc_curve(gt, pred) roc_auc = auc(fpr,", "true_pos_cat.sum() false_pos_sum = false_pos_cat.sum() recall = np.asarray([true_pos_sum / float(num_gt)]) precision", "out the detections in both ground truth and predictions that", "gt, pred, prob): # classification error pred_int = (pred >", "AUC = %.3f' % (class_acc, roc_auc) #return class_acc, roc_auc def", "mprec[ii+1]) inds = np.where(np.not_equal(mrec[1:], mrec[:-1]))[0]+1 ave_prec = ((mrec[inds] - mrec[inds-1])*mprec[inds]).sum()", "auc def compute_error_auc(op_str, gt, pred, prob): # classification error pred_int", "position. Each list entry is a different file. Each entry", "1-true_pos_cat if (conf == conf[0]).sum() == conf.shape[0]: # all the", "# pascal'12 way mprec = np.hstack((0, precision, 0)) mrec =", "[] gt_pos = [] for ii in range(len(nms_pos_o)): valid_time =", "', class acc = %.3f, ROC AUC = %.3f' %", "single value true_pos_sum = true_pos_cat.sum() false_pos_sum = false_pos_cat.sum() recall =", "= np.cumsum(true_pos_cat) false_pos_cum = np.cumsum(false_pos_cat) recall = true_pos_cum / float(num_gt)", "class_acc = (pred_int == gt).mean() * 100.0 # ROC -", "true_pos_sum))]) elif inds.shape[0] > 0: # otherwise produce a list", "roc_curve, auc def compute_error_auc(op_str, gt, pred, prob): # classification error", "curve and instead will return a single value true_pos_sum =", "gt_pos its an array of size (num_entries, 1). durations is", "correctly predicts the ground truth false_pos = [] # says", "filters out predictions and gt that are close to the", "nms_prob_o, gt_pos_o, durations, detection_overlap, win_size, remove_eof=True): \"\"\" nms_pos, nms_prob, and", "in nms_pos is an array of length num_entries. For nms_prob", "that are relevant. recall: fraction of relevant instances that are", "np.abs(gt_pos[ii].ravel()-nms_pos[ii].ravel()[:, np.newaxis]) within_overlap = (distance_to_gt <= detection_overlap) # remove duplicate", "are too # close to the end of the file", "(i.e. 1-tp) tp = np.zeros(num_preds) distance_to_gt = np.abs(gt_pos[ii].ravel()-nms_pos[ii].ravel()[:, np.newaxis]) within_overlap", "end of an audio file. returns precision: fraction of retrieved", "fraction of relevant instances that are retrieved. \"\"\" if remove_eof:", "for ii in range(mprec.shape[0]-2, -1,-1): mprec[ii] = np.maximum(mprec[ii], mprec[ii+1]) inds", "def prec_recall_1d(nms_pos_o, nms_prob_o, gt_pos_o, durations, detection_overlap, win_size, remove_eof=True): \"\"\" nms_pos,", "- tp) # calc precision and recall - sort confidence", "predictions that are too # close to the end of", "= False tp[selected_pred] = 1 # set as true positives", "indices of all valid predictions if inds.shape[0] > 0: max_prob", "if gt_cur.shape[0] > 0: gt_pos.append(gt_cur[:, 0][gt_cur[:, 0] < valid_time][..., np.newaxis])", "false positive (i.e. 1-tp) tp = np.zeros(num_preds) distance_to_gt = np.abs(gt_pos[ii].ravel()-nms_pos[ii].ravel()[:,", "truth false_pos = [] # says there is a detection", "or not. win_size is used to ignore predictions and ground", "# the curve and instead will return a single value", "= 0 # pascal'12 way mprec = np.hstack((0, precision, 0))", "(false_pos_sum + true_pos_sum))]) elif inds.shape[0] > 0: # otherwise produce", "will return a single value true_pos_sum = true_pos_cat.sum() false_pos_sum =", "get the indices of all valid predictions if inds.shape[0] >", "win_size): # this filters out predictions and gt that are", "def calc_average_precision(recall, precision): precision[np.isnan(precision)] = 0 recall[np.isnan(recall)] = 0 #", "detection_overlap, win_size, remove_eof=True): \"\"\" nms_pos, nms_prob, and gt_pos are lists", "detection_overlap) # remove duplicate detections - assign to valid detection", "sort confidence in descending order # PASCAL style conf =", "pred) roc_auc = auc(fpr, tpr) print op_str, ', class acc", "= (distance_to_gt <= detection_overlap) # remove duplicate detections - assign", "# filter out the detections in both ground truth and", "retrieved. \"\"\" if remove_eof: # filter out the detections in", "win_size, remove_eof=True): \"\"\" nms_pos, nms_prob, and gt_pos are lists of", ":] = False tp[selected_pred] = 1 # set as true", "= 1 # set as true positives true_pos.append(tp) false_pos.append(1 -", "= np.concatenate(false_pos)[inds].astype(float) # i.e. 1-true_pos_cat if (conf == conf[0]).sum() ==", "length of the number of files with each entry containing", "acc = %.3f, ROC AUC = %.3f' % (class_acc, roc_auc)", "= nms_pos_o[ii] < valid_time nms_pos.append(nms_pos_o[ii][valid_preds]) nms_prob.append(nms_prob_o[ii][valid_preds, 0][..., np.newaxis]) return nms_pos,", "class acc = %.3f, ROC AUC = %.3f' % (class_acc,", "false_pos_cat.sum() recall = np.asarray([true_pos_sum / float(num_gt)]) precision = np.asarray([(true_pos_sum /", "descending order # PASCAL style conf = np.concatenate(nms_prob)[:, 0] num_gt", "0][..., np.newaxis]) return nms_pos, nms_prob, gt_pos def prec_recall_1d(nms_pos_o, nms_prob_o, gt_pos_o,", "the probability values are the same therefore we will not", "* 100.0 # ROC - area under curve fpr, tpr,", "containing that file length in seconds. detection_overlap determines if a", "tp = np.zeros(num_preds) distance_to_gt = np.abs(gt_pos[ii].ravel()-nms_pos[ii].ravel()[:, np.newaxis]) within_overlap = (distance_to_gt", "therefore we will not sweep # the curve and instead", "instead will return a single value true_pos_sum = true_pos_cat.sum() false_pos_sum", "nms_pos = nms_pos_o nms_prob = nms_prob_o gt_pos = gt_pos_o #", "different file. Each entry in nms_pos is an array of", "roc_auc def calc_average_precision(recall, precision): precision[np.isnan(precision)] = 0 recall[np.isnan(recall)] = 0", "ROC AUC = %.3f' % (class_acc, roc_auc) #return class_acc, roc_auc", "elif inds.shape[0] > 0: # otherwise produce a list of", "# this filters out predictions and gt that are close", "def compute_error_auc(op_str, gt, pred, prob): # classification error pred_int =", "gt_pos[ii].shape[0] # for each set of predictions label them as", "roc_curve(gt, pred) roc_auc = auc(fpr, tpr) print op_str, ', class", "and instead will return a single value true_pos_sum = true_pos_cat.sum()", "gt_pos_o, durations, win_size): # this filters out predictions and gt", "gt that are close to the end # this is", "but isn't for ii in range(len(nms_pos)): num_preds = nms_pos[ii].shape[0] if", "lists of numpy arrays specifying detection position, detection probability and", "# correctly predicts the ground truth false_pos = [] #", "# set as true positives true_pos.append(tp) false_pos.append(1 - tp) #", "distance_to_gt = np.abs(gt_pos[ii].ravel()-nms_pos[ii].ravel()[:, np.newaxis]) within_overlap = (distance_to_gt <= detection_overlap) #", "is a bit messy because of the shapes of gt_pos_o", "tpr) print op_str, ', class acc = %.3f, ROC AUC", "values true_pos_cum = np.cumsum(true_pos_cat) false_pos_cum = np.cumsum(false_pos_cat) recall = true_pos_cum", "= [] # correctly predicts the ground truth false_pos =", "seconds. detection_overlap determines if a prediction is counted as correct", "= np.where(np.not_equal(mrec[1:], mrec[:-1]))[0]+1 ave_prec = ((mrec[inds] - mrec[inds-1])*mprec[inds]).sum() return ave_prec", "size (num_entries, 1). durations is a array of the length", "the shapes of gt_pos_o nms_pos = [] nms_prob = []", "# says there is a detection but isn't for ii", "of the shapes of gt_pos_o nms_pos = [] nms_prob =", "False tp[selected_pred] = 1 # set as true positives true_pos.append(tp)", "auc(fpr, tpr) print op_str, ', class acc = %.3f, ROC", "in range(mprec.shape[0]-2, -1,-1): mprec[ii] = np.maximum(mprec[ii], mprec[ii+1]) inds = np.where(np.not_equal(mrec[1:],", "valid_time][..., np.newaxis]) else: gt_pos.append(gt_cur) valid_preds = nms_pos_o[ii] < valid_time nms_pos.append(nms_pos_o[ii][valid_preds])", "the indices of all valid predictions if inds.shape[0] > 0:", "contains something num_gt = gt_pos[ii].shape[0] # for each set of", "same therefore we will not sweep # the curve and", "nms_prob and gt_pos its an array of size (num_entries, 1).", "100.0 # ROC - area under curve fpr, tpr, thresholds", "filter out the detections in both ground truth and predictions", "calc precision and recall - sort confidence in descending order", "def remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size): # this filters out", "/ float(num_gt) precision = (true_pos_cum / (false_pos_cum + true_pos_cum)) return", "precision = (true_pos_cum / (false_pos_cum + true_pos_cum)) return precision, recall", "shapes of gt_pos_o nms_pos = [] nms_prob = [] gt_pos", "area under curve fpr, tpr, thresholds = roc_curve(gt, pred) roc_auc", "true positives true_pos.append(tp) false_pos.append(1 - tp) # calc precision and", "to the end # this is a bit messy because", "the same therefore we will not sweep # the curve", "np.newaxis]) return nms_pos, nms_prob, gt_pos def prec_recall_1d(nms_pos_o, nms_prob_o, gt_pos_o, durations,", "for each set of predictions label them as true positive", "((mrec[inds] - mrec[inds-1])*mprec[inds]).sum() return ave_prec def remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations,", "file - dont count them during eval nms_pos, nms_prob, gt_pos", "(conf == conf[0]).sum() == conf.shape[0]: # all the probability values", "For nms_prob and gt_pos its an array of size (num_entries,", "an array of size (num_entries, 1). durations is a array", "num_preds = nms_pos[ii].shape[0] if num_preds > 0: # check to", "= roc_curve(gt, pred) roc_auc = auc(fpr, tpr) print op_str, ',", "it contains something num_gt = gt_pos[ii].shape[0] # for each set", "ave_prec def remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size): # this filters", "and gt_pos its an array of size (num_entries, 1). durations", "range(len(nms_pos)): num_preds = nms_pos[ii].shape[0] if num_preds > 0: # check", "gt_pos.append(gt_cur) valid_preds = nms_pos_o[ii] < valid_time nms_pos.append(nms_pos_o[ii][valid_preds]) nms_prob.append(nms_prob_o[ii][valid_preds, 0][..., np.newaxis])", "np.cumsum(true_pos_cat) false_pos_cum = np.cumsum(false_pos_cat) recall = true_pos_cum / float(num_gt) precision", "= np.hstack((0, precision, 0)) mrec = np.hstack((0, recall, 1)) for", "# calc precision and recall - sort confidence in descending", "prediction is counted as correct or not. win_size is used", "num_gt = np.concatenate(gt_pos).shape[0] inds = np.argsort(conf)[::-1] true_pos_cat = np.concatenate(true_pos)[inds].astype(float) false_pos_cat", "> 0: # check to make sure it contains something", "pascal'12 way mprec = np.hstack((0, precision, 0)) mrec = np.hstack((0,", "prob): # classification error pred_int = (pred > prob).astype(np.int) class_acc", "the end of the file - dont count them during", "thresholds = roc_curve(gt, pred) roc_auc = auc(fpr, tpr) print op_str,", "(distance_to_gt <= detection_overlap) # remove duplicate detections - assign to", "close to the end # this is a bit messy", "is a different file. Each entry in nms_pos is an", "instances that are relevant. recall: fraction of relevant instances that", "np from sklearn.metrics import roc_curve, auc def compute_error_auc(op_str, gt, pred,", "of values true_pos_cum = np.cumsum(true_pos_cat) false_pos_cum = np.cumsum(false_pos_cat) recall =", "messy because of the shapes of gt_pos_o nms_pos = []", "= np.cumsum(false_pos_cat) recall = true_pos_cum / float(num_gt) precision = (true_pos_cum", "np.concatenate(true_pos)[inds].astype(float) false_pos_cat = np.concatenate(false_pos)[inds].astype(float) # i.e. 1-true_pos_cat if (conf ==", "[] # correctly predicts the ground truth false_pos = []", "in both ground truth and predictions that are too #", "determines if a prediction is counted as correct or not.", "within_overlap[selected_pred, :] = False tp[selected_pred] = 1 # set as", "end # this is a bit messy because of the", "true_pos_cum / float(num_gt) precision = (true_pos_cum / (false_pos_cum + true_pos_cum))", "roc_auc = auc(fpr, tpr) print op_str, ', class acc =", "for jj in range(num_gt): inds = np.where(within_overlap[:, jj])[0] # get", "np.newaxis]) else: gt_pos.append(gt_cur) valid_preds = nms_pos_o[ii] < valid_time nms_pos.append(nms_pos_o[ii][valid_preds]) nms_prob.append(nms_prob_o[ii][valid_preds,", "# close to the end of the file - dont", "- dont count them during eval nms_pos, nms_prob, gt_pos =", "import roc_curve, auc def compute_error_auc(op_str, gt, pred, prob): # classification", "conf = np.concatenate(nms_prob)[:, 0] num_gt = np.concatenate(gt_pos).shape[0] inds = np.argsort(conf)[::-1]", "= [] # says there is a detection but isn't", "that are close to the end # this is a", "<= detection_overlap) # remove duplicate detections - assign to valid", "precision, 0)) mrec = np.hstack((0, recall, 1)) for ii in", "retrieved instances that are relevant. recall: fraction of relevant instances", "%.3f' % (class_acc, roc_auc) #return class_acc, roc_auc def calc_average_precision(recall, precision):", "#return class_acc, roc_auc def calc_average_precision(recall, precision): precision[np.isnan(precision)] = 0 recall[np.isnan(recall)]", "positives true_pos.append(tp) false_pos.append(1 - tp) # calc precision and recall", "as true positives true_pos.append(tp) false_pos.append(1 - tp) # calc precision", "an audio file. returns precision: fraction of retrieved instances that", "float(num_gt)]) precision = np.asarray([(true_pos_sum / (false_pos_sum + true_pos_sum))]) elif inds.shape[0]", "end of the file - dont count them during eval", "tp) # calc precision and recall - sort confidence in", "true_pos = [] # correctly predicts the ground truth false_pos", "predictions and gt that are close to the end #", "np.hstack((0, recall, 1)) for ii in range(mprec.shape[0]-2, -1,-1): mprec[ii] =", "= [] nms_prob = [] gt_pos = [] for ii", "prob).astype(np.int) class_acc = (pred_int == gt).mean() * 100.0 # ROC", "inds = np.where(within_overlap[:, jj])[0] # get the indices of all", "its an array of size (num_entries, 1). durations is a", "specifying detection position, detection probability and GT position. Each list", "detection with highest prob for jj in range(num_gt): inds =", "the curve and instead will return a single value true_pos_sum", "remove_eof: # filter out the detections in both ground truth", "the end # this is a bit messy because of", "for ii in range(len(nms_pos_o)): valid_time = durations[ii] - win_size gt_cur", "them as true positive or false positive (i.e. 1-tp) tp", "audio file. returns precision: fraction of retrieved instances that are", "file true_pos = [] # correctly predicts the ground truth", "sklearn.metrics import roc_curve, auc def compute_error_auc(op_str, gt, pred, prob): #", "set as true positives true_pos.append(tp) false_pos.append(1 - tp) # calc", "detections in both ground truth and predictions that are too", "np.zeros(num_preds) distance_to_gt = np.abs(gt_pos[ii].ravel()-nms_pos[ii].ravel()[:, np.newaxis]) within_overlap = (distance_to_gt <= detection_overlap)", "< valid_time nms_pos.append(nms_pos_o[ii][valid_preds]) nms_prob.append(nms_prob_o[ii][valid_preds, 0][..., np.newaxis]) return nms_pos, nms_prob, gt_pos", "= np.hstack((0, recall, 1)) for ii in range(mprec.shape[0]-2, -1,-1): mprec[ii]", "selected_pred = inds[max_prob] within_overlap[selected_pred, :] = False tp[selected_pred] = 1", "np.hstack((0, precision, 0)) mrec = np.hstack((0, recall, 1)) for ii", "/ (false_pos_sum + true_pos_sum))]) elif inds.shape[0] > 0: # otherwise", "- mrec[inds-1])*mprec[inds]).sum() return ave_prec def remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size):", "length num_entries. For nms_prob and gt_pos its an array of", "1)) for ii in range(mprec.shape[0]-2, -1,-1): mprec[ii] = np.maximum(mprec[ii], mprec[ii+1])", "num_gt = gt_pos[ii].shape[0] # for each set of predictions label", "and gt_pos are lists of numpy arrays specifying detection position,", "conf.shape[0]: # all the probability values are the same therefore", "np.concatenate(false_pos)[inds].astype(float) # i.e. 1-true_pos_cat if (conf == conf[0]).sum() == conf.shape[0]:", "valid_preds = nms_pos_o[ii] < valid_time nms_pos.append(nms_pos_o[ii][valid_preds]) nms_prob.append(nms_prob_o[ii][valid_preds, 0][..., np.newaxis]) return", "nms_prob.append(nms_prob_o[ii][valid_preds, 0][..., np.newaxis]) return nms_pos, nms_prob, gt_pos def prec_recall_1d(nms_pos_o, nms_prob_o,", "# loop through each file true_pos = [] # correctly", "0: max_prob = np.argmax(nms_prob[ii][inds]) selected_pred = inds[max_prob] within_overlap[selected_pred, :] =", "gt).mean() * 100.0 # ROC - area under curve fpr,", "gt_pos are lists of numpy arrays specifying detection position, detection", "%.3f, ROC AUC = %.3f' % (class_acc, roc_auc) #return class_acc,", "inds[max_prob] within_overlap[selected_pred, :] = False tp[selected_pred] = 1 # set", "valid_time nms_pos.append(nms_pos_o[ii][valid_preds]) nms_prob.append(nms_prob_o[ii][valid_preds, 0][..., np.newaxis]) return nms_pos, nms_prob, gt_pos def", "# ROC - area under curve fpr, tpr, thresholds =", "assign to valid detection with highest prob for jj in", "class_acc, roc_auc def calc_average_precision(recall, precision): precision[np.isnan(precision)] = 0 recall[np.isnan(recall)] =", "win_size gt_cur = gt_pos_o[ii] if gt_cur.shape[0] > 0: gt_pos.append(gt_cur[:, 0][gt_cur[:,", "of numpy arrays specifying detection position, detection probability and GT", "ii in range(len(nms_pos_o)): valid_time = durations[ii] - win_size gt_cur =", "precision: fraction of retrieved instances that are relevant. recall: fraction", "ground truth and predictions that are too # close to", "= np.concatenate(gt_pos).shape[0] inds = np.argsort(conf)[::-1] true_pos_cat = np.concatenate(true_pos)[inds].astype(float) false_pos_cat =", "0: # otherwise produce a list of values true_pos_cum =", "= nms_prob_o gt_pos = gt_pos_o # loop through each file", "gt_pos_o, durations, detection_overlap, win_size, remove_eof=True): \"\"\" nms_pos, nms_prob, and gt_pos", "of relevant instances that are retrieved. \"\"\" if remove_eof: #", "not sweep # the curve and instead will return a", "style conf = np.concatenate(nms_prob)[:, 0] num_gt = np.concatenate(gt_pos).shape[0] inds =", "gt_pos_o[ii] if gt_cur.shape[0] > 0: gt_pos.append(gt_cur[:, 0][gt_cur[:, 0] < valid_time][...,", "fpr, tpr, thresholds = roc_curve(gt, pred) roc_auc = auc(fpr, tpr)", "= nms_pos[ii].shape[0] if num_preds > 0: # check to make", "mprec = np.hstack((0, precision, 0)) mrec = np.hstack((0, recall, 1))", "of files with each entry containing that file length in", "if (conf == conf[0]).sum() == conf.shape[0]: # all the probability", "and predictions that are too # close to the end", "precision[np.isnan(precision)] = 0 recall[np.isnan(recall)] = 0 # pascal'12 way mprec", "jj])[0] # get the indices of all valid predictions if", "mrec[:-1]))[0]+1 ave_prec = ((mrec[inds] - mrec[inds-1])*mprec[inds]).sum() return ave_prec def remove_end_preds(nms_pos_o,", "= np.zeros(num_preds) distance_to_gt = np.abs(gt_pos[ii].ravel()-nms_pos[ii].ravel()[:, np.newaxis]) within_overlap = (distance_to_gt <=", "file. returns precision: fraction of retrieved instances that are relevant.", "recall, 1)) for ii in range(mprec.shape[0]-2, -1,-1): mprec[ii] = np.maximum(mprec[ii],", "this is a bit messy because of the shapes of", "[] for ii in range(len(nms_pos_o)): valid_time = durations[ii] - win_size", "during eval nms_pos, nms_prob, gt_pos = remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations,", "inds = np.where(np.not_equal(mrec[1:], mrec[:-1]))[0]+1 ave_prec = ((mrec[inds] - mrec[inds-1])*mprec[inds]).sum() return", "of the number of files with each entry containing that", "remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size): # this filters out predictions", "np.maximum(mprec[ii], mprec[ii+1]) inds = np.where(np.not_equal(mrec[1:], mrec[:-1]))[0]+1 ave_prec = ((mrec[inds] -", "with each entry containing that file length in seconds. detection_overlap", "list of values true_pos_cum = np.cumsum(true_pos_cat) false_pos_cum = np.cumsum(false_pos_cat) recall", "inds = np.argsort(conf)[::-1] true_pos_cat = np.concatenate(true_pos)[inds].astype(float) false_pos_cat = np.concatenate(false_pos)[inds].astype(float) #", "each file true_pos = [] # correctly predicts the ground", "of an audio file. returns precision: fraction of retrieved instances", "nms_pos, nms_prob, gt_pos def prec_recall_1d(nms_pos_o, nms_prob_o, gt_pos_o, durations, detection_overlap, win_size,", "= inds[max_prob] within_overlap[selected_pred, :] = False tp[selected_pred] = 1 #", "is an array of length num_entries. For nms_prob and gt_pos", "0: # check to make sure it contains something num_gt", "list entry is a different file. Each entry in nms_pos", "valid predictions if inds.shape[0] > 0: max_prob = np.argmax(nms_prob[ii][inds]) selected_pred", "the detections in both ground truth and predictions that are", "of all valid predictions if inds.shape[0] > 0: max_prob =", "= auc(fpr, tpr) print op_str, ', class acc = %.3f,", "is counted as correct or not. win_size is used to", "ignore predictions and ground truth at the end of an", "isn't for ii in range(len(nms_pos)): num_preds = nms_pos[ii].shape[0] if num_preds", "range(mprec.shape[0]-2, -1,-1): mprec[ii] = np.maximum(mprec[ii], mprec[ii+1]) inds = np.where(np.not_equal(mrec[1:], mrec[:-1]))[0]+1", "number of files with each entry containing that file length", "nms_prob = nms_prob_o gt_pos = gt_pos_o # loop through each", "conf[0]).sum() == conf.shape[0]: # all the probability values are the", "false_pos.append(1 - tp) # calc precision and recall - sort", "a array of the length of the number of files", "nms_pos[ii].shape[0] if num_preds > 0: # check to make sure", "(pred > prob).astype(np.int) class_acc = (pred_int == gt).mean() * 100.0", "as true positive or false positive (i.e. 1-tp) tp =", "Each entry in nms_pos is an array of length num_entries.", "= (pred > prob).astype(np.int) class_acc = (pred_int == gt).mean() *", "of the length of the number of files with each", "in descending order # PASCAL style conf = np.concatenate(nms_prob)[:, 0]", "way mprec = np.hstack((0, precision, 0)) mrec = np.hstack((0, recall,", "to the end of the file - dont count them", "the length of the number of files with each entry", "truth and predictions that are too # close to the", "recall = true_pos_cum / float(num_gt) precision = (true_pos_cum / (false_pos_cum", "pred, prob): # classification error pred_int = (pred > prob).astype(np.int)", "both ground truth and predictions that are too # close", "gt_pos = gt_pos_o # loop through each file true_pos =", "= %.3f' % (class_acc, roc_auc) #return class_acc, roc_auc def calc_average_precision(recall,", "recall: fraction of relevant instances that are retrieved. \"\"\" if", "== gt).mean() * 100.0 # ROC - area under curve", "probability values are the same therefore we will not sweep", "array of length num_entries. For nms_prob and gt_pos its an", "= gt_pos_o # loop through each file true_pos = []", "gt_pos def prec_recall_1d(nms_pos_o, nms_prob_o, gt_pos_o, durations, detection_overlap, win_size, remove_eof=True): \"\"\"", "a list of values true_pos_cum = np.cumsum(true_pos_cat) false_pos_cum = np.cumsum(false_pos_cat)", "nms_prob_o, gt_pos_o, durations, win_size): # this filters out predictions and", "> 0: gt_pos.append(gt_cur[:, 0][gt_cur[:, 0] < valid_time][..., np.newaxis]) else: gt_pos.append(gt_cur)", "that are retrieved. \"\"\" if remove_eof: # filter out the", "too # close to the end of the file -", "= [] for ii in range(len(nms_pos_o)): valid_time = durations[ii] -", "calc_average_precision(recall, precision): precision[np.isnan(precision)] = 0 recall[np.isnan(recall)] = 0 # pascal'12", "relevant instances that are retrieved. \"\"\" if remove_eof: # filter", "with highest prob for jj in range(num_gt): inds = np.where(within_overlap[:,", "all valid predictions if inds.shape[0] > 0: max_prob = np.argmax(nms_prob[ii][inds])", "= np.concatenate(nms_prob)[:, 0] num_gt = np.concatenate(gt_pos).shape[0] inds = np.argsort(conf)[::-1] true_pos_cat", "is a array of the length of the number of", "# this is a bit messy because of the shapes", "= gt_pos[ii].shape[0] # for each set of predictions label them", "> 0: # otherwise produce a list of values true_pos_cum", "recall = np.asarray([true_pos_sum / float(num_gt)]) precision = np.asarray([(true_pos_sum / (false_pos_sum", "length in seconds. detection_overlap determines if a prediction is counted", "np.where(within_overlap[:, jj])[0] # get the indices of all valid predictions", "i.e. 1-true_pos_cat if (conf == conf[0]).sum() == conf.shape[0]: # all", "op_str, ', class acc = %.3f, ROC AUC = %.3f'", "of size (num_entries, 1). durations is a array of the", "0 # pascal'12 way mprec = np.hstack((0, precision, 0)) mrec", "them during eval nms_pos, nms_prob, gt_pos = remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o,", "probability and GT position. Each list entry is a different", "true positive or false positive (i.e. 1-tp) tp = np.zeros(num_preds)", "0] num_gt = np.concatenate(gt_pos).shape[0] inds = np.argsort(conf)[::-1] true_pos_cat = np.concatenate(true_pos)[inds].astype(float)", "file. Each entry in nms_pos is an array of length", "(num_entries, 1). durations is a array of the length of", "durations is a array of the length of the number", "an array of length num_entries. For nms_prob and gt_pos its", "\"\"\" nms_pos, nms_prob, and gt_pos are lists of numpy arrays", "array of size (num_entries, 1). durations is a array of", "0][gt_cur[:, 0] < valid_time][..., np.newaxis]) else: gt_pos.append(gt_cur) valid_preds = nms_pos_o[ii]", "detections - assign to valid detection with highest prob for", "-1,-1): mprec[ii] = np.maximum(mprec[ii], mprec[ii+1]) inds = np.where(np.not_equal(mrec[1:], mrec[:-1]))[0]+1 ave_prec", "files with each entry containing that file length in seconds.", "valid detection with highest prob for jj in range(num_gt): inds", "in seconds. detection_overlap determines if a prediction is counted as", "- win_size gt_cur = gt_pos_o[ii] if gt_cur.shape[0] > 0: gt_pos.append(gt_cur[:,", "np.cumsum(false_pos_cat) recall = true_pos_cum / float(num_gt) precision = (true_pos_cum /", "highest prob for jj in range(num_gt): inds = np.where(within_overlap[:, jj])[0]", "inds.shape[0] > 0: # otherwise produce a list of values", "gt_pos_o # loop through each file true_pos = [] #", "- area under curve fpr, tpr, thresholds = roc_curve(gt, pred)", "== conf.shape[0]: # all the probability values are the same", "at the end of an audio file. returns precision: fraction", "# remove duplicate detections - assign to valid detection with", "sure it contains something num_gt = gt_pos[ii].shape[0] # for each", "0 recall[np.isnan(recall)] = 0 # pascal'12 way mprec = np.hstack((0,", "of retrieved instances that are relevant. recall: fraction of relevant", "num_preds > 0: # check to make sure it contains", "false_pos = [] # says there is a detection but", "win_size) else: nms_pos = nms_pos_o nms_prob = nms_prob_o gt_pos =", "precision): precision[np.isnan(precision)] = 0 recall[np.isnan(recall)] = 0 # pascal'12 way", "of gt_pos_o nms_pos = [] nms_prob = [] gt_pos =", "durations[ii] - win_size gt_cur = gt_pos_o[ii] if gt_cur.shape[0] > 0:", "each entry containing that file length in seconds. detection_overlap determines", "detection_overlap determines if a prediction is counted as correct or", "+ true_pos_sum))]) elif inds.shape[0] > 0: # otherwise produce a", "> prob).astype(np.int) class_acc = (pred_int == gt).mean() * 100.0 #", "= np.maximum(mprec[ii], mprec[ii+1]) inds = np.where(np.not_equal(mrec[1:], mrec[:-1]))[0]+1 ave_prec = ((mrec[inds]", "# classification error pred_int = (pred > prob).astype(np.int) class_acc =", "nms_pos = [] nms_prob = [] gt_pos = [] for", "jj in range(num_gt): inds = np.where(within_overlap[:, jj])[0] # get the", "gt_pos = remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size) else: nms_pos =", "numpy as np from sklearn.metrics import roc_curve, auc def compute_error_auc(op_str,", "nms_prob, and gt_pos are lists of numpy arrays specifying detection", "# otherwise produce a list of values true_pos_cum = np.cumsum(true_pos_cat)", "as correct or not. win_size is used to ignore predictions", "in range(num_gt): inds = np.where(within_overlap[:, jj])[0] # get the indices", "positive or false positive (i.e. 1-tp) tp = np.zeros(num_preds) distance_to_gt", "predicts the ground truth false_pos = [] # says there", "label them as true positive or false positive (i.e. 1-tp)", "to ignore predictions and ground truth at the end of", "are retrieved. \"\"\" if remove_eof: # filter out the detections", "tp[selected_pred] = 1 # set as true positives true_pos.append(tp) false_pos.append(1", "relevant. recall: fraction of relevant instances that are retrieved. \"\"\"", "- assign to valid detection with highest prob for jj", "sweep # the curve and instead will return a single", "mprec[ii] = np.maximum(mprec[ii], mprec[ii+1]) inds = np.where(np.not_equal(mrec[1:], mrec[:-1]))[0]+1 ave_prec =", "classification error pred_int = (pred > prob).astype(np.int) class_acc = (pred_int", "np.asarray([true_pos_sum / float(num_gt)]) precision = np.asarray([(true_pos_sum / (false_pos_sum + true_pos_sum))])", "precision and recall - sort confidence in descending order #", "pred_int = (pred > prob).astype(np.int) class_acc = (pred_int == gt).mean()", "and gt that are close to the end # this", "(class_acc, roc_auc) #return class_acc, roc_auc def calc_average_precision(recall, precision): precision[np.isnan(precision)] =", "check to make sure it contains something num_gt = gt_pos[ii].shape[0]", "tpr, thresholds = roc_curve(gt, pred) roc_auc = auc(fpr, tpr) print", "if num_preds > 0: # check to make sure it", "make sure it contains something num_gt = gt_pos[ii].shape[0] # for", "inds.shape[0] > 0: max_prob = np.argmax(nms_prob[ii][inds]) selected_pred = inds[max_prob] within_overlap[selected_pred,", "entry containing that file length in seconds. detection_overlap determines if", "remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size) else: nms_pos = nms_pos_o nms_prob", "# all the probability values are the same therefore we", "# get the indices of all valid predictions if inds.shape[0]", "in range(len(nms_pos)): num_preds = nms_pos[ii].shape[0] if num_preds > 0: #", "import numpy as np from sklearn.metrics import roc_curve, auc def", "we will not sweep # the curve and instead will", "true_pos_sum = true_pos_cat.sum() false_pos_sum = false_pos_cat.sum() recall = np.asarray([true_pos_sum /", "close to the end of the file - dont count", "ii in range(mprec.shape[0]-2, -1,-1): mprec[ii] = np.maximum(mprec[ii], mprec[ii+1]) inds =", "true_pos_cat = np.concatenate(true_pos)[inds].astype(float) false_pos_cat = np.concatenate(false_pos)[inds].astype(float) # i.e. 1-true_pos_cat if", "nms_pos is an array of length num_entries. For nms_prob and", "nms_pos, nms_prob, and gt_pos are lists of numpy arrays specifying", "= (pred_int == gt).mean() * 100.0 # ROC - area", "if a prediction is counted as correct or not. win_size", "of length num_entries. For nms_prob and gt_pos its an array", "is used to ignore predictions and ground truth at the", "nms_pos, nms_prob, gt_pos = remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size) else:", "else: nms_pos = nms_pos_o nms_prob = nms_prob_o gt_pos = gt_pos_o", "are lists of numpy arrays specifying detection position, detection probability", "eval nms_pos, nms_prob, gt_pos = remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size)", "nms_pos.append(nms_pos_o[ii][valid_preds]) nms_prob.append(nms_prob_o[ii][valid_preds, 0][..., np.newaxis]) return nms_pos, nms_prob, gt_pos def prec_recall_1d(nms_pos_o,", "ave_prec = ((mrec[inds] - mrec[inds-1])*mprec[inds]).sum() return ave_prec def remove_end_preds(nms_pos_o, nms_prob_o,", "valid_time = durations[ii] - win_size gt_cur = gt_pos_o[ii] if gt_cur.shape[0]", "np.argmax(nms_prob[ii][inds]) selected_pred = inds[max_prob] within_overlap[selected_pred, :] = False tp[selected_pred] =", "detection probability and GT position. Each list entry is a", "precision = np.asarray([(true_pos_sum / (false_pos_sum + true_pos_sum))]) elif inds.shape[0] >", "remove duplicate detections - assign to valid detection with highest", "to make sure it contains something num_gt = gt_pos[ii].shape[0] #", "if remove_eof: # filter out the detections in both ground", "mrec = np.hstack((0, recall, 1)) for ii in range(mprec.shape[0]-2, -1,-1):", "the ground truth false_pos = [] # says there is", "set of predictions label them as true positive or false", "range(len(nms_pos_o)): valid_time = durations[ii] - win_size gt_cur = gt_pos_o[ii] if", "nms_pos_o[ii] < valid_time nms_pos.append(nms_pos_o[ii][valid_preds]) nms_prob.append(nms_prob_o[ii][valid_preds, 0][..., np.newaxis]) return nms_pos, nms_prob,", "= ((mrec[inds] - mrec[inds-1])*mprec[inds]).sum() return ave_prec def remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o,", "max_prob = np.argmax(nms_prob[ii][inds]) selected_pred = inds[max_prob] within_overlap[selected_pred, :] = False", "= [] gt_pos = [] for ii in range(len(nms_pos_o)): valid_time", "np.newaxis]) within_overlap = (distance_to_gt <= detection_overlap) # remove duplicate detections", "if inds.shape[0] > 0: max_prob = np.argmax(nms_prob[ii][inds]) selected_pred = inds[max_prob]", "a bit messy because of the shapes of gt_pos_o nms_pos", "order # PASCAL style conf = np.concatenate(nms_prob)[:, 0] num_gt =", "something num_gt = gt_pos[ii].shape[0] # for each set of predictions", "positive (i.e. 1-tp) tp = np.zeros(num_preds) distance_to_gt = np.abs(gt_pos[ii].ravel()-nms_pos[ii].ravel()[:, np.newaxis])", "truth at the end of an audio file. returns precision:", "ground truth false_pos = [] # says there is a", "0] < valid_time][..., np.newaxis]) else: gt_pos.append(gt_cur) valid_preds = nms_pos_o[ii] <", "of the file - dont count them during eval nms_pos,", "1-tp) tp = np.zeros(num_preds) distance_to_gt = np.abs(gt_pos[ii].ravel()-nms_pos[ii].ravel()[:, np.newaxis]) within_overlap =", "gt_pos_o nms_pos = [] nms_prob = [] gt_pos = []", "position, detection probability and GT position. Each list entry is", "= np.abs(gt_pos[ii].ravel()-nms_pos[ii].ravel()[:, np.newaxis]) within_overlap = (distance_to_gt <= detection_overlap) # remove", "dont count them during eval nms_pos, nms_prob, gt_pos = remove_end_preds(nms_pos_o,", "= 0 recall[np.isnan(recall)] = 0 # pascal'12 way mprec =", "= np.asarray([(true_pos_sum / (false_pos_sum + true_pos_sum))]) elif inds.shape[0] > 0:", "this filters out predictions and gt that are close to", "array of the length of the number of files with", "count them during eval nms_pos, nms_prob, gt_pos = remove_end_preds(nms_pos_o, nms_prob_o,", "arrays specifying detection position, detection probability and GT position. Each", "used to ignore predictions and ground truth at the end", "a prediction is counted as correct or not. win_size is", "durations, win_size): # this filters out predictions and gt that", "= true_pos_cat.sum() false_pos_sum = false_pos_cat.sum() recall = np.asarray([true_pos_sum / float(num_gt)])", "# PASCAL style conf = np.concatenate(nms_prob)[:, 0] num_gt = np.concatenate(gt_pos).shape[0]", "(pred_int == gt).mean() * 100.0 # ROC - area under", "says there is a detection but isn't for ii in", "and recall - sort confidence in descending order # PASCAL", "prec_recall_1d(nms_pos_o, nms_prob_o, gt_pos_o, durations, detection_overlap, win_size, remove_eof=True): \"\"\" nms_pos, nms_prob,", "nms_prob, gt_pos = remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size) else: nms_pos", "1 # set as true positives true_pos.append(tp) false_pos.append(1 - tp)", "because of the shapes of gt_pos_o nms_pos = [] nms_prob", "entry is a different file. Each entry in nms_pos is", "a detection but isn't for ii in range(len(nms_pos)): num_preds =", "and GT position. Each list entry is a different file.", "GT position. Each list entry is a different file. Each", "true_pos.append(tp) false_pos.append(1 - tp) # calc precision and recall -", "PASCAL style conf = np.concatenate(nms_prob)[:, 0] num_gt = np.concatenate(gt_pos).shape[0] inds", "np.where(np.not_equal(mrec[1:], mrec[:-1]))[0]+1 ave_prec = ((mrec[inds] - mrec[inds-1])*mprec[inds]).sum() return ave_prec def", "for ii in range(len(nms_pos)): num_preds = nms_pos[ii].shape[0] if num_preds >", "return ave_prec def remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size): # this", "there is a detection but isn't for ii in range(len(nms_pos)):", "false_pos_cat = np.concatenate(false_pos)[inds].astype(float) # i.e. 1-true_pos_cat if (conf == conf[0]).sum()", "under curve fpr, tpr, thresholds = roc_curve(gt, pred) roc_auc =", "in range(len(nms_pos_o)): valid_time = durations[ii] - win_size gt_cur = gt_pos_o[ii]", "prob for jj in range(num_gt): inds = np.where(within_overlap[:, jj])[0] #", "= %.3f, ROC AUC = %.3f' % (class_acc, roc_auc) #return", "nms_prob_o, gt_pos_o, durations, win_size) else: nms_pos = nms_pos_o nms_prob =", "detection position, detection probability and GT position. Each list entry", "print op_str, ', class acc = %.3f, ROC AUC =", "1). durations is a array of the length of the", "return a single value true_pos_sum = true_pos_cat.sum() false_pos_sum = false_pos_cat.sum()", "np.argsort(conf)[::-1] true_pos_cat = np.concatenate(true_pos)[inds].astype(float) false_pos_cat = np.concatenate(false_pos)[inds].astype(float) # i.e. 1-true_pos_cat", "= remove_end_preds(nms_pos_o, nms_prob_o, gt_pos_o, durations, win_size) else: nms_pos = nms_pos_o", "durations, win_size) else: nms_pos = nms_pos_o nms_prob = nms_prob_o gt_pos", "file length in seconds. detection_overlap determines if a prediction is", "to valid detection with highest prob for jj in range(num_gt):", "nms_prob_o gt_pos = gt_pos_o # loop through each file true_pos", "= np.argmax(nms_prob[ii][inds]) selected_pred = inds[max_prob] within_overlap[selected_pred, :] = False tp[selected_pred]", "otherwise produce a list of values true_pos_cum = np.cumsum(true_pos_cat) false_pos_cum", "predictions if inds.shape[0] > 0: max_prob = np.argmax(nms_prob[ii][inds]) selected_pred =", "\"\"\" if remove_eof: # filter out the detections in both", "each set of predictions label them as true positive or", "will not sweep # the curve and instead will return", "range(num_gt): inds = np.where(within_overlap[:, jj])[0] # get the indices of", "gt_pos.append(gt_cur[:, 0][gt_cur[:, 0] < valid_time][..., np.newaxis]) else: gt_pos.append(gt_cur) valid_preds =", "detection but isn't for ii in range(len(nms_pos)): num_preds = nms_pos[ii].shape[0]", "0: gt_pos.append(gt_cur[:, 0][gt_cur[:, 0] < valid_time][..., np.newaxis]) else: gt_pos.append(gt_cur) valid_preds", "compute_error_auc(op_str, gt, pred, prob): # classification error pred_int = (pred", "or false positive (i.e. 1-tp) tp = np.zeros(num_preds) distance_to_gt =", "correct or not. win_size is used to ignore predictions and", "true_pos_cum = np.cumsum(true_pos_cat) false_pos_cum = np.cumsum(false_pos_cat) recall = true_pos_cum /", "not. win_size is used to ignore predictions and ground truth", "confidence in descending order # PASCAL style conf = np.concatenate(nms_prob)[:,", "a single value true_pos_sum = true_pos_cat.sum() false_pos_sum = false_pos_cat.sum() recall", "gt_cur = gt_pos_o[ii] if gt_cur.shape[0] > 0: gt_pos.append(gt_cur[:, 0][gt_cur[:, 0]", "predictions and ground truth at the end of an audio", "< valid_time][..., np.newaxis]) else: gt_pos.append(gt_cur) valid_preds = nms_pos_o[ii] < valid_time", "are close to the end # this is a bit", "np.asarray([(true_pos_sum / (false_pos_sum + true_pos_sum))]) elif inds.shape[0] > 0: #", "within_overlap = (distance_to_gt <= detection_overlap) # remove duplicate detections -", "np.concatenate(gt_pos).shape[0] inds = np.argsort(conf)[::-1] true_pos_cat = np.concatenate(true_pos)[inds].astype(float) false_pos_cat = np.concatenate(false_pos)[inds].astype(float)", "= nms_pos_o nms_prob = nms_prob_o gt_pos = gt_pos_o # loop", "- sort confidence in descending order # PASCAL style conf", "num_entries. For nms_prob and gt_pos its an array of size", "gt_pos = [] for ii in range(len(nms_pos_o)): valid_time = durations[ii]", "ROC - area under curve fpr, tpr, thresholds = roc_curve(gt,", "out predictions and gt that are close to the end", "the file - dont count them during eval nms_pos, nms_prob,", "gt_pos_o, durations, win_size) else: nms_pos = nms_pos_o nms_prob = nms_prob_o", "gt_cur.shape[0] > 0: gt_pos.append(gt_cur[:, 0][gt_cur[:, 0] < valid_time][..., np.newaxis]) else:", "[] # says there is a detection but isn't for", "false_pos_sum = false_pos_cat.sum() recall = np.asarray([true_pos_sum / float(num_gt)]) precision =", "is a detection but isn't for ii in range(len(nms_pos)): num_preds", "of predictions label them as true positive or false positive", "as np from sklearn.metrics import roc_curve, auc def compute_error_auc(op_str, gt,", "/ float(num_gt)]) precision = np.asarray([(true_pos_sum / (false_pos_sum + true_pos_sum))]) elif", "# for each set of predictions label them as true", "[] nms_prob = [] gt_pos = [] for ii in", "instances that are retrieved. \"\"\" if remove_eof: # filter out", "else: gt_pos.append(gt_cur) valid_preds = nms_pos_o[ii] < valid_time nms_pos.append(nms_pos_o[ii][valid_preds]) nms_prob.append(nms_prob_o[ii][valid_preds, 0][...,", "entry in nms_pos is an array of length num_entries. For", "and ground truth at the end of an audio file.", "counted as correct or not. win_size is used to ignore", "= false_pos_cat.sum() recall = np.asarray([true_pos_sum / float(num_gt)]) precision = np.asarray([(true_pos_sum", "from sklearn.metrics import roc_curve, auc def compute_error_auc(op_str, gt, pred, prob):", "that file length in seconds. detection_overlap determines if a prediction", "float(num_gt) precision = (true_pos_cum / (false_pos_cum + true_pos_cum)) return precision,", "Each list entry is a different file. Each entry in", "recall - sort confidence in descending order # PASCAL style", "through each file true_pos = [] # correctly predicts the" ]
[ "import record from tests.mgmt_testcase import HttpStatusCode, AzureMgmtTestCase class MgmtNetworkTest(AzureMgmtTestCase): def", "test_virtual_network_gateway_operations(self): # https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-site-to-site-resource-manager-portal vnet_name = self.get_resource_name('pyvirtnet') fe_name = self.get_resource_name('pysubnetfe') be_name", "all lbs = self.network_client.load_balancers.list_all() lbs = list(lbs) self.assertGreater(len(lbs), 0) #", "lbs = list(lbs) self.assertGreater(len(lbs), 0) # Delete async_lb_delete = self.network_client.load_balancers.delete(", "express_route_name )) self.assertEqual(len(peerings), 1) stats = self.network_client.express_route_circuits.get_peering_stats( self.group_name, express_route_name, 'AzurePublicPeering'", "False, 'load_distribution': 'Default', 'frontend_ip_configuration': { 'id': front_end_id }, 'backend_address_pool': {", "'name': 'Standard'}, 'ip_configurations':[{ 'name': 'default', 'private_ip_allocation_method': 'Dynamic', 'subnet': { 'id':", "self.group_name, vnet_name, be_name, {'address_prefix': '10.12.0.0/24'} ) be_subnet_info = async_subnet_creation.result() #", "('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/backendAddressPools/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, addr_pool_name )", "Get it lb_info = self.network_client.load_balancers.get( self.group_name, lb_name ) # List", "self.assertGreater(len(lbs), 0) # List RG lbs = self.network_client.load_balancers.list(self.group_name) lbs =", "itself vng_name = self.get_resource_name('pyvng') gw_params = { 'location': self.region, 'gateway_type':", "AzureMgmtTestCase class MgmtNetworkTest(AzureMgmtTestCase): def setUp(self): super(MgmtNetworkTest, self).setUp() self.network_client = self.create_mgmt_client(", "Building a BackEnd adress pool backend_address_pools = [{ 'name': addr_pool_name", "self.network_client.route_tables.delete( self.group_name, route_table_name ) async_route_table_delete.wait() @record def test_usages(self): usages =", "}] # Building a LoadBalancer rule load_balancing_rules = [{ 'name':", "'address_space': { 'address_prefixes': ['10.0.0.0/16'] } } ) async_vnet_creation.wait() # Create", "'value', }, ) result_create = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create, )", "Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, be_name, {'address_prefix': '10.12.0.0/24'} )", "vnet.name, '10.0.1.35' # Should be available since new VNet sor", "# Building a HealthProbe probes = [{ 'name': probe_name, 'protocol':", ") async_delete.wait() @record def test_load_balancers(self): public_ip_name = self.get_resource_name('pyipname') frontend_ip_name =", "a FrontEndIpPool frontend_ip_configurations = [{ 'name': frontend_ip_name, 'private_ip_allocation_method': 'Dynamic', 'public_ip_address':", ")) self.assertEqual(len(nics), 1) nics = list(self.network_client.network_interfaces.list_all()) self.assertGreater(len(nics), 0) async_delete =", "= result_create.result() # Gateway itself vng_name = self.get_resource_name('pyvng') gw_params =", "self.assertEqual(len(result_list), 1) result_list_all = self.network_client.public_ip_addresses.list_all() #self.assertEqual(result_list_all.status_code, HttpStatusCode.OK) result_list_all = list(result_list_all)", ") async_peering.wait() async_express_route = self.network_client.express_route_circuits.delete( self.group_name, express_route_name ) async_express_route.wait() @record", "protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp, source_address_prefix='*', source_port_range='655', ), ], ) result_create = self.network_client.network_security_groups.create_or_update( self.group_name,", "= self.get_resource_name('pyapname') probe_name = self.get_resource_name('pyprobename') lb_name = self.get_resource_name('pylbname') front_end_id =", "self.assertEqual(len(new_security_rules), 2) result_delete = self.network_client.security_rules.delete( self.group_name, security_group_name, new_security_rule_name ) result_delete.wait()", "'id': probe_id } }] # Building InboundNATRule1 inbound_nat_rules = [{", "= self.network_client.express_route_circuits.create_or_update( self.group_name, express_route_name, { \"location\": self.region, \"sku\": { \"name\":", "= self.network_client.virtual_networks.get( self.group_name, network_name, ) self.assertEqual(len(result_get.subnets), 2) result_get = self.network_client.subnets.get(", "async_route_table = self.network_client.route_tables.create_or_update( self.group_name, route_table_name, {'location': self.region} ) route_table =", "self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, frontend_ip_name ) back_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network'", "'default', 'private_ip_allocation_method': 'Dynamic', 'subnet': { 'id': gateway_subnet_info.id }, 'public_ip_address': {", "self.network_client.virtual_networks.create_or_update( self.group_name, vnet_name, { 'location': self.region, 'address_space': { 'address_prefixes': [", "Security Rules new_security_rule_name = self.get_resource_name('pynewrule') async_security_rule = self.network_client.security_rules.create_or_update( self.group_name, security_group_name,", "async_subnet_creation.result() # Create Gateway Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name,", "new_security_rule_name) new_security_rules = list(self.network_client.security_rules.list( self.group_name, security_group_name )) self.assertEqual(len(new_security_rules), 2) result_delete", "= async_publicip_creation.result() # Building a FrontEndIpPool frontend_ip_configurations = [{ 'name':", "# List all lbs = self.network_client.load_balancers.list_all() lbs = list(lbs) self.assertGreater(len(lbs),", "{'address_prefix': '10.0.0.0/24'} ) subnet_info = async_subnet_creation.result() # Create NIC async_nic_creation", "= self.network_client.network_security_groups.get( self.group_name, security_group_name, ) result_list = list(self.network_client.network_security_groups.list( self.group_name, ))", "1 ) self.assertTrue(ip_availability.available) result_list = list(self.network_client.virtual_networks.list( self.group_name, )) self.assertEqual(len(result_list), 1)", "#-------------------------------------------------------------------------- import unittest import azure.mgmt.network.models from testutils.common_recordingtestcase import record from", "async_lb_delete = self.network_client.load_balancers.delete( self.group_name, lb_name ) async_lb_delete.wait() @record def test_public_ip_addresses(self):", "= self.network_client.network_interfaces.create_or_update( self.group_name, nic_name, { 'location': self.region, 'ip_configurations': [{ 'name':", "List all lbs = self.network_client.load_balancers.list_all() lbs = list(lbs) self.assertGreater(len(lbs), 0)", "nic_info.name ) nics = list(self.network_client.network_interfaces.list( self.group_name )) self.assertEqual(len(nics), 1) nics", ") probe_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/probes/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name,", "security_rule_name = self.get_resource_name('pysecgrouprule') params_create = azure.mgmt.network.models.NetworkSecurityGroup( location=self.region, security_rules=[ azure.mgmt.network.models.SecurityRule( name=security_rule_name,", "self.group_name, network_name, subnet2_name, ) result_list = self.network_client.subnets.list( self.group_name, network_name, )", "= self.create_mgmt_client( azure.mgmt.network.NetworkManagementClient ) if not self.is_playback(): self.create_resource_group() @record def", "2, 'name': 'Standard'}, 'ip_configurations':[{ 'name': 'default', 'private_ip_allocation_method': 'Dynamic', 'subnet': {", "be_name = self.get_resource_name('pysubnetbe') gateway_name = self.get_resource_name('pysubnetga') # Create VNet async_vnet_creation", "azure.mgmt.network.models.NetworkSecurityGroup( location=self.region, security_rules=[ azure.mgmt.network.models.SecurityRule( name=security_rule_name, access=azure.mgmt.network.models.SecurityRuleAccess.allow, description='Test security rule', destination_address_prefix='*',", "= list(self.network_client.express_route_service_providers.list()) self.assertGreater(len(ersp), 0) self.assertTrue(all(hasattr(u, 'bandwidths_offered') for u in ersp))", "4, 'frontend_ip_configuration': { 'id': front_end_id } }) # Creating Load", "0) async_route = self.network_client.routes.create_or_update( self.group_name, route_table.name, route_name, { 'address_prefix': '10.1.0.0/16',", "async_publicip_creation = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, public_ip_parameters ) public_ip_info = async_publicip_creation.result()", "#self.assertEqual(result_delete.status_code, HttpStatusCode.OK) result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list)", "route_table_name = self.get_resource_name('pyroutetable') route_name = self.get_resource_name('pyroute') async_route_table = self.network_client.route_tables.create_or_update( self.group_name,", "self.network_client.network_interfaces.create_or_update( self.group_name, nic_name, { 'location': self.region, 'ip_configurations': [{ 'name': 'MyIpConfig',", "HttpStatusCode.OK) self.assertEqual(result_get.location, self.region) self.assertEqual(result_get.tags['key'], 'value') result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK)", "u in usages)) @record def test_express_route_service_providers(self): ersp = list(self.network_client.express_route_service_providers.list()) self.assertGreater(len(ersp),", "async_subnet_creation.result() # Create NIC async_nic_creation = self.network_client.network_interfaces.create_or_update( self.group_name, nic_name, {", "ersp)) @record def test_express_route_circuit(self): express_route_name = self.get_resource_name('pyexpressroute') async_express_route = self.network_client.express_route_circuits.create_or_update(", "], ) result_create = self.network_client.network_security_groups.create_or_update( self.group_name, security_group_name, params_create, ) result_create.wait()", "self.group_name )) self.assertEqual(len(routes), 1) routes = list(self.network_client.express_route_circuits.list_all()) self.assertGreater(len(routes), 0) stats", "ersp = list(self.network_client.express_route_service_providers.list()) self.assertGreater(len(ersp), 0) self.assertTrue(all(hasattr(u, 'bandwidths_offered') for u in", "self.network_client.subnets.delete( self.group_name, network_name, subnet2_name, ) result_delete.wait() @record def test_network_security_groups(self): security_group_name", "'static', 'idle_timeout_in_minutes': 4 } async_publicip_creation = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, public_ip_parameters", "route_table.name, route_name, { 'address_prefix': '10.1.0.0/16', 'next_hop_type': 'None' } ) route", "MgmtNetworkTest(AzureMgmtTestCase): def setUp(self): super(MgmtNetworkTest, self).setUp() self.network_client = self.create_mgmt_client( azure.mgmt.network.NetworkManagementClient )", "frontend_ip_name ) back_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/backendAddressPools/{}').format( self.settings.SUBSCRIPTION_ID,", "} }] } ) nic_info = async_nic_creation.result() nic_info = self.network_client.network_interfaces.get(", "self.assertEqual(result_get.location, self.region) self.assertEqual(result_get.tags['key'], 'value') result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list", "public_ip_name, ) result_delete.wait() # AzureOperationPoller #self.assertEqual(result_delete.status_code, HttpStatusCode.OK) result_list = self.network_client.public_ip_addresses.list(self.group_name)", ") #self.assertEqual(result_check.status_code, HttpStatusCode.OK) self.assertTrue(result_check) @record def test_subnets(self): network_name = self.get_resource_name('pysubnet')", "def test_subnets(self): network_name = self.get_resource_name('pysubnet') subnet1_name = self.get_resource_name('pysubnetone') subnet2_name =", "peering = self.network_client.express_route_circuit_peerings.get( self.group_name, express_route_name, 'AzurePublicPeering' ) peerings = list(self.network_client.express_route_circuit_peerings.list(", "self.network_client.subnets.create_or_update( self.group_name, vnet_name, subnet_name, {'address_prefix': '10.0.0.0/24'} ) subnet_info = async_subnet_creation.result()", "result_get = self.network_client.network_security_groups.get( self.group_name, security_group_name, ) result_list = list(self.network_client.network_security_groups.list( self.group_name,", "= self.get_resource_name('pysubnetbe') gateway_name = self.get_resource_name('pysubnetga') # Create VNet async_vnet_creation =", "'pydomain', ) #self.assertEqual(result_check.status_code, HttpStatusCode.OK) self.assertTrue(result_check) @record def test_subnets(self): network_name =", "express_route_name, 'AzurePublicPeering' ) self.assertIsNotNone(stats) auth_name = self.get_resource_name('pyauth') async_auth = self.network_client.express_route_circuit_authorizations.create_or_update(", "security_group_name, ) result_delete.wait() @record def test_routes(self): route_table_name = self.get_resource_name('pyroutetable') route_name", ")) self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.virtual_networks.list_all()) async_delete = self.network_client.virtual_networks.delete( self.group_name,", "result_get = self.network_client.subnets.get( self.group_name, network_name, subnet2_name, ) result_list = self.network_client.subnets.list(", "Delete async_lb_delete = self.network_client.load_balancers.delete( self.group_name, lb_name ) async_lb_delete.wait() @record def", "list(result_list) self.assertEqual(len(result_list), 1) result_list_all = self.network_client.public_ip_addresses.list_all() #self.assertEqual(result_list_all.status_code, HttpStatusCode.OK) result_list_all =", "network_name, params_create, ) result_create.wait() # AzureOperationPoller params_create = azure.mgmt.network.models.Subnet( name=subnet2_name,", "result_create = self.network_client.subnets.create_or_update( self.group_name, network_name, subnet2_name, params_create, ) result_create.wait() #", "'Standard', 'capacity': 2, 'name': 'Standard'}, 'ip_configurations':[{ 'name': 'default', 'private_ip_allocation_method': 'Dynamic',", "} ) async_vnet_creation.wait() # Create Front End Subnet async_subnet_creation =", "self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.virtual_networks.list_all()) async_delete = self.network_client.virtual_networks.delete( self.group_name, network_name,", ")) self.assertEqual(len(routes), 1) async_route_delete = self.network_client.routes.delete( self.group_name, route_table.name, route.name )", "subnet_info = async_subnet_creation.result() # Create NIC async_nic_creation = self.network_client.network_interfaces.create_or_update( self.group_name,", "async_peering = self.network_client.express_route_circuit_peerings.create_or_update( self.group_name, express_route_name, 'AzurePublicPeering', { \"peering_type\": \"AzurePublicPeering\", \"peer_asn\":", "list(self.network_client.express_route_circuit_authorizations.list( self.group_name, express_route_name )) self.assertEqual(len(auths), 1) async_auth = self.network_client.express_route_circuit_authorizations.delete( self.group_name,", "'10.11.0.0/24'} ) fe_subnet_info = async_subnet_creation.result() # Create Back End Subnet", "self.network_client.security_rules.create_or_update( self.group_name, security_group_name, new_security_rule_name, { 'access':azure.mgmt.network.models.SecurityRuleAccess.allow, 'description':'New Test security rule',", "self.network_client.subnets.create_or_update( self.group_name, vnet_name, be_name, {'address_prefix': '10.12.0.0/24'} ) be_subnet_info = async_subnet_creation.result()", "self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list), 0) @record def", "{ 'id': front_end_id } }) # Creating Load Balancer lb_async_creation", "AzureOperationPoller params_create = azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ) result_create = self.network_client.subnets.create_or_update(", "0) result_delete = self.network_client.public_ip_addresses.delete( self.group_name, public_ip_name, ) result_delete.wait() # AzureOperationPoller", ") nics = list(self.network_client.network_interfaces.list( self.group_name )) self.assertEqual(len(nics), 1) nics =", "= list(self.network_client.virtual_networks.list( self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.virtual_networks.list_all()) async_delete", "'id': subnet_info.id } }] } ) nic_info = async_nic_creation.result() nic_info", "security_rule = async_security_rule.result() security_rule = self.network_client.security_rules.get( self.group_name, security_group_name, security_rule.name )", "route_name) routes = list(self.network_client.routes.list( self.group_name, route_table.name )) self.assertEqual(len(routes), 1) async_route_delete", "= { 'location': self.region, 'gateway_type': 'VPN', 'vpn_type': 'RouteBased', 'enable_bgp': False,", "def test_load_balancers(self): public_ip_name = self.get_resource_name('pyipname') frontend_ip_name = self.get_resource_name('pyfipname') addr_pool_name =", "= azure.mgmt.network.models.NetworkSecurityGroup( location=self.region, security_rules=[ azure.mgmt.network.models.SecurityRule( name=security_rule_name, access=azure.mgmt.network.models.SecurityRuleAccess.allow, description='Test security rule',", "= self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create, ) result_create.wait() # AzureOperationPoller params_create", "{ 'id': subnet_info.id } }] } ) nic_info = async_nic_creation.result()", "} }) # Creating Load Balancer lb_async_creation = self.network_client.load_balancers.create_or_update( self.group_name,", "'protocol': 'tcp', 'frontend_port': 21, 'backend_port': 22, 'enable_floating_ip': False, 'idle_timeout_in_minutes': 4,", "self.get_resource_name('pyroutetable') route_name = self.get_resource_name('pyroute') async_route_table = self.network_client.route_tables.create_or_update( self.group_name, route_table_name, {'location':", ") gateway_subnet_info = async_subnet_creation.result() # Public IP Address public_ip_name =", "vnet = self.network_client.virtual_networks.get( self.group_name, vnet.name, ) ip_availability = self.network_client.virtual_networks.check_ip_address_availability( self.group_name,", "route_table.name, route.name ) self.assertEqual(route.name, route_name) routes = list(self.network_client.routes.list( self.group_name, route_table.name", "self.assertTrue(ip_availability.available) result_list = list(self.network_client.virtual_networks.list( self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all =", "= self.get_resource_name('pyexpressroute') async_express_route = self.network_client.express_route_circuits.create_or_update( self.group_name, express_route_name, { \"location\": self.region,", "result_delete.wait() # Delete NSG result_delete = self.network_client.network_security_groups.delete( self.group_name, security_group_name, )", "name=subnet2_name, address_prefix='10.0.2.0/24', ), ], ) result_create = self.network_client.virtual_networks.create_or_update( self.group_name, network_name,", "https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-site-to-site-resource-manager-portal vnet_name = self.get_resource_name('pyvirtnet') fe_name = self.get_resource_name('pysubnetfe') be_name = self.get_resource_name('pysubnetbe')", "list(lbs) self.assertGreater(len(lbs), 0) # List RG lbs = self.network_client.load_balancers.list(self.group_name) lbs", "# https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-site-to-site-resource-manager-portal vnet_name = self.get_resource_name('pyvirtnet') fe_name = self.get_resource_name('pysubnetfe') be_name =", "self.network_client.express_route_circuits.get( self.group_name, express_route_name ) routes = list(self.network_client.express_route_circuits.list( self.group_name )) self.assertEqual(len(routes),", "BackEnd adress pool backend_address_pools = [{ 'name': addr_pool_name }] #", "= self.network_client.network_security_groups.delete( self.group_name, security_group_name, ) result_delete.wait() @record def test_routes(self): route_table_name", "= async_subnet_creation.result() # Create NIC async_nic_creation = self.network_client.network_interfaces.create_or_update( self.group_name, nic_name,", "def test_network_security_groups(self): security_group_name = self.get_resource_name('pysecgroup') security_rule_name = self.get_resource_name('pysecgrouprule') params_create =", ")) self.assertEqual(len(peerings), 1) stats = self.network_client.express_route_circuits.get_peering_stats( self.group_name, express_route_name, 'AzurePublicPeering' )", "route = self.network_client.routes.get( self.group_name, route_table.name, route.name ) self.assertEqual(route.name, route_name) routes", "= self.network_client.route_tables.create_or_update( self.group_name, route_table_name, {'location': self.region} ) route_table = async_route_table.result()", "list(result_list_all) self.assertGreater(len(result_list_all), 0) result_delete = self.network_client.public_ip_addresses.delete( self.group_name, public_ip_name, ) result_delete.wait()", "root for # license information. #-------------------------------------------------------------------------- import unittest import azure.mgmt.network.models", "], ), subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), ], ) result_create", "Create Back End Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, be_name,", "0) stats = self.network_client.express_route_circuits.get_stats( self.group_name, express_route_name ) self.assertIsNotNone(stats) async_peering =", "self.network_client.express_route_circuits.create_or_update( self.group_name, express_route_name, { \"location\": self.region, \"sku\": { \"name\": \"Standard_MeteredData\",", "} async_publicip_creation = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, public_ip_parameters ) public_ip_info =", "'Default', 'frontend_ip_configuration': { 'id': front_end_id }, 'backend_address_pool': { 'id': back_end_id", "self.get_resource_name('pyipname') frontend_ip_name = self.get_resource_name('pyfipname') addr_pool_name = self.get_resource_name('pyapname') probe_name = self.get_resource_name('pyprobename')", "'10.11.0.0/16', '10.12.0.0/16' ] } } ) async_vnet_creation.wait() # Create Front", "self.network_client.express_route_circuit_peerings.get( self.group_name, express_route_name, 'AzurePublicPeering' ) peerings = list(self.network_client.express_route_circuit_peerings.list( self.group_name, express_route_name", "4, 'enable_floating_ip': False, 'load_distribution': 'Default', 'frontend_ip_configuration': { 'id': front_end_id },", ") self.assertTrue(ip_availability.available) result_list = list(self.network_client.virtual_networks.list( self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all", "'GatewaySubnet', {'address_prefix': '10.12.255.0/27'} ) gateway_subnet_info = async_subnet_creation.result() # Public IP", "'enable_floating_ip': False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': { 'id': front_end_id } }]", "subnet2_name, ) result_delete.wait() @record def test_network_security_groups(self): security_group_name = self.get_resource_name('pysecgroup') security_rule_name", "vnet_name, { 'location': self.region, 'address_space': { 'address_prefixes': ['10.0.0.0/16'] } }", "azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ) result_create = self.network_client.subnets.create_or_update( self.group_name, network_name, subnet2_name,", "route_table_name, {'location': self.region} ) route_table = async_route_table.result() route_table = self.network_client.route_tables.get(", "# Security Rules new_security_rule_name = self.get_resource_name('pynewrule') async_security_rule = self.network_client.security_rules.create_or_update( self.group_name,", "self.group_name, vnet_name, fe_name, {'address_prefix': '10.11.0.0/24'} ) fe_subnet_info = async_subnet_creation.result() #", "tests.mgmt_testcase import HttpStatusCode, AzureMgmtTestCase class MgmtNetworkTest(AzureMgmtTestCase): def setUp(self): super(MgmtNetworkTest, self).setUp()", "1) result_list_all = self.network_client.public_ip_addresses.list_all() #self.assertEqual(result_list_all.status_code, HttpStatusCode.OK) result_list_all = list(result_list_all) self.assertGreater(len(result_list_all),", "a HealthProbe probes = [{ 'name': probe_name, 'protocol': 'Http', 'port':", "self.get_resource_name('pyexpressroute') async_express_route = self.network_client.express_route_circuits.create_or_update( self.group_name, express_route_name, { \"location\": self.region, \"sku\":", "[{ 'name': 'MyIpConfig', 'subnet': { 'id': subnet_info.id } }] }", "# license information. #-------------------------------------------------------------------------- import unittest import azure.mgmt.network.models from testutils.common_recordingtestcase", "network_name, ) self.assertEqual(len(result_get.subnets), 2) result_get = self.network_client.subnets.get( self.group_name, network_name, subnet2_name,", "# Create Back End Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name,", "async_security_rule.result() security_rule = self.network_client.security_rules.get( self.group_name, security_group_name, security_rule.name ) self.assertEqual(security_rule.name, new_security_rule_name)", "# Create Front End Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name,", "\"192.168.2.0/30\", \"vlan_id\": 200, } ) peering = async_peering.result() peering =", "network_name, subnet2_name, ) result_list = self.network_client.subnets.list( self.group_name, network_name, ) subnets", "async_auth = self.network_client.express_route_circuit_authorizations.delete( self.group_name, express_route_name, auth_name ) async_auth.wait() async_peering =", "'name': 'default', 'private_ip_allocation_method': 'Dynamic', 'subnet': { 'id': gateway_subnet_info.id }, 'public_ip_address':", "usages = list(self.network_client.usages.list(self.region)) self.assertGreater(len(usages), 1) self.assertTrue(all(hasattr(u, 'name') for u in", "= self.get_resource_name('pyvnet') subnet1_name = self.get_resource_name('pyvnetsubnetone') subnet2_name = self.get_resource_name('pyvnetsubnettwo') params_create =", "express_route_name, 'AzurePublicPeering' ) async_peering.wait() async_express_route = self.network_client.express_route_circuits.delete( self.group_name, express_route_name )", "result_delete.wait() # AzureOperationPoller #self.assertEqual(result_delete.status_code, HttpStatusCode.OK) result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK)", "auth_name ) auths = list(self.network_client.express_route_circuit_authorizations.list( self.group_name, express_route_name )) self.assertEqual(len(auths), 1)", "= async_peering.result() peering = self.network_client.express_route_circuit_peerings.get( self.group_name, express_route_name, 'AzurePublicPeering' ) peerings", "} ) peering = async_peering.result() peering = self.network_client.express_route_circuit_peerings.get( self.group_name, express_route_name,", "{ 'id': front_end_id } }] # Building InboundNATRule2 inbound_nat_rules.append({ 'name':", "} ) nic_info = async_nic_creation.result() nic_info = self.network_client.network_interfaces.get( self.group_name, nic_info.name", "= async_nic_creation.result() nic_info = self.network_client.network_interfaces.get( self.group_name, nic_info.name ) nics =", "azure.mgmt.network.models.PublicIPAddress( location=self.region, public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic, tags={ 'key': 'value', }, ) result_create =", "# AzureOperationPoller result_get = self.network_client.network_security_groups.get( self.group_name, security_group_name, ) result_list =", "= self.network_client.express_route_circuit_peerings.get( self.group_name, express_route_name, 'AzurePublicPeering' ) peerings = list(self.network_client.express_route_circuit_peerings.list( self.group_name,", "async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, subnet_name, {'address_prefix': '10.0.0.0/24'} ) subnet_info", "'idle_timeout_in_minutes': 4, 'enable_floating_ip': False, 'load_distribution': 'Default', 'frontend_ip_configuration': { 'id': front_end_id", ") fe_subnet_info = async_subnet_creation.result() # Create Back End Subnet async_subnet_creation", "async_nic_creation.result() nic_info = self.network_client.network_interfaces.get( self.group_name, nic_info.name ) nics = list(self.network_client.network_interfaces.list(", "def test_express_route_circuit(self): express_route_name = self.get_resource_name('pyexpressroute') async_express_route = self.network_client.express_route_circuits.create_or_update( self.group_name, express_route_name,", "= list(lbs) self.assertGreater(len(lbs), 0) # Delete async_lb_delete = self.network_client.load_balancers.delete( self.group_name,", "'/backendAddressPools/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, addr_pool_name ) probe_id = ('/subscriptions/{}' '/resourceGroups/{}'", "= list(result_list) self.assertEqual(len(result_list), 0) @record def test_virtual_networks(self): network_name = self.get_resource_name('pyvnet')", "dns_servers=[ '10.1.1.1', '10.1.2.4', ], ), subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ),", "vnet_name = self.get_resource_name('pyvnet') subnet_name = self.get_resource_name('pysubnet') nic_name = self.get_resource_name('pynic') #", "express_route_name ) self.assertIsNotNone(stats) async_peering = self.network_client.express_route_circuit_peerings.create_or_update( self.group_name, express_route_name, 'AzurePublicPeering', {", "Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, subnet_name, {'address_prefix': '10.0.0.0/24'} )", "} } ) async_vnet_creation.wait() # Create Front End Subnet async_subnet_creation", "Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, 'GatewaySubnet', {'address_prefix': '10.12.255.0/27'} )", "[{ 'name': 'azure-sample-netrule1', 'protocol': 'tcp', 'frontend_port': 21, 'backend_port': 22, 'enable_floating_ip':", "= self.get_resource_name('pyroutetable') route_name = self.get_resource_name('pyroute') async_route_table = self.network_client.route_tables.create_or_update( self.group_name, route_table_name,", "public_ip_parameters = { 'location': self.region, 'public_ip_allocation_method': 'static', 'idle_timeout_in_minutes': 4 }", "{ 'location': self.region, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'probes': probes, 'load_balancing_rules':", "self.network_client.virtual_networks.get( self.group_name, vnet.name, ) ip_availability = self.network_client.virtual_networks.check_ip_address_availability( self.group_name, vnet.name, '10.0.1.35'", "'backend_port': 80, 'idle_timeout_in_minutes': 4, 'enable_floating_ip': False, 'load_distribution': 'Default', 'frontend_ip_configuration': {", "self.assertGreater(len(route_tables), 0) async_route = self.network_client.routes.create_or_update( self.group_name, route_table.name, route_name, { 'address_prefix':", "'enable_floating_ip': False, 'load_distribution': 'Default', 'frontend_ip_configuration': { 'id': front_end_id }, 'backend_address_pool':", "self.group_name, network_name, ) subnets = list(result_list) result_delete = self.network_client.subnets.delete( self.group_name,", "= self.get_resource_name('pysubnet') nic_name = self.get_resource_name('pynic') # Create VNet async_vnet_creation =", "self.group_name, network_name, params_create, ) result_create.wait() # AzureOperationPoller params_create = azure.mgmt.network.models.Subnet(", "# Building InboundNATRule2 inbound_nat_rules.append({ 'name': 'azure-sample-netrule2', 'protocol': 'tcp', 'frontend_port': 23,", "self.group_name, nic_info.name ) nics = list(self.network_client.network_interfaces.list( self.group_name )) self.assertEqual(len(nics), 1)", "} } ) express_route = async_express_route.result() express_route = self.network_client.express_route_circuits.get( self.group_name,", "Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under", "result_create.result() vnet = self.network_client.virtual_networks.get( self.group_name, vnet.name, ) ip_availability = self.network_client.virtual_networks.check_ip_address_availability(", "= self.network_client.subnets.delete( self.group_name, network_name, subnet2_name, ) result_delete.wait() @record def test_network_security_groups(self):", ") async_auth.wait() async_peering = self.network_client.express_route_circuit_peerings.delete( self.group_name, express_route_name, 'AzurePublicPeering' ) async_peering.wait()", "self.network_client.network_security_groups.create_or_update( self.group_name, security_group_name, params_create, ) result_create.wait() # AzureOperationPoller result_get =", ") # Create PublicIP public_ip_parameters = { 'location': self.region, 'public_ip_allocation_method':", "'enable_bgp': False, 'sku': { 'tier': 'Standard', 'capacity': 2, 'name': 'Standard'},", "frontend_ip_configurations = [{ 'name': frontend_ip_name, 'private_ip_allocation_method': 'Dynamic', 'public_ip_address': { 'id':", "auth_name = self.get_resource_name('pyauth') async_auth = self.network_client.express_route_circuit_authorizations.create_or_update( self.group_name, express_route_name, auth_name, {}", "self.group_name, express_route_name ) routes = list(self.network_client.express_route_circuits.list( self.group_name )) self.assertEqual(len(routes), 1)", "result_create = self.network_client.network_security_groups.create_or_update( self.group_name, security_group_name, params_create, ) result_create.wait() # AzureOperationPoller", "result_create.result() # Gateway itself vng_name = self.get_resource_name('pyvng') gw_params = {", "80, 'idle_timeout_in_minutes': 4, 'enable_floating_ip': False, 'load_distribution': 'Default', 'frontend_ip_configuration': { 'id':", "('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/frontendIPConfigurations/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, frontend_ip_name )", "self.group_name, route_table_name, {'location': self.region} ) route_table = async_route_table.result() route_table =", "'name': 'azure-sample-netrule1', 'protocol': 'tcp', 'frontend_port': 21, 'backend_port': 22, 'enable_floating_ip': False,", "address_prefix='10.0.1.0/24', ), azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ), ], ) result_create =", "self.network_client.express_route_circuits.delete( self.group_name, express_route_name ) async_express_route.wait() @record def test_virtual_network_gateway_operations(self): # https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-site-to-site-resource-manager-portal", "self.assertGreater(len(result_list_all), 0) result_delete = self.network_client.public_ip_addresses.delete( self.group_name, public_ip_name, ) result_delete.wait() #", "self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create, ) result_create.wait() # AzureOperationPoller params_create =", "rule', 'destination_address_prefix':'*', 'destination_port_range':'123-3500', 'direction':azure.mgmt.network.models.SecurityRuleDirection.outbound, 'priority':400, 'protocol':azure.mgmt.network.models.SecurityRuleProtocol.tcp, 'source_address_prefix':'*', 'source_port_range':'655', } )", "list(lbs) self.assertGreater(len(lbs), 0) # Delete async_lb_delete = self.network_client.load_balancers.delete( self.group_name, lb_name", "self.group_name, lb_name, probe_name ) # Create PublicIP public_ip_parameters = {", "load_balancing_rules = [{ 'name': 'azure-sample-lb-rule', 'protocol': 'tcp', 'frontend_port': 80, 'backend_port':", "test_express_route_circuit(self): express_route_name = self.get_resource_name('pyexpressroute') async_express_route = self.network_client.express_route_circuits.create_or_update( self.group_name, express_route_name, {", "location=self.region, security_rules=[ azure.mgmt.network.models.SecurityRule( name=security_rule_name, access=azure.mgmt.network.models.SecurityRuleAccess.allow, description='Test security rule', destination_address_prefix='*', destination_port_range='123-3500',", "= list(self.network_client.route_tables.list_all()) self.assertGreater(len(route_tables), 0) async_route = self.network_client.routes.create_or_update( self.group_name, route_table.name, route_name,", "probes, 'load_balancing_rules': load_balancing_rules, 'inbound_nat_rules' :inbound_nat_rules } ) lb_info = lb_async_creation.result()", "self.assertGreater(len(ersp), 0) self.assertTrue(all(hasattr(u, 'bandwidths_offered') for u in ersp)) @record def", "# AzureOperationPoller result_get = self.network_client.virtual_networks.get( self.group_name, network_name, ) self.assertEqual(len(result_get.subnets), 2)", "pool backend_address_pools = [{ 'name': addr_pool_name }] # Building a", "self.network_client.check_dns_name_availability( self.region, 'pydomain', ) #self.assertEqual(result_check.status_code, HttpStatusCode.OK) self.assertTrue(result_check) @record def test_subnets(self):", "fe_name = self.get_resource_name('pysubnetfe') be_name = self.get_resource_name('pysubnetbe') gateway_name = self.get_resource_name('pysubnetga') #", "= async_security_rule.result() security_rule = self.network_client.security_rules.get( self.group_name, security_group_name, security_rule.name ) self.assertEqual(security_rule.name,", "self.assertGreater(len(nics), 0) async_delete = self.network_client.network_interfaces.delete( self.group_name, nic_info.name ) async_delete.wait() @record", ") async_route_delete.wait() async_route_table_delete = self.network_client.route_tables.delete( self.group_name, route_table_name ) async_route_table_delete.wait() @record", ") peering = async_peering.result() peering = self.network_client.express_route_circuit_peerings.get( self.group_name, express_route_name, 'AzurePublicPeering'", "routes = list(self.network_client.express_route_circuits.list_all()) self.assertGreater(len(routes), 0) stats = self.network_client.express_route_circuits.get_stats( self.group_name, express_route_name", "= self.get_resource_name('pysubnetone') subnet2_name = self.get_resource_name('pysubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace(", "express_route = async_express_route.result() express_route = self.network_client.express_route_circuits.get( self.group_name, express_route_name ) routes", "1) async_route_delete = self.network_client.routes.delete( self.group_name, route_table.name, route.name ) async_route_delete.wait() async_route_table_delete", "= async_auth.result() auth = self.network_client.express_route_circuit_authorizations.get( self.group_name, express_route_name, auth_name ) auths", "license information. #-------------------------------------------------------------------------- import unittest import azure.mgmt.network.models from testutils.common_recordingtestcase import", "{ 'address_prefixes': ['10.0.0.0/16'] } } ) async_vnet_creation.wait() # Create Subnet", "for u in ersp)) @record def test_express_route_circuit(self): express_route_name = self.get_resource_name('pyexpressroute')", "public_ip_address.id } }], } async_create = self.network_client.virtual_network_gateways.create_or_update( self.group_name, vng_name, gw_params", "} async_create = self.network_client.virtual_network_gateways.create_or_update( self.group_name, vng_name, gw_params ) vng =", "list(self.network_client.network_security_groups.list_all()) # Security Rules new_security_rule_name = self.get_resource_name('pynewrule') async_security_rule = self.network_client.security_rules.create_or_update(", "lb_name, { 'location': self.region, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'probes': probes,", "= { 'location': self.region, 'public_ip_allocation_method': 'static', 'idle_timeout_in_minutes': 4 } async_publicip_creation", "it lb_info = self.network_client.load_balancers.get( self.group_name, lb_name ) # List all", "}, 'backend_address_pool': { 'id': back_end_id }, 'probe': { 'id': probe_id", "= self.get_resource_name('pysecgroup') security_rule_name = self.get_resource_name('pysecgrouprule') params_create = azure.mgmt.network.models.NetworkSecurityGroup( location=self.region, security_rules=[", ") if not self.is_playback(): self.create_resource_group() @record def test_network_interface_card(self): vnet_name =", ") # List all lbs = self.network_client.load_balancers.list_all() lbs = list(lbs)", "setUp(self): super(MgmtNetworkTest, self).setUp() self.network_client = self.create_mgmt_client( azure.mgmt.network.NetworkManagementClient ) if not", "probe_name = self.get_resource_name('pyprobename') lb_name = self.get_resource_name('pylbname') front_end_id = ('/subscriptions/{}' '/resourceGroups/{}'", "result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list), 0)", "def test_virtual_network_gateway_operations(self): # https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-site-to-site-resource-manager-portal vnet_name = self.get_resource_name('pyvirtnet') fe_name = self.get_resource_name('pysubnetfe')", "access=azure.mgmt.network.models.SecurityRuleAccess.allow, description='Test security rule', destination_address_prefix='*', destination_port_range='123-3500', direction=azure.mgmt.network.models.SecurityRuleDirection.inbound, priority=500, protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp, source_address_prefix='*',", ") lb_info = lb_async_creation.result() # Get it lb_info = self.network_client.load_balancers.get(", "source_port_range='655', ), ], ) result_create = self.network_client.network_security_groups.create_or_update( self.group_name, security_group_name, params_create,", "), azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ), ], ) result_create = self.network_client.virtual_networks.create_or_update(", "async_delete.wait() @record def test_dns_availability(self): result_check = self.network_client.check_dns_name_availability( self.region, 'pydomain', )", "Licensed under the MIT License. See License.txt in the project", "self.network_client.network_security_groups.get( self.group_name, security_group_name, ) result_list = list(self.network_client.network_security_groups.list( self.group_name, )) self.assertEqual(len(result_list),", "route_name = self.get_resource_name('pyroute') async_route_table = self.network_client.route_tables.create_or_update( self.group_name, route_table_name, {'location': self.region}", "a LoadBalancer rule load_balancing_rules = [{ 'name': 'azure-sample-lb-rule', 'protocol': 'tcp',", "self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.network_security_groups.list_all()) # Security Rules", "} }] # Building InboundNATRule2 inbound_nat_rules.append({ 'name': 'azure-sample-netrule2', 'protocol': 'tcp',", "address_prefix='10.0.2.0/24', ) result_create = self.network_client.subnets.create_or_update( self.group_name, network_name, subnet2_name, params_create, )", "self.network_client.load_balancers.list_all() lbs = list(lbs) self.assertGreater(len(lbs), 0) # List RG lbs", "test_network_interface_card(self): vnet_name = self.get_resource_name('pyvnet') subnet_name = self.get_resource_name('pysubnet') nic_name = self.get_resource_name('pynic')", "express_route_name, auth_name, {} ) auth = async_auth.result() auth = self.network_client.express_route_circuit_authorizations.get(", "self.assertEqual(route.name, route_name) routes = list(self.network_client.routes.list( self.group_name, route_table.name )) self.assertEqual(len(routes), 1)", "\"AzurePublicPeering\", \"peer_asn\": 100, \"primary_peer_address_prefix\": \"192.168.1.0/30\", \"secondary_peer_address_prefix\": \"192.168.2.0/30\", \"vlan_id\": 200, }", "= self.network_client.express_route_circuit_authorizations.get( self.group_name, express_route_name, auth_name ) auths = list(self.network_client.express_route_circuit_authorizations.list( self.group_name,", "{ 'address_prefix': '10.1.0.0/16', 'next_hop_type': 'None' } ) route = async_route.result()", "route_table = self.network_client.route_tables.get( self.group_name, route_table.name ) self.assertEqual(route_table.name, route_table_name) route_tables =", "1) routes = list(self.network_client.express_route_circuits.list_all()) self.assertGreater(len(routes), 0) stats = self.network_client.express_route_circuits.get_stats( self.group_name,", "import azure.mgmt.network.models from testutils.common_recordingtestcase import record from tests.mgmt_testcase import HttpStatusCode,", "HealthProbe probes = [{ 'name': probe_name, 'protocol': 'Http', 'port': 80,", "= list(self.network_client.express_route_circuits.list( self.group_name )) self.assertEqual(len(routes), 1) routes = list(self.network_client.express_route_circuits.list_all()) self.assertGreater(len(routes),", "= azure.mgmt.network.models.PublicIPAddress( location=self.region, public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic, tags={ 'key': 'value', }, ) result_create", ") async_route_table_delete.wait() @record def test_usages(self): usages = list(self.network_client.usages.list(self.region)) self.assertGreater(len(usages), 1)", "network_name, ) async_delete.wait() @record def test_dns_availability(self): result_check = self.network_client.check_dns_name_availability( self.region,", "{ 'id': back_end_id }, 'probe': { 'id': probe_id } }]", "@record def test_subnets(self): network_name = self.get_resource_name('pysubnet') subnet1_name = self.get_resource_name('pysubnetone') subnet2_name", "NIC async_nic_creation = self.network_client.network_interfaces.create_or_update( self.group_name, nic_name, { 'location': self.region, 'ip_configurations':", "'backend_address_pool': { 'id': back_end_id }, 'probe': { 'id': probe_id }", "async_route_delete.wait() async_route_table_delete = self.network_client.route_tables.delete( self.group_name, route_table_name ) async_route_table_delete.wait() @record def", "self.assertTrue(all(hasattr(u, 'bandwidths_offered') for u in ersp)) @record def test_express_route_circuit(self): express_route_name", "= list(result_list) result_delete = self.network_client.subnets.delete( self.group_name, network_name, subnet2_name, ) result_delete.wait()", "async_subnet_creation.result() # Public IP Address public_ip_name = self.get_resource_name('pyipname') params_create =", "'AzurePublicPeering' ) async_peering.wait() async_express_route = self.network_client.express_route_circuits.delete( self.group_name, express_route_name ) async_express_route.wait()", "Address public_ip_name = self.get_resource_name('pyipname') params_create = azure.mgmt.network.models.PublicIPAddress( location=self.region, public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic, tags={", "public_ip_info.id } }] # Building a BackEnd adress pool backend_address_pools", "), subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ),", "= self.get_resource_name('pysecgrouprule') params_create = azure.mgmt.network.models.NetworkSecurityGroup( location=self.region, security_rules=[ azure.mgmt.network.models.SecurityRule( name=security_rule_name, access=azure.mgmt.network.models.SecurityRuleAccess.allow,", "# Building a BackEnd adress pool backend_address_pools = [{ 'name':", "in usages)) @record def test_express_route_service_providers(self): ersp = list(self.network_client.express_route_service_providers.list()) self.assertGreater(len(ersp), 0)", "# Create VNet async_vnet_creation = self.network_client.virtual_networks.create_or_update( self.group_name, vnet_name, { 'location':", "'10.0.1.35' # Should be available since new VNet sor Subnet", ") result_create.wait() # AzureOperationPoller result_get = self.network_client.network_security_groups.get( self.group_name, security_group_name, )", "End Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, fe_name, {'address_prefix': '10.11.0.0/24'}", "[{ 'name': 'azure-sample-lb-rule', 'protocol': 'tcp', 'frontend_port': 80, 'backend_port': 80, 'idle_timeout_in_minutes':", "'address_space': { 'address_prefixes': [ '10.11.0.0/16', '10.12.0.0/16' ] } } )", "HttpStatusCode.OK) result_list_all = list(result_list_all) self.assertGreater(len(result_list_all), 0) result_delete = self.network_client.public_ip_addresses.delete( self.group_name,", "vnet = result_create.result() vnet = self.network_client.virtual_networks.get( self.group_name, vnet.name, ) ip_availability", "params_create = azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ) result_create = self.network_client.subnets.create_or_update( self.group_name,", "security_rule.name ) self.assertEqual(security_rule.name, new_security_rule_name) new_security_rules = list(self.network_client.security_rules.list( self.group_name, security_group_name ))", "self.network_client = self.create_mgmt_client( azure.mgmt.network.NetworkManagementClient ) if not self.is_playback(): self.create_resource_group() @record", "'sku': { 'tier': 'Standard', 'capacity': 2, 'name': 'Standard'}, 'ip_configurations':[{ 'name':", "}, 'probe': { 'id': probe_id } }] # Building InboundNATRule1", "# Gateway itself vng_name = self.get_resource_name('pyvng') gw_params = { 'location':", "async_create = self.network_client.virtual_network_gateways.create_or_update( self.group_name, vng_name, gw_params ) vng = async_create.result()", "'protocol': 'tcp', 'frontend_port': 80, 'backend_port': 80, 'idle_timeout_in_minutes': 4, 'enable_floating_ip': False,", "= self.network_client.security_rules.delete( self.group_name, security_group_name, new_security_rule_name ) result_delete.wait() # Delete NSG", "= self.get_resource_name('pyvng') gw_params = { 'location': self.region, 'gateway_type': 'VPN', 'vpn_type':", "priority=500, protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp, source_address_prefix='*', source_port_range='655', ), ], ) result_create = self.network_client.network_security_groups.create_or_update(", "location=self.region, public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic, tags={ 'key': 'value', }, ) result_create = self.network_client.public_ip_addresses.create_or_update(", "'10.0.0.0/24'} ) subnet_info = async_subnet_creation.result() # Create NIC async_nic_creation =", "subnets = list(result_list) result_delete = self.network_client.subnets.delete( self.group_name, network_name, subnet2_name, )", "'name': 'azure-sample-netrule2', 'protocol': 'tcp', 'frontend_port': 23, 'backend_port': 22, 'enable_floating_ip': False,", "'RouteBased', 'enable_bgp': False, 'sku': { 'tier': 'Standard', 'capacity': 2, 'name':", "Rules new_security_rule_name = self.get_resource_name('pynewrule') async_security_rule = self.network_client.security_rules.create_or_update( self.group_name, security_group_name, new_security_rule_name,", "nic_name = self.get_resource_name('pynic') # Create VNet async_vnet_creation = self.network_client.virtual_networks.create_or_update( self.group_name,", "{ 'tier': 'Standard', 'capacity': 2, 'name': 'Standard'}, 'ip_configurations':[{ 'name': 'default',", "self.region, 'address_space': { 'address_prefixes': [ '10.11.0.0/16', '10.12.0.0/16' ] } }", "# Public IP Address public_ip_name = self.get_resource_name('pyipname') params_create = azure.mgmt.network.models.PublicIPAddress(", "auth_name, {} ) auth = async_auth.result() auth = self.network_client.express_route_circuit_authorizations.get( self.group_name,", "self.group_name, express_route_name ) async_express_route.wait() @record def test_virtual_network_gateway_operations(self): # https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-site-to-site-resource-manager-portal vnet_name", "azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[ '10.0.0.0/16', ], ), dhcp_options=azure.mgmt.network.models.DhcpOptions( dns_servers=[ '10.1.1.1',", "inbound_nat_rules = [{ 'name': 'azure-sample-netrule1', 'protocol': 'tcp', 'frontend_port': 21, 'backend_port':", "self.region, 'public_ip_allocation_method': 'static', 'idle_timeout_in_minutes': 4 } async_publicip_creation = self.network_client.public_ip_addresses.create_or_update( self.group_name,", "self.group_name, security_group_name, security_rule.name ) self.assertEqual(security_rule.name, new_security_rule_name) new_security_rules = list(self.network_client.security_rules.list( self.group_name,", "params_create = azure.mgmt.network.models.PublicIPAddress( location=self.region, public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic, tags={ 'key': 'value', }, )", "= self.network_client.subnets.create_or_update( self.group_name, network_name, subnet2_name, params_create, ) result_create.wait() # AzureOperationPoller", "{'address_prefix': '10.11.0.0/24'} ) fe_subnet_info = async_subnet_creation.result() # Create Back End", "self.group_name, public_ip_name, params_create, ) result_create.wait() # AzureOperationPoller #self.assertEqual(result_create.status_code, HttpStatusCode.OK) result_get", "'frontend_port': 80, 'backend_port': 80, 'idle_timeout_in_minutes': 4, 'enable_floating_ip': False, 'load_distribution': 'Default',", "network_name, subnet2_name, params_create, ) result_create.wait() # AzureOperationPoller result_get = self.network_client.virtual_networks.get(", "self.get_resource_name('pyfipname') addr_pool_name = self.get_resource_name('pyapname') probe_name = self.get_resource_name('pyprobename') lb_name = self.get_resource_name('pylbname')", "self.group_name, express_route_name, { \"location\": self.region, \"sku\": { \"name\": \"Standard_MeteredData\", \"tier\":", "async_vnet_creation = self.network_client.virtual_networks.create_or_update( self.group_name, vnet_name, { 'location': self.region, 'address_space': {", "async_delete.wait() @record def test_load_balancers(self): public_ip_name = self.get_resource_name('pyipname') frontend_ip_name = self.get_resource_name('pyfipname')", ") result_list = self.network_client.subnets.list( self.group_name, network_name, ) subnets = list(result_list)", "route_name, { 'address_prefix': '10.1.0.0/16', 'next_hop_type': 'None' } ) route =", "0) self.assertTrue(all(hasattr(u, 'bandwidths_offered') for u in ersp)) @record def test_express_route_circuit(self):", "self.group_name, security_group_name, params_create, ) result_create.wait() # AzureOperationPoller result_get = self.network_client.network_security_groups.get(", "new_security_rules = list(self.network_client.security_rules.list( self.group_name, security_group_name )) self.assertEqual(len(new_security_rules), 2) result_delete =", "self.network_client.routes.delete( self.group_name, route_table.name, route.name ) async_route_delete.wait() async_route_table_delete = self.network_client.route_tables.delete( self.group_name,", "}], } async_create = self.network_client.virtual_network_gateways.create_or_update( self.group_name, vng_name, gw_params ) vng", "test_network_security_groups(self): security_group_name = self.get_resource_name('pysecgroup') security_rule_name = self.get_resource_name('pysecgrouprule') params_create = azure.mgmt.network.models.NetworkSecurityGroup(", "Create NIC async_nic_creation = self.network_client.network_interfaces.create_or_update( self.group_name, nic_name, { 'location': self.region,", "= self.network_client.express_route_circuits.delete( self.group_name, express_route_name ) async_express_route.wait() @record def test_virtual_network_gateway_operations(self): #", "addr_pool_name ) probe_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/probes/{}').format( self.settings.SUBSCRIPTION_ID,", "gateway_name = self.get_resource_name('pysubnetga') # Create VNet async_vnet_creation = self.network_client.virtual_networks.create_or_update( self.group_name,", "# coding: utf-8 #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All", "async_route_table_delete.wait() @record def test_usages(self): usages = list(self.network_client.usages.list(self.region)) self.assertGreater(len(usages), 1) self.assertTrue(all(hasattr(u,", "= self.network_client.check_dns_name_availability( self.region, 'pydomain', ) #self.assertEqual(result_check.status_code, HttpStatusCode.OK) self.assertTrue(result_check) @record def", ") nic_info = async_nic_creation.result() nic_info = self.network_client.network_interfaces.get( self.group_name, nic_info.name )", "nics = list(self.network_client.network_interfaces.list_all()) self.assertGreater(len(nics), 0) async_delete = self.network_client.network_interfaces.delete( self.group_name, nic_info.name", "'public_ip_allocation_method': 'static', 'idle_timeout_in_minutes': 4 } async_publicip_creation = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name,", "= list(self.network_client.routes.list( self.group_name, route_table.name )) self.assertEqual(len(routes), 1) async_route_delete = self.network_client.routes.delete(", "= [{ 'name': 'azure-sample-netrule1', 'protocol': 'tcp', 'frontend_port': 21, 'backend_port': 22,", "result_create.wait() # AzureOperationPoller result_get = self.network_client.network_security_groups.get( self.group_name, security_group_name, ) result_list", "= [{ 'name': probe_name, 'protocol': 'Http', 'port': 80, 'interval_in_seconds': 15,", "address_prefix='10.0.1.0/24', ), ], ) result_create = self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create,", "'healthprobe.aspx' }] # Building a LoadBalancer rule load_balancing_rules = [{", "= list(self.network_client.express_route_circuit_peerings.list( self.group_name, express_route_name )) self.assertEqual(len(peerings), 1) stats = self.network_client.express_route_circuits.get_peering_stats(", "= list(self.network_client.express_route_circuit_authorizations.list( self.group_name, express_route_name )) self.assertEqual(len(auths), 1) async_auth = self.network_client.express_route_circuit_authorizations.delete(", "False, 'sku': { 'tier': 'Standard', 'capacity': 2, 'name': 'Standard'}, 'ip_configurations':[{", "result_list = self.network_client.subnets.list( self.group_name, network_name, ) subnets = list(result_list) result_delete", "gateway_subnet_info.id }, 'public_ip_address': { 'id': public_ip_address.id } }], } async_create", "AzureOperationPoller #self.assertEqual(result_create.status_code, HttpStatusCode.OK) result_get = self.network_client.public_ip_addresses.get( self.group_name, public_ip_name, ) #self.assertEqual(result_get.status_code,", "route_tables = list(self.network_client.route_tables.list_all()) self.assertGreater(len(route_tables), 0) async_route = self.network_client.routes.create_or_update( self.group_name, route_table.name,", "route_tables = list(self.network_client.route_tables.list( self.group_name )) self.assertEqual(len(route_tables), 1) route_tables = list(self.network_client.route_tables.list_all())", "params_create = azure.mgmt.network.models.NetworkSecurityGroup( location=self.region, security_rules=[ azure.mgmt.network.models.SecurityRule( name=security_rule_name, access=azure.mgmt.network.models.SecurityRuleAccess.allow, description='Test security", "list(result_list) self.assertEqual(len(result_list), 0) @record def test_virtual_networks(self): network_name = self.get_resource_name('pyvnet') subnet1_name", "self.assertEqual(len(routes), 1) routes = list(self.network_client.express_route_circuits.list_all()) self.assertGreater(len(routes), 0) stats = self.network_client.express_route_circuits.get_stats(", "backend_address_pools, 'probes': probes, 'load_balancing_rules': load_balancing_rules, 'inbound_nat_rules' :inbound_nat_rules } ) lb_info", "load_balancing_rules, 'inbound_nat_rules' :inbound_nat_rules } ) lb_info = lb_async_creation.result() # Get", "route.name ) async_route_delete.wait() async_route_table_delete = self.network_client.route_tables.delete( self.group_name, route_table_name ) async_route_table_delete.wait()", "self.region, \"sku\": { \"name\": \"Standard_MeteredData\", \"tier\": \"Standard\", \"family\": \"MeteredData\" },", "async_vnet_creation.wait() # Create Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, subnet_name,", "public_ip_name = self.get_resource_name('pyipname') params_create = azure.mgmt.network.models.PublicIPAddress( location=self.region, public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic, tags={ 'key':", "self.get_resource_name('pyvirtnet') fe_name = self.get_resource_name('pysubnetfe') be_name = self.get_resource_name('pysubnetbe') gateway_name = self.get_resource_name('pysubnetga')", "nic_name, { 'location': self.region, 'ip_configurations': [{ 'name': 'MyIpConfig', 'subnet': {", "= self.network_client.security_rules.get( self.group_name, security_group_name, security_rule.name ) self.assertEqual(security_rule.name, new_security_rule_name) new_security_rules =", "4, 'request_path': 'healthprobe.aspx' }] # Building a LoadBalancer rule load_balancing_rules", "azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ), ], ) result_create = self.network_client.virtual_networks.create_or_update( self.group_name,", "express_route_name, { \"location\": self.region, \"sku\": { \"name\": \"Standard_MeteredData\", \"tier\": \"Standard\",", "# Create PublicIP public_ip_parameters = { 'location': self.region, 'public_ip_allocation_method': 'static',", "self.network_client.virtual_networks.check_ip_address_availability( self.group_name, vnet.name, '10.0.1.35' # Should be available since new", "2) result_get = self.network_client.subnets.get( self.group_name, network_name, subnet2_name, ) result_list =", "'address_prefix': '10.1.0.0/16', 'next_hop_type': 'None' } ) route = async_route.result() route", "async_peering.result() peering = self.network_client.express_route_circuit_peerings.get( self.group_name, express_route_name, 'AzurePublicPeering' ) peerings =", "), dhcp_options=azure.mgmt.network.models.DhcpOptions( dns_servers=[ '10.1.1.1', '10.1.2.4', ], ), subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name,", ") result_create = self.network_client.subnets.create_or_update( self.group_name, network_name, subnet2_name, params_create, ) result_create.wait()", "0) # Delete async_lb_delete = self.network_client.load_balancers.delete( self.group_name, lb_name ) async_lb_delete.wait()", "express_route_name, 'AzurePublicPeering', { \"peering_type\": \"AzurePublicPeering\", \"peer_asn\": 100, \"primary_peer_address_prefix\": \"192.168.1.0/30\", \"secondary_peer_address_prefix\":", "\"peering_location\": \"Chicago\", \"bandwidth_in_mbps\": 100 } } ) express_route = async_express_route.result()", "= self.network_client.virtual_network_gateways.create_or_update( self.group_name, vng_name, gw_params ) vng = async_create.result() self.assertEquals(vng.name,", "self.group_name, security_group_name, ) result_list = list(self.network_client.network_security_groups.list( self.group_name, )) self.assertEqual(len(result_list), 1)", "in ersp)) @record def test_express_route_circuit(self): express_route_name = self.get_resource_name('pyexpressroute') async_express_route =", "}, 'public_ip_address': { 'id': public_ip_address.id } }], } async_create =", "{ 'address_prefixes': [ '10.11.0.0/16', '10.12.0.0/16' ] } } ) async_vnet_creation.wait()", "addr_pool_name = self.get_resource_name('pyapname') probe_name = self.get_resource_name('pyprobename') lb_name = self.get_resource_name('pylbname') front_end_id", "subnet1_name = self.get_resource_name('pysubnetone') subnet2_name = self.get_resource_name('pysubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region,", "= self.get_resource_name('pyvnetsubnetone') subnet2_name = self.get_resource_name('pyvnetsubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace(", ") public_ip_address = result_create.result() # Gateway itself vng_name = self.get_resource_name('pyvng')", "80, 'backend_port': 80, 'idle_timeout_in_minutes': 4, 'enable_floating_ip': False, 'load_distribution': 'Default', 'frontend_ip_configuration':", "'id': public_ip_info.id } }] # Building a BackEnd adress pool", "result_delete.wait() @record def test_routes(self): route_table_name = self.get_resource_name('pyroutetable') route_name = self.get_resource_name('pyroute')", "'location': self.region, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'probes': probes, 'load_balancing_rules': load_balancing_rules,", "'value') result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list),", "= self.network_client.load_balancers.create_or_update( self.group_name, lb_name, { 'location': self.region, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools':", "= self.network_client.routes.create_or_update( self.group_name, route_table.name, route_name, { 'address_prefix': '10.1.0.0/16', 'next_hop_type': 'None'", "public_ip_name, public_ip_parameters ) public_ip_info = async_publicip_creation.result() # Building a FrontEndIpPool", "All rights reserved. # Licensed under the MIT License. See", "\"peering_type\": \"AzurePublicPeering\", \"peer_asn\": 100, \"primary_peer_address_prefix\": \"192.168.1.0/30\", \"secondary_peer_address_prefix\": \"192.168.2.0/30\", \"vlan_id\": 200,", "the project root for # license information. #-------------------------------------------------------------------------- import unittest", "result_check = self.network_client.check_dns_name_availability( self.region, 'pydomain', ) #self.assertEqual(result_check.status_code, HttpStatusCode.OK) self.assertTrue(result_check) @record", "self.get_resource_name('pyipname') params_create = azure.mgmt.network.models.PublicIPAddress( location=self.region, public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic, tags={ 'key': 'value', },", "vnet_name, { 'location': self.region, 'address_space': { 'address_prefixes': [ '10.11.0.0/16', '10.12.0.0/16'", ") routes = list(self.network_client.express_route_circuits.list( self.group_name )) self.assertEqual(len(routes), 1) routes =", "'priority':400, 'protocol':azure.mgmt.network.models.SecurityRuleProtocol.tcp, 'source_address_prefix':'*', 'source_port_range':'655', } ) security_rule = async_security_rule.result() security_rule", "self.get_resource_name('pysubnet') nic_name = self.get_resource_name('pynic') # Create VNet async_vnet_creation = self.network_client.virtual_networks.create_or_update(", "auth = async_auth.result() auth = self.network_client.express_route_circuit_authorizations.get( self.group_name, express_route_name, auth_name )", "self.network_client.load_balancers.list(self.group_name) lbs = list(lbs) self.assertGreater(len(lbs), 0) # Delete async_lb_delete =", "self.assertEqual(len(route_tables), 1) route_tables = list(self.network_client.route_tables.list_all()) self.assertGreater(len(route_tables), 0) async_route = self.network_client.routes.create_or_update(", "result_list_all = self.network_client.public_ip_addresses.list_all() #self.assertEqual(result_list_all.status_code, HttpStatusCode.OK) result_list_all = list(result_list_all) self.assertGreater(len(result_list_all), 0)", "'azure-sample-lb-rule', 'protocol': 'tcp', 'frontend_port': 80, 'backend_port': 80, 'idle_timeout_in_minutes': 4, 'enable_floating_ip':", "'protocol':azure.mgmt.network.models.SecurityRuleProtocol.tcp, 'source_address_prefix':'*', 'source_port_range':'655', } ) security_rule = async_security_rule.result() security_rule =", "'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': { 'id': front_end_id } }] # Building", "'azure-sample-netrule2', 'protocol': 'tcp', 'frontend_port': 23, 'backend_port': 22, 'enable_floating_ip': False, 'idle_timeout_in_minutes':", "= self.network_client.public_ip_addresses.delete( self.group_name, public_ip_name, ) result_delete.wait() # AzureOperationPoller #self.assertEqual(result_delete.status_code, HttpStatusCode.OK)", ")) self.assertEqual(len(routes), 1) routes = list(self.network_client.express_route_circuits.list_all()) self.assertGreater(len(routes), 0) stats =", "self.get_resource_name('pysubnet') subnet1_name = self.get_resource_name('pysubnetone') subnet2_name = self.get_resource_name('pysubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork(", "express_route_name ) routes = list(self.network_client.express_route_circuits.list( self.group_name )) self.assertEqual(len(routes), 1) routes", "u in ersp)) @record def test_express_route_circuit(self): express_route_name = self.get_resource_name('pyexpressroute') async_express_route", "self.network_client.route_tables.get( self.group_name, route_table.name ) self.assertEqual(route_table.name, route_table_name) route_tables = list(self.network_client.route_tables.list( self.group_name", "= self.get_resource_name('pysubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[ '10.0.0.0/16', ],", "1) nics = list(self.network_client.network_interfaces.list_all()) self.assertGreater(len(nics), 0) async_delete = self.network_client.network_interfaces.delete( self.group_name,", "self.group_name, route_table.name ) self.assertEqual(route_table.name, route_table_name) route_tables = list(self.network_client.route_tables.list( self.group_name ))", "subnet_name = self.get_resource_name('pysubnet') nic_name = self.get_resource_name('pynic') # Create VNet async_vnet_creation", "azure.mgmt.network.models from testutils.common_recordingtestcase import record from tests.mgmt_testcase import HttpStatusCode, AzureMgmtTestCase", "\"192.168.1.0/30\", \"secondary_peer_address_prefix\": \"192.168.2.0/30\", \"vlan_id\": 200, } ) peering = async_peering.result()", "], ), subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24',", "\"vlan_id\": 200, } ) peering = async_peering.result() peering = self.network_client.express_route_circuit_peerings.get(", "= self.network_client.subnets.create_or_update( self.group_name, vnet_name, 'GatewaySubnet', {'address_prefix': '10.12.255.0/27'} ) gateway_subnet_info =", ")) self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.network_security_groups.list_all()) # Security Rules new_security_rule_name", ") #self.assertEqual(result_get.status_code, HttpStatusCode.OK) self.assertEqual(result_get.location, self.region) self.assertEqual(result_get.tags['key'], 'value') result_list = self.network_client.public_ip_addresses.list(self.group_name)", "'gateway_type': 'VPN', 'vpn_type': 'RouteBased', 'enable_bgp': False, 'sku': { 'tier': 'Standard',", "'access':azure.mgmt.network.models.SecurityRuleAccess.allow, 'description':'New Test security rule', 'destination_address_prefix':'*', 'destination_port_range':'123-3500', 'direction':azure.mgmt.network.models.SecurityRuleDirection.outbound, 'priority':400, 'protocol':azure.mgmt.network.models.SecurityRuleProtocol.tcp,", ")) self.assertEqual(len(route_tables), 1) route_tables = list(self.network_client.route_tables.list_all()) self.assertGreater(len(route_tables), 0) async_route =", "'MyIpConfig', 'subnet': { 'id': subnet_info.id } }] } ) nic_info", "# AzureOperationPoller #self.assertEqual(result_delete.status_code, HttpStatusCode.OK) result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list", "{ 'id': gateway_subnet_info.id }, 'public_ip_address': { 'id': public_ip_address.id } }],", "\"tier\": \"Standard\", \"family\": \"MeteredData\" }, \"service_provider_properties\": { \"service_provider_name\": \"Comcast\", \"peering_location\":", "'address_prefixes': ['10.0.0.0/16'] } } ) async_vnet_creation.wait() # Create Subnet async_subnet_creation", "self.network_client.subnets.get( self.group_name, network_name, subnet2_name, ) result_list = self.network_client.subnets.list( self.group_name, network_name,", "\"Standard\", \"family\": \"MeteredData\" }, \"service_provider_properties\": { \"service_provider_name\": \"Comcast\", \"peering_location\": \"Chicago\",", "list(self.network_client.routes.list( self.group_name, route_table.name )) self.assertEqual(len(routes), 1) async_route_delete = self.network_client.routes.delete( self.group_name,", "# Create Gateway Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, 'GatewaySubnet',", "backend_address_pools = [{ 'name': addr_pool_name }] # Building a HealthProbe", "\"sku\": { \"name\": \"Standard_MeteredData\", \"tier\": \"Standard\", \"family\": \"MeteredData\" }, \"service_provider_properties\":", "'/frontendIPConfigurations/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, frontend_ip_name ) back_end_id = ('/subscriptions/{}' '/resourceGroups/{}'", ")) self.assertEqual(len(auths), 1) async_auth = self.network_client.express_route_circuit_authorizations.delete( self.group_name, express_route_name, auth_name )", "22, 'enable_floating_ip': False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': { 'id': front_end_id }", "routes = list(self.network_client.routes.list( self.group_name, route_table.name )) self.assertEqual(len(routes), 1) async_route_delete =", "'interval_in_seconds': 15, 'number_of_probes': 4, 'request_path': 'healthprobe.aspx' }] # Building a", ") async_delete.wait() @record def test_dns_availability(self): result_check = self.network_client.check_dns_name_availability( self.region, 'pydomain',", "def test_dns_availability(self): result_check = self.network_client.check_dns_name_availability( self.region, 'pydomain', ) #self.assertEqual(result_check.status_code, HttpStatusCode.OK)", "'10.12.0.0/16' ] } } ) async_vnet_creation.wait() # Create Front End", "self.network_client.routes.create_or_update( self.group_name, route_table.name, route_name, { 'address_prefix': '10.1.0.0/16', 'next_hop_type': 'None' }", "security_rule = self.network_client.security_rules.get( self.group_name, security_group_name, security_rule.name ) self.assertEqual(security_rule.name, new_security_rule_name) new_security_rules", "= self.network_client.subnets.get( self.group_name, network_name, subnet2_name, ) result_list = self.network_client.subnets.list( self.group_name,", "= list(self.network_client.usages.list(self.region)) self.assertGreater(len(usages), 1) self.assertTrue(all(hasattr(u, 'name') for u in usages))", "test_routes(self): route_table_name = self.get_resource_name('pyroutetable') route_name = self.get_resource_name('pyroute') async_route_table = self.network_client.route_tables.create_or_update(", "{ 'location': self.region, 'ip_configurations': [{ 'name': 'MyIpConfig', 'subnet': { 'id':", "name=subnet1_name, address_prefix='10.0.1.0/24', ), azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ), ], ) result_create", "front_end_id } }] # Building InboundNATRule2 inbound_nat_rules.append({ 'name': 'azure-sample-netrule2', 'protocol':", "self.network_client.express_route_circuit_peerings.create_or_update( self.group_name, express_route_name, 'AzurePublicPeering', { \"peering_type\": \"AzurePublicPeering\", \"peer_asn\": 100, \"primary_peer_address_prefix\":", "0) # List RG lbs = self.network_client.load_balancers.list(self.group_name) lbs = list(lbs)", "= self.get_resource_name('pyipname') frontend_ip_name = self.get_resource_name('pyfipname') addr_pool_name = self.get_resource_name('pyapname') probe_name =", "self.group_name, public_ip_name, ) result_delete.wait() # AzureOperationPoller #self.assertEqual(result_delete.status_code, HttpStatusCode.OK) result_list =", "LoadBalancer rule load_balancing_rules = [{ 'name': 'azure-sample-lb-rule', 'protocol': 'tcp', 'frontend_port':", "Gateway Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, 'GatewaySubnet', {'address_prefix': '10.12.255.0/27'}", "Building a HealthProbe probes = [{ 'name': probe_name, 'protocol': 'Http',", "= self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, public_ip_parameters ) public_ip_info = async_publicip_creation.result() #", "peering = async_peering.result() peering = self.network_client.express_route_circuit_peerings.get( self.group_name, express_route_name, 'AzurePublicPeering' )", "in the project root for # license information. #-------------------------------------------------------------------------- import", "coding: utf-8 #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights", "from testutils.common_recordingtestcase import record from tests.mgmt_testcase import HttpStatusCode, AzureMgmtTestCase class", "vnet_name, subnet_name, {'address_prefix': '10.0.0.0/24'} ) subnet_info = async_subnet_creation.result() # Create", "= self.network_client.network_security_groups.create_or_update( self.group_name, security_group_name, params_create, ) result_create.wait() # AzureOperationPoller result_get", "Microsoft Corporation. All rights reserved. # Licensed under the MIT", ") route = async_route.result() route = self.network_client.routes.get( self.group_name, route_table.name, route.name", "self.group_name, express_route_name, auth_name ) auths = list(self.network_client.express_route_circuit_authorizations.list( self.group_name, express_route_name ))", "new_security_rule_name = self.get_resource_name('pynewrule') async_security_rule = self.network_client.security_rules.create_or_update( self.group_name, security_group_name, new_security_rule_name, {", "100 } } ) express_route = async_express_route.result() express_route = self.network_client.express_route_circuits.get(", "self.group_name, network_name, params_create, ) vnet = result_create.result() vnet = self.network_client.virtual_networks.get(", "params_create, ) result_create.wait() # AzureOperationPoller params_create = azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24',", "Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, fe_name, {'address_prefix': '10.11.0.0/24'} )", "result_delete = self.network_client.public_ip_addresses.delete( self.group_name, public_ip_name, ) result_delete.wait() # AzureOperationPoller #self.assertEqual(result_delete.status_code,", "route = async_route.result() route = self.network_client.routes.get( self.group_name, route_table.name, route.name )", "list(self.network_client.express_route_circuits.list_all()) self.assertGreater(len(routes), 0) stats = self.network_client.express_route_circuits.get_stats( self.group_name, express_route_name ) self.assertIsNotNone(stats)", "result_create.wait() # AzureOperationPoller params_create = azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ) result_create", "= list(self.network_client.network_interfaces.list( self.group_name )) self.assertEqual(len(nics), 1) nics = list(self.network_client.network_interfaces.list_all()) self.assertGreater(len(nics),", "params_create, ) result_create.wait() # AzureOperationPoller result_get = self.network_client.virtual_networks.get( self.group_name, network_name,", "self.get_resource_name('pysecgrouprule') params_create = azure.mgmt.network.models.NetworkSecurityGroup( location=self.region, security_rules=[ azure.mgmt.network.models.SecurityRule( name=security_rule_name, access=azure.mgmt.network.models.SecurityRuleAccess.allow, description='Test", "\"MeteredData\" }, \"service_provider_properties\": { \"service_provider_name\": \"Comcast\", \"peering_location\": \"Chicago\", \"bandwidth_in_mbps\": 100", "= [{ 'name': frontend_ip_name, 'private_ip_allocation_method': 'Dynamic', 'public_ip_address': { 'id': public_ip_info.id", "description='Test security rule', destination_address_prefix='*', destination_port_range='123-3500', direction=azure.mgmt.network.models.SecurityRuleDirection.inbound, priority=500, protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp, source_address_prefix='*', source_port_range='655',", "result_get = self.network_client.public_ip_addresses.get( self.group_name, public_ip_name, ) #self.assertEqual(result_get.status_code, HttpStatusCode.OK) self.assertEqual(result_get.location, self.region)", "], ) result_create = self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create, ) vnet", "'public_ip_address': { 'id': public_ip_address.id } }], } async_create = self.network_client.virtual_network_gateways.create_or_update(", "async_publicip_creation.result() # Building a FrontEndIpPool frontend_ip_configurations = [{ 'name': frontend_ip_name,", "200, } ) peering = async_peering.result() peering = self.network_client.express_route_circuit_peerings.get( self.group_name,", ") vnet = result_create.result() vnet = self.network_client.virtual_networks.get( self.group_name, vnet.name, )", "self.group_name, vnet_name, { 'location': self.region, 'address_space': { 'address_prefixes': ['10.0.0.0/16'] }", "'name': addr_pool_name }] # Building a HealthProbe probes = [{", "list(self.network_client.express_route_circuits.list( self.group_name )) self.assertEqual(len(routes), 1) routes = list(self.network_client.express_route_circuits.list_all()) self.assertGreater(len(routes), 0)", "params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[ '10.0.0.0/16', ], ), dhcp_options=azure.mgmt.network.models.DhcpOptions(", "adress pool backend_address_pools = [{ 'name': addr_pool_name }] # Building", "express_route_name, auth_name ) async_auth.wait() async_peering = self.network_client.express_route_circuit_peerings.delete( self.group_name, express_route_name, 'AzurePublicPeering'", "be available since new VNet sor Subnet 1 ) self.assertTrue(ip_availability.available)", "stats = self.network_client.express_route_circuits.get_stats( self.group_name, express_route_name ) self.assertIsNotNone(stats) async_peering = self.network_client.express_route_circuit_peerings.create_or_update(", "probe_name ) # Create PublicIP public_ip_parameters = { 'location': self.region,", "self.group_name, lb_name, frontend_ip_name ) back_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}'", "[ '10.11.0.0/16', '10.12.0.0/16' ] } } ) async_vnet_creation.wait() # Create", "azure.mgmt.network.NetworkManagementClient ) if not self.is_playback(): self.create_resource_group() @record def test_network_interface_card(self): vnet_name", "if not self.is_playback(): self.create_resource_group() @record def test_network_interface_card(self): vnet_name = self.get_resource_name('pyvnet')", "InboundNATRule1 inbound_nat_rules = [{ 'name': 'azure-sample-netrule1', 'protocol': 'tcp', 'frontend_port': 21,", "{ \"location\": self.region, \"sku\": { \"name\": \"Standard_MeteredData\", \"tier\": \"Standard\", \"family\":", "} } ) async_vnet_creation.wait() # Create Subnet async_subnet_creation = self.network_client.subnets.create_or_update(", "], ) result_create = self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create, ) result_create.wait()", "0) async_delete = self.network_client.network_interfaces.delete( self.group_name, nic_info.name ) async_delete.wait() @record def", "'name': frontend_ip_name, 'private_ip_allocation_method': 'Dynamic', 'public_ip_address': { 'id': public_ip_info.id } }]", "'location': self.region, 'public_ip_allocation_method': 'static', 'idle_timeout_in_minutes': 4 } async_publicip_creation = self.network_client.public_ip_addresses.create_or_update(", "[{ 'name': probe_name, 'protocol': 'Http', 'port': 80, 'interval_in_seconds': 15, 'number_of_probes':", "See License.txt in the project root for # license information.", "async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, be_name, {'address_prefix': '10.12.0.0/24'} ) be_subnet_info", "], ), dhcp_options=azure.mgmt.network.models.DhcpOptions( dns_servers=[ '10.1.1.1', '10.1.2.4', ], ), subnets=[ azure.mgmt.network.models.Subnet(", "async_peering.wait() async_express_route = self.network_client.express_route_circuits.delete( self.group_name, express_route_name ) async_express_route.wait() @record def", "destination_address_prefix='*', destination_port_range='123-3500', direction=azure.mgmt.network.models.SecurityRuleDirection.inbound, priority=500, protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp, source_address_prefix='*', source_port_range='655', ), ], )", "False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': { 'id': front_end_id } }) #", "import unittest import azure.mgmt.network.models from testutils.common_recordingtestcase import record from tests.mgmt_testcase", "lb_name, frontend_ip_name ) back_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/backendAddressPools/{}').format(", "#self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list), 0) @record def test_virtual_networks(self):", "self.group_name, lb_name, { 'location': self.region, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'probes':", "@record def test_usages(self): usages = list(self.network_client.usages.list(self.region)) self.assertGreater(len(usages), 1) self.assertTrue(all(hasattr(u, 'name')", "= self.network_client.subnets.create_or_update( self.group_name, vnet_name, be_name, {'address_prefix': '10.12.0.0/24'} ) be_subnet_info =", "self.region) self.assertEqual(result_get.tags['key'], 'value') result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list =", "result_delete.wait() @record def test_network_security_groups(self): security_group_name = self.get_resource_name('pysecgroup') security_rule_name = self.get_resource_name('pysecgrouprule')", "Back End Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, be_name, {'address_prefix':", "self.get_resource_name('pynic') # Create VNet async_vnet_creation = self.network_client.virtual_networks.create_or_update( self.group_name, vnet_name, {", "self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create, ) result_create.wait() # AzureOperationPoller #self.assertEqual(result_create.status_code, HttpStatusCode.OK)", "result_create = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create, ) public_ip_address = result_create.result()", "azure.mgmt.network.models.SecurityRule( name=security_rule_name, access=azure.mgmt.network.models.SecurityRuleAccess.allow, description='Test security rule', destination_address_prefix='*', destination_port_range='123-3500', direction=azure.mgmt.network.models.SecurityRuleDirection.inbound, priority=500,", "} ) route = async_route.result() route = self.network_client.routes.get( self.group_name, route_table.name,", "Balancer lb_async_creation = self.network_client.load_balancers.create_or_update( self.group_name, lb_name, { 'location': self.region, 'frontend_ip_configurations':", "'location': self.region, 'gateway_type': 'VPN', 'vpn_type': 'RouteBased', 'enable_bgp': False, 'sku': {", "auths = list(self.network_client.express_route_circuit_authorizations.list( self.group_name, express_route_name )) self.assertEqual(len(auths), 1) async_auth =", "4, 'frontend_ip_configuration': { 'id': front_end_id } }] # Building InboundNATRule2", "License. See License.txt in the project root for # license", "lb_name, probe_name ) # Create PublicIP public_ip_parameters = { 'location':", ") self.assertEqual(security_rule.name, new_security_rule_name) new_security_rules = list(self.network_client.security_rules.list( self.group_name, security_group_name )) self.assertEqual(len(new_security_rules),", "}] # Building a BackEnd adress pool backend_address_pools = [{", "result_list = list(result_list) self.assertEqual(len(result_list), 0) @record def test_virtual_networks(self): network_name =", "async_express_route.wait() @record def test_virtual_network_gateway_operations(self): # https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-site-to-site-resource-manager-portal vnet_name = self.get_resource_name('pyvirtnet') fe_name", "nic_info = async_nic_creation.result() nic_info = self.network_client.network_interfaces.get( self.group_name, nic_info.name ) nics", "Gateway itself vng_name = self.get_resource_name('pyvng') gw_params = { 'location': self.region,", "'VPN', 'vpn_type': 'RouteBased', 'enable_bgp': False, 'sku': { 'tier': 'Standard', 'capacity':", "'AzurePublicPeering' ) self.assertIsNotNone(stats) auth_name = self.get_resource_name('pyauth') async_auth = self.network_client.express_route_circuit_authorizations.create_or_update( self.group_name,", "'/loadBalancers/{}' '/backendAddressPools/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, addr_pool_name ) probe_id = ('/subscriptions/{}'", "lbs = self.network_client.load_balancers.list(self.group_name) lbs = list(lbs) self.assertGreater(len(lbs), 0) # Delete", "lb_info = lb_async_creation.result() # Get it lb_info = self.network_client.load_balancers.get( self.group_name,", "async_express_route = self.network_client.express_route_circuits.delete( self.group_name, express_route_name ) async_express_route.wait() @record def test_virtual_network_gateway_operations(self):", "self.group_name, vng_name, gw_params ) vng = async_create.result() self.assertEquals(vng.name, vng_name) #------------------------------------------------------------------------------", "dhcp_options=azure.mgmt.network.models.DhcpOptions( dns_servers=[ '10.1.1.1', '10.1.2.4', ], ), subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24',", "= self.get_resource_name('pysubnetfe') be_name = self.get_resource_name('pysubnetbe') gateway_name = self.get_resource_name('pysubnetga') # Create", "= self.network_client.express_route_circuits.get_stats( self.group_name, express_route_name ) self.assertIsNotNone(stats) async_peering = self.network_client.express_route_circuit_peerings.create_or_update( self.group_name,", "0) @record def test_virtual_networks(self): network_name = self.get_resource_name('pyvnet') subnet1_name = self.get_resource_name('pyvnetsubnetone')", "InboundNATRule2 inbound_nat_rules.append({ 'name': 'azure-sample-netrule2', 'protocol': 'tcp', 'frontend_port': 23, 'backend_port': 22,", "public_ip_name, params_create, ) public_ip_address = result_create.result() # Gateway itself vng_name", "= list(self.network_client.network_security_groups.list_all()) # Security Rules new_security_rule_name = self.get_resource_name('pynewrule') async_security_rule =", "sor Subnet 1 ) self.assertTrue(ip_availability.available) result_list = list(self.network_client.virtual_networks.list( self.group_name, ))", ")) self.assertEqual(len(new_security_rules), 2) result_delete = self.network_client.security_rules.delete( self.group_name, security_group_name, new_security_rule_name )", "= async_route.result() route = self.network_client.routes.get( self.group_name, route_table.name, route.name ) self.assertEqual(route.name,", "subnet1_name = self.get_resource_name('pyvnetsubnetone') subnet2_name = self.get_resource_name('pyvnetsubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region,", "= self.network_client.network_interfaces.get( self.group_name, nic_info.name ) nics = list(self.network_client.network_interfaces.list( self.group_name ))", "@record def test_network_security_groups(self): security_group_name = self.get_resource_name('pysecgroup') security_rule_name = self.get_resource_name('pysecgrouprule') params_create", "self.region, 'pydomain', ) #self.assertEqual(result_check.status_code, HttpStatusCode.OK) self.assertTrue(result_check) @record def test_subnets(self): network_name", "self.group_name, vnet.name, '10.0.1.35' # Should be available since new VNet", "#self.assertEqual(result_check.status_code, HttpStatusCode.OK) self.assertTrue(result_check) @record def test_subnets(self): network_name = self.get_resource_name('pysubnet') subnet1_name", "AzureOperationPoller #self.assertEqual(result_delete.status_code, HttpStatusCode.OK) result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list =", "self.get_resource_name('pysubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[ '10.0.0.0/16', ], ),", "= lb_async_creation.result() # Get it lb_info = self.network_client.load_balancers.get( self.group_name, lb_name", "1) result_list_all = list(self.network_client.network_security_groups.list_all()) # Security Rules new_security_rule_name = self.get_resource_name('pynewrule')", "Building a LoadBalancer rule load_balancing_rules = [{ 'name': 'azure-sample-lb-rule', 'protocol':", "'name': 'azure-sample-lb-rule', 'protocol': 'tcp', 'frontend_port': 80, 'backend_port': 80, 'idle_timeout_in_minutes': 4,", ") be_subnet_info = async_subnet_creation.result() # Create Gateway Subnet async_subnet_creation =", ") result_create = self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create, ) vnet =", "self.group_name, vnet_name, 'GatewaySubnet', {'address_prefix': '10.12.255.0/27'} ) gateway_subnet_info = async_subnet_creation.result() #", "self.network_client.load_balancers.create_or_update( self.group_name, lb_name, { 'location': self.region, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools,", "lb_name = self.get_resource_name('pylbname') front_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/frontendIPConfigurations/{}').format(", "self.group_name )) self.assertEqual(len(nics), 1) nics = list(self.network_client.network_interfaces.list_all()) self.assertGreater(len(nics), 0) async_delete", "= ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/backendAddressPools/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, addr_pool_name", "self.network_client.subnets.create_or_update( self.group_name, vnet_name, 'GatewaySubnet', {'address_prefix': '10.12.255.0/27'} ) gateway_subnet_info = async_subnet_creation.result()", "self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, probe_name ) # Create PublicIP public_ip_parameters =", ") result_create.wait() # AzureOperationPoller result_get = self.network_client.virtual_networks.get( self.group_name, network_name, )", "self.network_client.virtual_networks.delete( self.group_name, network_name, ) async_delete.wait() @record def test_dns_availability(self): result_check =", "'location': self.region, 'address_space': { 'address_prefixes': [ '10.11.0.0/16', '10.12.0.0/16' ] }", "} }], } async_create = self.network_client.virtual_network_gateways.create_or_update( self.group_name, vng_name, gw_params )", "list(self.network_client.route_tables.list_all()) self.assertGreater(len(route_tables), 0) async_route = self.network_client.routes.create_or_update( self.group_name, route_table.name, route_name, {", "result_delete = self.network_client.subnets.delete( self.group_name, network_name, subnet2_name, ) result_delete.wait() @record def", "async_peering = self.network_client.express_route_circuit_peerings.delete( self.group_name, express_route_name, 'AzurePublicPeering' ) async_peering.wait() async_express_route =", "}, ) result_create = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create, ) public_ip_address", "self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.network_security_groups.list_all()) # Security Rules new_security_rule_name =", "Building InboundNATRule2 inbound_nat_rules.append({ 'name': 'azure-sample-netrule2', 'protocol': 'tcp', 'frontend_port': 23, 'backend_port':", "self.group_name, security_group_name, ) result_delete.wait() @record def test_routes(self): route_table_name = self.get_resource_name('pyroutetable')", "def setUp(self): super(MgmtNetworkTest, self).setUp() self.network_client = self.create_mgmt_client( azure.mgmt.network.NetworkManagementClient ) if", "since new VNet sor Subnet 1 ) self.assertTrue(ip_availability.available) result_list =", "self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, public_ip_parameters ) public_ip_info = async_publicip_creation.result() # Building", ") vng = async_create.result() self.assertEquals(vng.name, vng_name) #------------------------------------------------------------------------------ if __name__ ==", "'ip_configurations':[{ 'name': 'default', 'private_ip_allocation_method': 'Dynamic', 'subnet': { 'id': gateway_subnet_info.id },", "'capacity': 2, 'name': 'Standard'}, 'ip_configurations':[{ 'name': 'default', 'private_ip_allocation_method': 'Dynamic', 'subnet':", "utf-8 #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved.", "list(self.network_client.network_security_groups.list( self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.network_security_groups.list_all()) # Security", "'Http', 'port': 80, 'interval_in_seconds': 15, 'number_of_probes': 4, 'request_path': 'healthprobe.aspx' }]", "def test_express_route_service_providers(self): ersp = list(self.network_client.express_route_service_providers.list()) self.assertGreater(len(ersp), 0) self.assertTrue(all(hasattr(u, 'bandwidths_offered') for", "def test_routes(self): route_table_name = self.get_resource_name('pyroutetable') route_name = self.get_resource_name('pyroute') async_route_table =", "= self.get_resource_name('pyroute') async_route_table = self.network_client.route_tables.create_or_update( self.group_name, route_table_name, {'location': self.region} )", "{ 'id': probe_id } }] # Building InboundNATRule1 inbound_nat_rules =", "= self.network_client.express_route_circuit_authorizations.delete( self.group_name, express_route_name, auth_name ) async_auth.wait() async_peering = self.network_client.express_route_circuit_peerings.delete(", ") result_create.wait() # AzureOperationPoller #self.assertEqual(result_create.status_code, HttpStatusCode.OK) result_get = self.network_client.public_ip_addresses.get( self.group_name,", "'frontend_ip_configuration': { 'id': front_end_id }, 'backend_address_pool': { 'id': back_end_id },", ") result_create = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create, ) public_ip_address =", "information. #-------------------------------------------------------------------------- import unittest import azure.mgmt.network.models from testutils.common_recordingtestcase import record", "address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[ '10.0.0.0/16', ], ), dhcp_options=azure.mgmt.network.models.DhcpOptions( dns_servers=[ '10.1.1.1', '10.1.2.4', ],", "'request_path': 'healthprobe.aspx' }] # Building a LoadBalancer rule load_balancing_rules =", "'id': front_end_id } }] # Building InboundNATRule2 inbound_nat_rules.append({ 'name': 'azure-sample-netrule2',", "result_create.wait() # AzureOperationPoller result_get = self.network_client.virtual_networks.get( self.group_name, network_name, ) self.assertEqual(len(result_get.subnets),", "AzureOperationPoller result_get = self.network_client.network_security_groups.get( self.group_name, security_group_name, ) result_list = list(self.network_client.network_security_groups.list(", "Load Balancer lb_async_creation = self.network_client.load_balancers.create_or_update( self.group_name, lb_name, { 'location': self.region,", ") security_rule = async_security_rule.result() security_rule = self.network_client.security_rules.get( self.group_name, security_group_name, security_rule.name", "\"family\": \"MeteredData\" }, \"service_provider_properties\": { \"service_provider_name\": \"Comcast\", \"peering_location\": \"Chicago\", \"bandwidth_in_mbps\":", "self.assertIsNotNone(stats) auth_name = self.get_resource_name('pyauth') async_auth = self.network_client.express_route_circuit_authorizations.create_or_update( self.group_name, express_route_name, auth_name,", "self.assertEqual(len(result_get.subnets), 2) result_get = self.network_client.subnets.get( self.group_name, network_name, subnet2_name, ) result_list", "\"peer_asn\": 100, \"primary_peer_address_prefix\": \"192.168.1.0/30\", \"secondary_peer_address_prefix\": \"192.168.2.0/30\", \"vlan_id\": 200, } )", "23, 'backend_port': 22, 'enable_floating_ip': False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': { 'id':", "= self.get_resource_name('pyvnet') subnet_name = self.get_resource_name('pysubnet') nic_name = self.get_resource_name('pynic') # Create", "'protocol': 'tcp', 'frontend_port': 23, 'backend_port': 22, 'enable_floating_ip': False, 'idle_timeout_in_minutes': 4,", "'frontend_ip_configuration': { 'id': front_end_id } }] # Building InboundNATRule2 inbound_nat_rules.append({", "self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list), 1) result_list_all =", "async_route.result() route = self.network_client.routes.get( self.group_name, route_table.name, route.name ) self.assertEqual(route.name, route_name)", "} }] # Building a BackEnd adress pool backend_address_pools =", "self.group_name, lb_name ) # List all lbs = self.network_client.load_balancers.list_all() lbs", "fe_subnet_info = async_subnet_creation.result() # Create Back End Subnet async_subnet_creation =", "record from tests.mgmt_testcase import HttpStatusCode, AzureMgmtTestCase class MgmtNetworkTest(AzureMgmtTestCase): def setUp(self):", "= self.network_client.route_tables.get( self.group_name, route_table.name ) self.assertEqual(route_table.name, route_table_name) route_tables = list(self.network_client.route_tables.list(", "vng_name, gw_params ) vng = async_create.result() self.assertEquals(vng.name, vng_name) #------------------------------------------------------------------------------ if", "'private_ip_allocation_method': 'Dynamic', 'subnet': { 'id': gateway_subnet_info.id }, 'public_ip_address': { 'id':", "'location': self.region, 'address_space': { 'address_prefixes': ['10.0.0.0/16'] } } ) async_vnet_creation.wait()", ") async_vnet_creation.wait() # Create Front End Subnet async_subnet_creation = self.network_client.subnets.create_or_update(", "= self.network_client.subnets.list( self.group_name, network_name, ) subnets = list(result_list) result_delete =", "'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': { 'id': front_end_id } }) # Creating", "\"name\": \"Standard_MeteredData\", \"tier\": \"Standard\", \"family\": \"MeteredData\" }, \"service_provider_properties\": { \"service_provider_name\":", "21, 'backend_port': 22, 'enable_floating_ip': False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': { 'id':", "= self.network_client.express_route_circuits.get( self.group_name, express_route_name ) routes = list(self.network_client.express_route_circuits.list( self.group_name ))", "{'address_prefix': '10.12.255.0/27'} ) gateway_subnet_info = async_subnet_creation.result() # Public IP Address", "'name': 'MyIpConfig', 'subnet': { 'id': subnet_info.id } }] } )", "Test security rule', 'destination_address_prefix':'*', 'destination_port_range':'123-3500', 'direction':azure.mgmt.network.models.SecurityRuleDirection.outbound, 'priority':400, 'protocol':azure.mgmt.network.models.SecurityRuleProtocol.tcp, 'source_address_prefix':'*', 'source_port_range':'655',", "{ 'location': self.region, 'public_ip_allocation_method': 'static', 'idle_timeout_in_minutes': 4 } async_publicip_creation =", "subnet2_name = self.get_resource_name('pyvnetsubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[ '10.0.0.0/16',", "@record def test_network_interface_card(self): vnet_name = self.get_resource_name('pyvnet') subnet_name = self.get_resource_name('pysubnet') nic_name", "'tcp', 'frontend_port': 21, 'backend_port': 22, 'enable_floating_ip': False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration':", "'10.1.2.4', ], ), subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), ], )", "# Create NIC async_nic_creation = self.network_client.network_interfaces.create_or_update( self.group_name, nic_name, { 'location':", ") subnets = list(result_list) result_delete = self.network_client.subnets.delete( self.group_name, network_name, subnet2_name,", "self.group_name, public_ip_name, ) #self.assertEqual(result_get.status_code, HttpStatusCode.OK) self.assertEqual(result_get.location, self.region) self.assertEqual(result_get.tags['key'], 'value') result_list", "self.assertTrue(all(hasattr(u, 'name') for u in usages)) @record def test_express_route_service_providers(self): ersp", "vnet.name, ) ip_availability = self.network_client.virtual_networks.check_ip_address_availability( self.group_name, vnet.name, '10.0.1.35' # Should", "azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ), ], )", "lb_info = self.network_client.load_balancers.get( self.group_name, lb_name ) # List all lbs", "'destination_port_range':'123-3500', 'direction':azure.mgmt.network.models.SecurityRuleDirection.outbound, 'priority':400, 'protocol':azure.mgmt.network.models.SecurityRuleProtocol.tcp, 'source_address_prefix':'*', 'source_port_range':'655', } ) security_rule =", "15, 'number_of_probes': 4, 'request_path': 'healthprobe.aspx' }] # Building a LoadBalancer", "= self.network_client.route_tables.delete( self.group_name, route_table_name ) async_route_table_delete.wait() @record def test_usages(self): usages", "self.group_name, express_route_name, 'AzurePublicPeering' ) peerings = list(self.network_client.express_route_circuit_peerings.list( self.group_name, express_route_name ))", "self.group_name, nic_info.name ) async_delete.wait() @record def test_load_balancers(self): public_ip_name = self.get_resource_name('pyipname')", "name=subnet1_name, address_prefix='10.0.1.0/24', ), ], ) result_create = self.network_client.virtual_networks.create_or_update( self.group_name, network_name,", "nic_info = self.network_client.network_interfaces.get( self.group_name, nic_info.name ) nics = list(self.network_client.network_interfaces.list( self.group_name", "back_end_id }, 'probe': { 'id': probe_id } }] # Building", "}] # Building InboundNATRule1 inbound_nat_rules = [{ 'name': 'azure-sample-netrule1', 'protocol':", "self.is_playback(): self.create_resource_group() @record def test_network_interface_card(self): vnet_name = self.get_resource_name('pyvnet') subnet_name =", "self.network_client.load_balancers.delete( self.group_name, lb_name ) async_lb_delete.wait() @record def test_public_ip_addresses(self): public_ip_name =", "direction=azure.mgmt.network.models.SecurityRuleDirection.inbound, priority=500, protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp, source_address_prefix='*', source_port_range='655', ), ], ) result_create =", "location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[ '10.0.0.0/16', ], ), dhcp_options=azure.mgmt.network.models.DhcpOptions( dns_servers=[ '10.1.1.1', '10.1.2.4',", "public_ip_name = self.get_resource_name('pyipname') frontend_ip_name = self.get_resource_name('pyfipname') addr_pool_name = self.get_resource_name('pyapname') probe_name", "test_virtual_networks(self): network_name = self.get_resource_name('pyvnet') subnet1_name = self.get_resource_name('pyvnetsubnetone') subnet2_name = self.get_resource_name('pyvnetsubnettwo')", "self.assertGreater(len(usages), 1) self.assertTrue(all(hasattr(u, 'name') for u in usages)) @record def", "self.group_name )) self.assertEqual(len(route_tables), 1) route_tables = list(self.network_client.route_tables.list_all()) self.assertGreater(len(route_tables), 0) async_route", "self.group_name, lb_name, addr_pool_name ) probe_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}'", "params_create, ) result_create.wait() # AzureOperationPoller #self.assertEqual(result_create.status_code, HttpStatusCode.OK) result_get = self.network_client.public_ip_addresses.get(", "route_table.name, route.name ) async_route_delete.wait() async_route_table_delete = self.network_client.route_tables.delete( self.group_name, route_table_name )", "self.network_client.subnets.create_or_update( self.group_name, vnet_name, fe_name, {'address_prefix': '10.11.0.0/24'} ) fe_subnet_info = async_subnet_creation.result()", "self.region, 'gateway_type': 'VPN', 'vpn_type': 'RouteBased', 'enable_bgp': False, 'sku': { 'tier':", "{ 'location': self.region, 'address_space': { 'address_prefixes': [ '10.11.0.0/16', '10.12.0.0/16' ]", "2) result_delete = self.network_client.security_rules.delete( self.group_name, security_group_name, new_security_rule_name ) result_delete.wait() #", "result_list_all = list(result_list_all) self.assertGreater(len(result_list_all), 0) result_delete = self.network_client.public_ip_addresses.delete( self.group_name, public_ip_name,", "async_route = self.network_client.routes.create_or_update( self.group_name, route_table.name, route_name, { 'address_prefix': '10.1.0.0/16', 'next_hop_type':", "#self.assertEqual(result_create.status_code, HttpStatusCode.OK) result_get = self.network_client.public_ip_addresses.get( self.group_name, public_ip_name, ) #self.assertEqual(result_get.status_code, HttpStatusCode.OK)", "'private_ip_allocation_method': 'Dynamic', 'public_ip_address': { 'id': public_ip_info.id } }] # Building", "}] # Building InboundNATRule2 inbound_nat_rules.append({ 'name': 'azure-sample-netrule2', 'protocol': 'tcp', 'frontend_port':", "} }] # Building InboundNATRule1 inbound_nat_rules = [{ 'name': 'azure-sample-netrule1',", "'id': front_end_id } }) # Creating Load Balancer lb_async_creation =", "= self.get_resource_name('pylbname') front_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/frontendIPConfigurations/{}').format( self.settings.SUBSCRIPTION_ID,", "list(self.network_client.express_route_service_providers.list()) self.assertGreater(len(ersp), 0) self.assertTrue(all(hasattr(u, 'bandwidths_offered') for u in ersp)) @record", ") result_delete.wait() # Delete NSG result_delete = self.network_client.network_security_groups.delete( self.group_name, security_group_name,", "available since new VNet sor Subnet 1 ) self.assertTrue(ip_availability.available) result_list", "'10.1.1.1', '10.1.2.4', ], ), subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), ],", "self.network_client.express_route_circuit_authorizations.get( self.group_name, express_route_name, auth_name ) auths = list(self.network_client.express_route_circuit_authorizations.list( self.group_name, express_route_name", "'/providers/Microsoft.Network' '/loadBalancers/{}' '/frontendIPConfigurations/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, frontend_ip_name ) back_end_id =", "@record def test_dns_availability(self): result_check = self.network_client.check_dns_name_availability( self.region, 'pydomain', ) #self.assertEqual(result_check.status_code,", "async_express_route.result() express_route = self.network_client.express_route_circuits.get( self.group_name, express_route_name ) routes = list(self.network_client.express_route_circuits.list(", "Create Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, subnet_name, {'address_prefix': '10.0.0.0/24'}", "1) async_auth = self.network_client.express_route_circuit_authorizations.delete( self.group_name, express_route_name, auth_name ) async_auth.wait() async_peering", "#self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list), 1) result_list_all = self.network_client.public_ip_addresses.list_all()", "'/probes/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, probe_name ) # Create PublicIP public_ip_parameters", "self.assertEqual(route_table.name, route_table_name) route_tables = list(self.network_client.route_tables.list( self.group_name )) self.assertEqual(len(route_tables), 1) route_tables", "\"Comcast\", \"peering_location\": \"Chicago\", \"bandwidth_in_mbps\": 100 } } ) express_route =", "peerings = list(self.network_client.express_route_circuit_peerings.list( self.group_name, express_route_name )) self.assertEqual(len(peerings), 1) stats =", "), ], ) result_create = self.network_client.network_security_groups.create_or_update( self.group_name, security_group_name, params_create, )", "= self.network_client.load_balancers.get( self.group_name, lb_name ) # List all lbs =", "# Delete async_lb_delete = self.network_client.load_balancers.delete( self.group_name, lb_name ) async_lb_delete.wait() @record", ") ip_availability = self.network_client.virtual_networks.check_ip_address_availability( self.group_name, vnet.name, '10.0.1.35' # Should be", "rule', destination_address_prefix='*', destination_port_range='123-3500', direction=azure.mgmt.network.models.SecurityRuleDirection.inbound, priority=500, protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp, source_address_prefix='*', source_port_range='655', ), ],", "= self.network_client.virtual_networks.get( self.group_name, vnet.name, ) ip_availability = self.network_client.virtual_networks.check_ip_address_availability( self.group_name, vnet.name,", "testutils.common_recordingtestcase import record from tests.mgmt_testcase import HttpStatusCode, AzureMgmtTestCase class MgmtNetworkTest(AzureMgmtTestCase):", "params_create, ) result_create.wait() # AzureOperationPoller result_get = self.network_client.network_security_groups.get( self.group_name, security_group_name,", "self.group_name, nic_name, { 'location': self.region, 'ip_configurations': [{ 'name': 'MyIpConfig', 'subnet':", "'load_balancing_rules': load_balancing_rules, 'inbound_nat_rules' :inbound_nat_rules } ) lb_info = lb_async_creation.result() #", "Creating Load Balancer lb_async_creation = self.network_client.load_balancers.create_or_update( self.group_name, lb_name, { 'location':", "'protocol': 'Http', 'port': 80, 'interval_in_seconds': 15, 'number_of_probes': 4, 'request_path': 'healthprobe.aspx'", "async_subnet_creation.result() # Create Back End Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name,", "}) # Creating Load Balancer lb_async_creation = self.network_client.load_balancers.create_or_update( self.group_name, lb_name,", "\"bandwidth_in_mbps\": 100 } } ) express_route = async_express_route.result() express_route =", "import HttpStatusCode, AzureMgmtTestCase class MgmtNetworkTest(AzureMgmtTestCase): def setUp(self): super(MgmtNetworkTest, self).setUp() self.network_client", "not self.is_playback(): self.create_resource_group() @record def test_network_interface_card(self): vnet_name = self.get_resource_name('pyvnet') subnet_name", "route_table.name ) self.assertEqual(route_table.name, route_table_name) route_tables = list(self.network_client.route_tables.list( self.group_name )) self.assertEqual(len(route_tables),", "list(self.network_client.security_rules.list( self.group_name, security_group_name )) self.assertEqual(len(new_security_rules), 2) result_delete = self.network_client.security_rules.delete( self.group_name,", "= self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list), 1) result_list_all", "self.region, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'probes': probes, 'load_balancing_rules': load_balancing_rules, 'inbound_nat_rules'", "'inbound_nat_rules' :inbound_nat_rules } ) lb_info = lb_async_creation.result() # Get it", "'/providers/Microsoft.Network' '/loadBalancers/{}' '/probes/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, probe_name ) # Create", "self.region} ) route_table = async_route_table.result() route_table = self.network_client.route_tables.get( self.group_name, route_table.name", "'/loadBalancers/{}' '/probes/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, probe_name ) # Create PublicIP", "usages)) @record def test_express_route_service_providers(self): ersp = list(self.network_client.express_route_service_providers.list()) self.assertGreater(len(ersp), 0) self.assertTrue(all(hasattr(u,", "class MgmtNetworkTest(AzureMgmtTestCase): def setUp(self): super(MgmtNetworkTest, self).setUp() self.network_client = self.create_mgmt_client( azure.mgmt.network.NetworkManagementClient", "new VNet sor Subnet 1 ) self.assertTrue(ip_availability.available) result_list = list(self.network_client.virtual_networks.list(", "'10.12.0.0/24'} ) be_subnet_info = async_subnet_creation.result() # Create Gateway Subnet async_subnet_creation", "self).setUp() self.network_client = self.create_mgmt_client( azure.mgmt.network.NetworkManagementClient ) if not self.is_playback(): self.create_resource_group()", "self.assertEqual(len(result_list), 0) @record def test_virtual_networks(self): network_name = self.get_resource_name('pyvnet') subnet1_name =", "Building a FrontEndIpPool frontend_ip_configurations = [{ 'name': frontend_ip_name, 'private_ip_allocation_method': 'Dynamic',", "route_table_name ) async_route_table_delete.wait() @record def test_usages(self): usages = list(self.network_client.usages.list(self.region)) self.assertGreater(len(usages),", "'bandwidths_offered') for u in ersp)) @record def test_express_route_circuit(self): express_route_name =", "frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'probes': probes, 'load_balancing_rules': load_balancing_rules, 'inbound_nat_rules' :inbound_nat_rules }", "#------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #", "self.group_name, vnet_name, subnet_name, {'address_prefix': '10.0.0.0/24'} ) subnet_info = async_subnet_creation.result() #", "'tcp', 'frontend_port': 23, 'backend_port': 22, 'enable_floating_ip': False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration':", "= self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create, ) public_ip_address = result_create.result() #", "MIT License. See License.txt in the project root for #", "subnet_name, {'address_prefix': '10.0.0.0/24'} ) subnet_info = async_subnet_creation.result() # Create NIC", "result_create = self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create, ) vnet = result_create.result()", "frontend_ip_name = self.get_resource_name('pyfipname') addr_pool_name = self.get_resource_name('pyapname') probe_name = self.get_resource_name('pyprobename') lb_name", "self.network_client.virtual_networks.get( self.group_name, network_name, ) self.assertEqual(len(result_get.subnets), 2) result_get = self.network_client.subnets.get( self.group_name,", "VNet sor Subnet 1 ) self.assertTrue(ip_availability.available) result_list = list(self.network_client.virtual_networks.list( self.group_name,", "= async_subnet_creation.result() # Public IP Address public_ip_name = self.get_resource_name('pyipname') params_create", "lb_name, addr_pool_name ) probe_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/probes/{}').format(", "List RG lbs = self.network_client.load_balancers.list(self.group_name) lbs = list(lbs) self.assertGreater(len(lbs), 0)", "front_end_id } }) # Creating Load Balancer lb_async_creation = self.network_client.load_balancers.create_or_update(", "'subnet': { 'id': gateway_subnet_info.id }, 'public_ip_address': { 'id': public_ip_address.id }", "'10.1.1.1', '10.1.2.4', ], ), subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), azure.mgmt.network.models.Subnet(", "self.get_resource_name('pyprobename') lb_name = self.get_resource_name('pylbname') front_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}'", "Public IP Address public_ip_name = self.get_resource_name('pyipname') params_create = azure.mgmt.network.models.PublicIPAddress( location=self.region,", "Create Front End Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, fe_name,", "vng_name = self.get_resource_name('pyvng') gw_params = { 'location': self.region, 'gateway_type': 'VPN',", "False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': { 'id': front_end_id } }] #", "# List RG lbs = self.network_client.load_balancers.list(self.group_name) lbs = list(lbs) self.assertGreater(len(lbs),", "Front End Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, fe_name, {'address_prefix':", ") result_create.wait() # AzureOperationPoller params_create = azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', )", "= self.get_resource_name('pysubnet') subnet1_name = self.get_resource_name('pysubnetone') subnet2_name = self.get_resource_name('pysubnettwo') params_create =", ") self.assertEqual(route_table.name, route_table_name) route_tables = list(self.network_client.route_tables.list( self.group_name )) self.assertEqual(len(route_tables), 1)", "probe_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/probes/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name,", "self.network_client.express_route_circuits.get_stats( self.group_name, express_route_name ) self.assertIsNotNone(stats) async_peering = self.network_client.express_route_circuit_peerings.create_or_update( self.group_name, express_route_name,", "express_route_name, 'AzurePublicPeering' ) peerings = list(self.network_client.express_route_circuit_peerings.list( self.group_name, express_route_name )) self.assertEqual(len(peerings),", ") back_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/backendAddressPools/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name,", "async_security_rule = self.network_client.security_rules.create_or_update( self.group_name, security_group_name, new_security_rule_name, { 'access':azure.mgmt.network.models.SecurityRuleAccess.allow, 'description':'New Test", "self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create, ) vnet = result_create.result() vnet =", "{ 'id': front_end_id }, 'backend_address_pool': { 'id': back_end_id }, 'probe':", "def test_network_interface_card(self): vnet_name = self.get_resource_name('pyvnet') subnet_name = self.get_resource_name('pysubnet') nic_name =", "'AzurePublicPeering', { \"peering_type\": \"AzurePublicPeering\", \"peer_asn\": 100, \"primary_peer_address_prefix\": \"192.168.1.0/30\", \"secondary_peer_address_prefix\": \"192.168.2.0/30\",", "new_security_rule_name, { 'access':azure.mgmt.network.models.SecurityRuleAccess.allow, 'description':'New Test security rule', 'destination_address_prefix':'*', 'destination_port_range':'123-3500', 'direction':azure.mgmt.network.models.SecurityRuleDirection.outbound,", "{} ) auth = async_auth.result() auth = self.network_client.express_route_circuit_authorizations.get( self.group_name, express_route_name,", ") self.assertEqual(route.name, route_name) routes = list(self.network_client.routes.list( self.group_name, route_table.name )) self.assertEqual(len(routes),", "self.get_resource_name('pyvnetsubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[ '10.0.0.0/16', ], ),", "list(self.network_client.express_route_circuit_peerings.list( self.group_name, express_route_name )) self.assertEqual(len(peerings), 1) stats = self.network_client.express_route_circuits.get_peering_stats( self.group_name,", "= self.network_client.public_ip_addresses.get( self.group_name, public_ip_name, ) #self.assertEqual(result_get.status_code, HttpStatusCode.OK) self.assertEqual(result_get.location, self.region) self.assertEqual(result_get.tags['key'],", "lbs = self.network_client.load_balancers.list_all() lbs = list(lbs) self.assertGreater(len(lbs), 0) # List", "nic_info.name ) async_delete.wait() @record def test_load_balancers(self): public_ip_name = self.get_resource_name('pyipname') frontend_ip_name", "'source_port_range':'655', } ) security_rule = async_security_rule.result() security_rule = self.network_client.security_rules.get( self.group_name,", "under the MIT License. See License.txt in the project root", "self.network_client.public_ip_addresses.get( self.group_name, public_ip_name, ) #self.assertEqual(result_get.status_code, HttpStatusCode.OK) self.assertEqual(result_get.location, self.region) self.assertEqual(result_get.tags['key'], 'value')", "for # license information. #-------------------------------------------------------------------------- import unittest import azure.mgmt.network.models from", ") public_ip_info = async_publicip_creation.result() # Building a FrontEndIpPool frontend_ip_configurations =", "{ 'id': public_ip_info.id } }] # Building a BackEnd adress", "'10.1.2.4', ], ), subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), azure.mgmt.network.models.Subnet( name=subnet2_name,", "1) route_tables = list(self.network_client.route_tables.list_all()) self.assertGreater(len(route_tables), 0) async_route = self.network_client.routes.create_or_update( self.group_name,", "result_list = list(result_list) self.assertEqual(len(result_list), 1) result_list_all = self.network_client.public_ip_addresses.list_all() #self.assertEqual(result_list_all.status_code, HttpStatusCode.OK)", "1) stats = self.network_client.express_route_circuits.get_peering_stats( self.group_name, express_route_name, 'AzurePublicPeering' ) self.assertIsNotNone(stats) auth_name", "= self.get_resource_name('pyfipname') addr_pool_name = self.get_resource_name('pyapname') probe_name = self.get_resource_name('pyprobename') lb_name =", "async_delete = self.network_client.network_interfaces.delete( self.group_name, nic_info.name ) async_delete.wait() @record def test_load_balancers(self):", "self.assertEqual(security_rule.name, new_security_rule_name) new_security_rules = list(self.network_client.security_rules.list( self.group_name, security_group_name )) self.assertEqual(len(new_security_rules), 2)", "Building InboundNATRule1 inbound_nat_rules = [{ 'name': 'azure-sample-netrule1', 'protocol': 'tcp', 'frontend_port':", "# Creating Load Balancer lb_async_creation = self.network_client.load_balancers.create_or_update( self.group_name, lb_name, {", ") result_delete.wait() @record def test_network_security_groups(self): security_group_name = self.get_resource_name('pysecgroup') security_rule_name =", "HttpStatusCode, AzureMgmtTestCase class MgmtNetworkTest(AzureMgmtTestCase): def setUp(self): super(MgmtNetworkTest, self).setUp() self.network_client =", "'/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/probes/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, probe_name ) #", "self.get_resource_name('pylbname') front_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/frontendIPConfigurations/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name,", "# Building a LoadBalancer rule load_balancing_rules = [{ 'name': 'azure-sample-lb-rule',", "result_list = list(self.network_client.network_security_groups.list( self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.network_security_groups.list_all())", "#self.assertEqual(result_get.status_code, HttpStatusCode.OK) self.assertEqual(result_get.location, self.region) self.assertEqual(result_get.tags['key'], 'value') result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code,", "\"location\": self.region, \"sku\": { \"name\": \"Standard_MeteredData\", \"tier\": \"Standard\", \"family\": \"MeteredData\"", "}, ) result_create = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create, ) result_create.wait()", "}] # Building a HealthProbe probes = [{ 'name': probe_name,", "self.network_client.routes.get( self.group_name, route_table.name, route.name ) self.assertEqual(route.name, route_name) routes = list(self.network_client.routes.list(", "'frontend_ip_configuration': { 'id': front_end_id } }) # Creating Load Balancer", "# Get it lb_info = self.network_client.load_balancers.get( self.group_name, lb_name ) #", "test_usages(self): usages = list(self.network_client.usages.list(self.region)) self.assertGreater(len(usages), 1) self.assertTrue(all(hasattr(u, 'name') for u", "'/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/backendAddressPools/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, addr_pool_name ) probe_id", "async_lb_delete.wait() @record def test_public_ip_addresses(self): public_ip_name = self.get_resource_name('pyipname') params_create = azure.mgmt.network.models.PublicIPAddress(", "network_name = self.get_resource_name('pyvnet') subnet1_name = self.get_resource_name('pyvnetsubnetone') subnet2_name = self.get_resource_name('pyvnetsubnettwo') params_create", "network_name, subnet2_name, ) result_delete.wait() @record def test_network_security_groups(self): security_group_name = self.get_resource_name('pysecgroup')", "= async_subnet_creation.result() # Create Back End Subnet async_subnet_creation = self.network_client.subnets.create_or_update(", "async_delete = self.network_client.virtual_networks.delete( self.group_name, network_name, ) async_delete.wait() @record def test_dns_availability(self):", "'ip_configurations': [{ 'name': 'MyIpConfig', 'subnet': { 'id': subnet_info.id } }]", "'load_distribution': 'Default', 'frontend_ip_configuration': { 'id': front_end_id }, 'backend_address_pool': { 'id':", "#self.assertEqual(result_list_all.status_code, HttpStatusCode.OK) result_list_all = list(result_list_all) self.assertGreater(len(result_list_all), 0) result_delete = self.network_client.public_ip_addresses.delete(", "async_express_route = self.network_client.express_route_circuits.create_or_update( self.group_name, express_route_name, { \"location\": self.region, \"sku\": {", "result_list = list(self.network_client.virtual_networks.list( self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.virtual_networks.list_all())", "'frontend_port': 23, 'backend_port': 22, 'enable_floating_ip': False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': {", "HttpStatusCode.OK) result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list),", "result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list), 1)", "= list(result_list_all) self.assertGreater(len(result_list_all), 0) result_delete = self.network_client.public_ip_addresses.delete( self.group_name, public_ip_name, )", "inbound_nat_rules.append({ 'name': 'azure-sample-netrule2', 'protocol': 'tcp', 'frontend_port': 23, 'backend_port': 22, 'enable_floating_ip':", "self.group_name, express_route_name, 'AzurePublicPeering' ) self.assertIsNotNone(stats) auth_name = self.get_resource_name('pyauth') async_auth =", "('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/probes/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, probe_name )", "network_name, params_create, ) vnet = result_create.result() vnet = self.network_client.virtual_networks.get( self.group_name,", "@record def test_load_balancers(self): public_ip_name = self.get_resource_name('pyipname') frontend_ip_name = self.get_resource_name('pyfipname') addr_pool_name", "result_list_all = list(self.network_client.virtual_networks.list_all()) async_delete = self.network_client.virtual_networks.delete( self.group_name, network_name, ) async_delete.wait()", "rule load_balancing_rules = [{ 'name': 'azure-sample-lb-rule', 'protocol': 'tcp', 'frontend_port': 80,", "security_group_name, security_rule.name ) self.assertEqual(security_rule.name, new_security_rule_name) new_security_rules = list(self.network_client.security_rules.list( self.group_name, security_group_name", "'id': gateway_subnet_info.id }, 'public_ip_address': { 'id': public_ip_address.id } }], }", "async_vnet_creation.wait() # Create Front End Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name,", "self.network_client.route_tables.create_or_update( self.group_name, route_table_name, {'location': self.region} ) route_table = async_route_table.result() route_table", "{ \"service_provider_name\": \"Comcast\", \"peering_location\": \"Chicago\", \"bandwidth_in_mbps\": 100 } } )", "vnet_name = self.get_resource_name('pyvirtnet') fe_name = self.get_resource_name('pysubnetfe') be_name = self.get_resource_name('pysubnetbe') gateway_name", "public_ip_name, params_create, ) result_create.wait() # AzureOperationPoller #self.assertEqual(result_create.status_code, HttpStatusCode.OK) result_get =", "from tests.mgmt_testcase import HttpStatusCode, AzureMgmtTestCase class MgmtNetworkTest(AzureMgmtTestCase): def setUp(self): super(MgmtNetworkTest,", "= list(self.network_client.security_rules.list( self.group_name, security_group_name )) self.assertEqual(len(new_security_rules), 2) result_delete = self.network_client.security_rules.delete(", "= self.network_client.express_route_circuit_authorizations.create_or_update( self.group_name, express_route_name, auth_name, {} ) auth = async_auth.result()", "= self.network_client.subnets.create_or_update( self.group_name, vnet_name, fe_name, {'address_prefix': '10.11.0.0/24'} ) fe_subnet_info =", "Delete NSG result_delete = self.network_client.network_security_groups.delete( self.group_name, security_group_name, ) result_delete.wait() @record", "= self.network_client.load_balancers.delete( self.group_name, lb_name ) async_lb_delete.wait() @record def test_public_ip_addresses(self): public_ip_name", "= self.network_client.subnets.create_or_update( self.group_name, vnet_name, subnet_name, {'address_prefix': '10.0.0.0/24'} ) subnet_info =", "'vpn_type': 'RouteBased', 'enable_bgp': False, 'sku': { 'tier': 'Standard', 'capacity': 2,", "= self.network_client.public_ip_addresses.list_all() #self.assertEqual(result_list_all.status_code, HttpStatusCode.OK) result_list_all = list(result_list_all) self.assertGreater(len(result_list_all), 0) result_delete", "'next_hop_type': 'None' } ) route = async_route.result() route = self.network_client.routes.get(", "\"secondary_peer_address_prefix\": \"192.168.2.0/30\", \"vlan_id\": 200, } ) peering = async_peering.result() peering", "async_route_delete = self.network_client.routes.delete( self.group_name, route_table.name, route.name ) async_route_delete.wait() async_route_table_delete =", "project root for # license information. #-------------------------------------------------------------------------- import unittest import", "'address_prefixes': [ '10.11.0.0/16', '10.12.0.0/16' ] } } ) async_vnet_creation.wait() #", "subnet2_name, params_create, ) result_create.wait() # AzureOperationPoller result_get = self.network_client.virtual_networks.get( self.group_name,", "self.group_name, express_route_name, auth_name, {} ) auth = async_auth.result() auth =", "super(MgmtNetworkTest, self).setUp() self.network_client = self.create_mgmt_client( azure.mgmt.network.NetworkManagementClient ) if not self.is_playback():", "params_create, ) public_ip_address = result_create.result() # Gateway itself vng_name =", "'Dynamic', 'public_ip_address': { 'id': public_ip_info.id } }] # Building a", "= result_create.result() vnet = self.network_client.virtual_networks.get( self.group_name, vnet.name, ) ip_availability =", "self.assertEqual(len(nics), 1) nics = list(self.network_client.network_interfaces.list_all()) self.assertGreater(len(nics), 0) async_delete = self.network_client.network_interfaces.delete(", "{ 'id': public_ip_address.id } }], } async_create = self.network_client.virtual_network_gateways.create_or_update( self.group_name,", "= self.network_client.express_route_circuit_peerings.create_or_update( self.group_name, express_route_name, 'AzurePublicPeering', { \"peering_type\": \"AzurePublicPeering\", \"peer_asn\": 100,", "def test_virtual_networks(self): network_name = self.get_resource_name('pyvnet') subnet1_name = self.get_resource_name('pyvnetsubnetone') subnet2_name =", "addr_pool_name }] # Building a HealthProbe probes = [{ 'name':", "public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic, tags={ 'key': 'value', }, ) result_create = self.network_client.public_ip_addresses.create_or_update( self.group_name,", "'id': front_end_id }, 'backend_address_pool': { 'id': back_end_id }, 'probe': {", "gw_params ) vng = async_create.result() self.assertEquals(vng.name, vng_name) #------------------------------------------------------------------------------ if __name__", "NSG result_delete = self.network_client.network_security_groups.delete( self.group_name, security_group_name, ) result_delete.wait() @record def", "= [{ 'name': 'azure-sample-lb-rule', 'protocol': 'tcp', 'frontend_port': 80, 'backend_port': 80,", "'/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/frontendIPConfigurations/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, frontend_ip_name ) back_end_id", "self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, addr_pool_name ) probe_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network'", "list(self.network_client.network_interfaces.list( self.group_name )) self.assertEqual(len(nics), 1) nics = list(self.network_client.network_interfaces.list_all()) self.assertGreater(len(nics), 0)", "= self.network_client.routes.get( self.group_name, route_table.name, route.name ) self.assertEqual(route.name, route_name) routes =", "express_route = self.network_client.express_route_circuits.get( self.group_name, express_route_name ) routes = list(self.network_client.express_route_circuits.list( self.group_name", "{ 'access':azure.mgmt.network.models.SecurityRuleAccess.allow, 'description':'New Test security rule', 'destination_address_prefix':'*', 'destination_port_range':'123-3500', 'direction':azure.mgmt.network.models.SecurityRuleDirection.outbound, 'priority':400,", "= list(self.network_client.route_tables.list( self.group_name )) self.assertEqual(len(route_tables), 1) route_tables = list(self.network_client.route_tables.list_all()) self.assertGreater(len(route_tables),", "self.region, 'ip_configurations': [{ 'name': 'MyIpConfig', 'subnet': { 'id': subnet_info.id }", "AzureOperationPoller result_get = self.network_client.virtual_networks.get( self.group_name, network_name, ) self.assertEqual(len(result_get.subnets), 2) result_get", "a BackEnd adress pool backend_address_pools = [{ 'name': addr_pool_name }]", "# Delete NSG result_delete = self.network_client.network_security_groups.delete( self.group_name, security_group_name, ) result_delete.wait()", "express_route_name ) async_express_route.wait() @record def test_virtual_network_gateway_operations(self): # https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-site-to-site-resource-manager-portal vnet_name =", "self.group_name, lb_name ) async_lb_delete.wait() @record def test_public_ip_addresses(self): public_ip_name = self.get_resource_name('pyipname')", "'10.0.0.0/16', ], ), dhcp_options=azure.mgmt.network.models.DhcpOptions( dns_servers=[ '10.1.1.1', '10.1.2.4', ], ), subnets=[", "\"Chicago\", \"bandwidth_in_mbps\": 100 } } ) express_route = async_express_route.result() express_route", "}, \"service_provider_properties\": { \"service_provider_name\": \"Comcast\", \"peering_location\": \"Chicago\", \"bandwidth_in_mbps\": 100 }", ") result_list = list(self.network_client.network_security_groups.list( self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all =", "self.create_mgmt_client( azure.mgmt.network.NetworkManagementClient ) if not self.is_playback(): self.create_resource_group() @record def test_network_interface_card(self):", "= list(self.network_client.virtual_networks.list_all()) async_delete = self.network_client.virtual_networks.delete( self.group_name, network_name, ) async_delete.wait() @record", ") result_create = self.network_client.network_security_groups.create_or_update( self.group_name, security_group_name, params_create, ) result_create.wait() #", "{'location': self.region} ) route_table = async_route_table.result() route_table = self.network_client.route_tables.get( self.group_name,", "= self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list), 0) @record", "list(self.network_client.usages.list(self.region)) self.assertGreater(len(usages), 1) self.assertTrue(all(hasattr(u, 'name') for u in usages)) @record", "= list(self.network_client.network_security_groups.list( self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.network_security_groups.list_all()) #", "\"service_provider_name\": \"Comcast\", \"peering_location\": \"Chicago\", \"bandwidth_in_mbps\": 100 } } ) express_route", "Create PublicIP public_ip_parameters = { 'location': self.region, 'public_ip_allocation_method': 'static', 'idle_timeout_in_minutes':", "# Building a FrontEndIpPool frontend_ip_configurations = [{ 'name': frontend_ip_name, 'private_ip_allocation_method':", "'enable_floating_ip': False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': { 'id': front_end_id } })", "self.get_resource_name('pyvnet') subnet_name = self.get_resource_name('pysubnet') nic_name = self.get_resource_name('pynic') # Create VNet", "name=security_rule_name, access=azure.mgmt.network.models.SecurityRuleAccess.allow, description='Test security rule', destination_address_prefix='*', destination_port_range='123-3500', direction=azure.mgmt.network.models.SecurityRuleDirection.inbound, priority=500, protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp,", "security rule', 'destination_address_prefix':'*', 'destination_port_range':'123-3500', 'direction':azure.mgmt.network.models.SecurityRuleDirection.outbound, 'priority':400, 'protocol':azure.mgmt.network.models.SecurityRuleProtocol.tcp, 'source_address_prefix':'*', 'source_port_range':'655', }", ") result_delete.wait() @record def test_routes(self): route_table_name = self.get_resource_name('pyroutetable') route_name =", "= async_route_table.result() route_table = self.network_client.route_tables.get( self.group_name, route_table.name ) self.assertEqual(route_table.name, route_table_name)", "@record def test_routes(self): route_table_name = self.get_resource_name('pyroutetable') route_name = self.get_resource_name('pyroute') async_route_table", "async_auth = self.network_client.express_route_circuit_authorizations.create_or_update( self.group_name, express_route_name, auth_name, {} ) auth =", "self.network_client.virtual_network_gateways.create_or_update( self.group_name, vng_name, gw_params ) vng = async_create.result() self.assertEquals(vng.name, vng_name)", "lb_async_creation = self.network_client.load_balancers.create_or_update( self.group_name, lb_name, { 'location': self.region, 'frontend_ip_configurations': frontend_ip_configurations,", "security_group_name, new_security_rule_name ) result_delete.wait() # Delete NSG result_delete = self.network_client.network_security_groups.delete(", "'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'probes': probes, 'load_balancing_rules': load_balancing_rules, 'inbound_nat_rules' :inbound_nat_rules", "self.group_name, public_ip_name, params_create, ) public_ip_address = result_create.result() # Gateway itself", "vnet_name, be_name, {'address_prefix': '10.12.0.0/24'} ) be_subnet_info = async_subnet_creation.result() # Create", "@record def test_express_route_service_providers(self): ersp = list(self.network_client.express_route_service_providers.list()) self.assertGreater(len(ersp), 0) self.assertTrue(all(hasattr(u, 'bandwidths_offered')", "License.txt in the project root for # license information. #--------------------------------------------------------------------------", "self.get_resource_name('pynewrule') async_security_rule = self.network_client.security_rules.create_or_update( self.group_name, security_group_name, new_security_rule_name, { 'access':azure.mgmt.network.models.SecurityRuleAccess.allow, 'description':'New", "express_route_name, auth_name ) auths = list(self.network_client.express_route_circuit_authorizations.list( self.group_name, express_route_name )) self.assertEqual(len(auths),", "'probe': { 'id': probe_id } }] # Building InboundNATRule1 inbound_nat_rules", "test_load_balancers(self): public_ip_name = self.get_resource_name('pyipname') frontend_ip_name = self.get_resource_name('pyfipname') addr_pool_name = self.get_resource_name('pyapname')", "name=subnet2_name, address_prefix='10.0.2.0/24', ) result_create = self.network_client.subnets.create_or_update( self.group_name, network_name, subnet2_name, params_create,", "self.group_name, network_name, ) async_delete.wait() @record def test_dns_availability(self): result_check = self.network_client.check_dns_name_availability(", "result_create = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create, ) result_create.wait() # AzureOperationPoller", "def test_usages(self): usages = list(self.network_client.usages.list(self.region)) self.assertGreater(len(usages), 1) self.assertTrue(all(hasattr(u, 'name') for", "be_name, {'address_prefix': '10.12.0.0/24'} ) be_subnet_info = async_subnet_creation.result() # Create Gateway", "# AzureOperationPoller #self.assertEqual(result_create.status_code, HttpStatusCode.OK) result_get = self.network_client.public_ip_addresses.get( self.group_name, public_ip_name, )", "unittest import azure.mgmt.network.models from testutils.common_recordingtestcase import record from tests.mgmt_testcase import", "subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), ], ) result_create = self.network_client.virtual_networks.create_or_update(", "network_name, ) subnets = list(result_list) result_delete = self.network_client.subnets.delete( self.group_name, network_name,", "security_rules=[ azure.mgmt.network.models.SecurityRule( name=security_rule_name, access=azure.mgmt.network.models.SecurityRuleAccess.allow, description='Test security rule', destination_address_prefix='*', destination_port_range='123-3500', direction=azure.mgmt.network.models.SecurityRuleDirection.inbound,", "'Standard'}, 'ip_configurations':[{ 'name': 'default', 'private_ip_allocation_method': 'Dynamic', 'subnet': { 'id': gateway_subnet_info.id", "= list(self.network_client.network_interfaces.list_all()) self.assertGreater(len(nics), 0) async_delete = self.network_client.network_interfaces.delete( self.group_name, nic_info.name )", "{'address_prefix': '10.12.0.0/24'} ) be_subnet_info = async_subnet_creation.result() # Create Gateway Subnet", "'name') for u in usages)) @record def test_express_route_service_providers(self): ersp =", "), subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), ], ) result_create =", "self.group_name, express_route_name )) self.assertEqual(len(peerings), 1) stats = self.network_client.express_route_circuits.get_peering_stats( self.group_name, express_route_name,", "self.get_resource_name('pysubnetbe') gateway_name = self.get_resource_name('pysubnetga') # Create VNet async_vnet_creation = self.network_client.virtual_networks.create_or_update(", "fe_name, {'address_prefix': '10.11.0.0/24'} ) fe_subnet_info = async_subnet_creation.result() # Create Back", "[{ 'name': addr_pool_name }] # Building a HealthProbe probes =", "self.get_resource_name('pysubnetga') # Create VNet async_vnet_creation = self.network_client.virtual_networks.create_or_update( self.group_name, vnet_name, {", "HttpStatusCode.OK) result_get = self.network_client.public_ip_addresses.get( self.group_name, public_ip_name, ) #self.assertEqual(result_get.status_code, HttpStatusCode.OK) self.assertEqual(result_get.location,", "lb_name ) async_lb_delete.wait() @record def test_public_ip_addresses(self): public_ip_name = self.get_resource_name('pyipname') params_create", "'public_ip_address': { 'id': public_ip_info.id } }] # Building a BackEnd", "def test_public_ip_addresses(self): public_ip_name = self.get_resource_name('pyipname') params_create = azure.mgmt.network.models.PublicIPAddress( location=self.region, public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic,", "self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.virtual_networks.list_all()) async_delete = self.network_client.virtual_networks.delete(", ") async_vnet_creation.wait() # Create Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name,", "self.group_name, security_group_name )) self.assertEqual(len(new_security_rules), 2) result_delete = self.network_client.security_rules.delete( self.group_name, security_group_name,", "= self.network_client.routes.delete( self.group_name, route_table.name, route.name ) async_route_delete.wait() async_route_table_delete = self.network_client.route_tables.delete(", "lb_async_creation.result() # Get it lb_info = self.network_client.load_balancers.get( self.group_name, lb_name )", "Create VNet async_vnet_creation = self.network_client.virtual_networks.create_or_update( self.group_name, vnet_name, { 'location': self.region,", "\"primary_peer_address_prefix\": \"192.168.1.0/30\", \"secondary_peer_address_prefix\": \"192.168.2.0/30\", \"vlan_id\": 200, } ) peering =", "self.group_name, security_group_name, new_security_rule_name ) result_delete.wait() # Delete NSG result_delete =", "= self.network_client.express_route_circuit_peerings.delete( self.group_name, express_route_name, 'AzurePublicPeering' ) async_peering.wait() async_express_route = self.network_client.express_route_circuits.delete(", "self.group_name, express_route_name )) self.assertEqual(len(auths), 1) async_auth = self.network_client.express_route_circuit_authorizations.delete( self.group_name, express_route_name,", "1) self.assertTrue(all(hasattr(u, 'name') for u in usages)) @record def test_express_route_service_providers(self):", "address_prefixes=[ '10.0.0.0/16', ], ), dhcp_options=azure.mgmt.network.models.DhcpOptions( dns_servers=[ '10.1.1.1', '10.1.2.4', ], ),", "subnet2_name = self.get_resource_name('pysubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[ '10.0.0.0/16',", ") auth = async_auth.result() auth = self.network_client.express_route_circuit_authorizations.get( self.group_name, express_route_name, auth_name", "security_group_name, ) result_list = list(self.network_client.network_security_groups.list( self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all", "= self.get_resource_name('pyvirtnet') fe_name = self.get_resource_name('pysubnetfe') be_name = self.get_resource_name('pysubnetbe') gateway_name =", "'None' } ) route = async_route.result() route = self.network_client.routes.get( self.group_name,", "the MIT License. See License.txt in the project root for", "test_public_ip_addresses(self): public_ip_name = self.get_resource_name('pyipname') params_create = azure.mgmt.network.models.PublicIPAddress( location=self.region, public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic, tags={", ") self.assertEqual(len(result_get.subnets), 2) result_get = self.network_client.subnets.get( self.group_name, network_name, subnet2_name, )", "self.assertEqual(len(peerings), 1) stats = self.network_client.express_route_circuits.get_peering_stats( self.group_name, express_route_name, 'AzurePublicPeering' ) self.assertIsNotNone(stats)", "security rule', destination_address_prefix='*', destination_port_range='123-3500', direction=azure.mgmt.network.models.SecurityRuleDirection.inbound, priority=500, protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp, source_address_prefix='*', source_port_range='655', ),", "'key': 'value', }, ) result_create = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create,", "self.network_client.network_security_groups.delete( self.group_name, security_group_name, ) result_delete.wait() @record def test_routes(self): route_table_name =", "'destination_address_prefix':'*', 'destination_port_range':'123-3500', 'direction':azure.mgmt.network.models.SecurityRuleDirection.outbound, 'priority':400, 'protocol':azure.mgmt.network.models.SecurityRuleProtocol.tcp, 'source_address_prefix':'*', 'source_port_range':'655', } ) security_rule", "} ) async_vnet_creation.wait() # Create Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name,", "result_delete = self.network_client.network_security_groups.delete( self.group_name, security_group_name, ) result_delete.wait() @record def test_routes(self):", "self.network_client.load_balancers.get( self.group_name, lb_name ) # List all lbs = self.network_client.load_balancers.list_all()", "] } } ) async_vnet_creation.wait() # Create Front End Subnet", "@record def test_public_ip_addresses(self): public_ip_name = self.get_resource_name('pyipname') params_create = azure.mgmt.network.models.PublicIPAddress( location=self.region,", "100, \"primary_peer_address_prefix\": \"192.168.1.0/30\", \"secondary_peer_address_prefix\": \"192.168.2.0/30\", \"vlan_id\": 200, } ) peering", "self.group_name, route_table.name )) self.assertEqual(len(routes), 1) async_route_delete = self.network_client.routes.delete( self.group_name, route_table.name,", "self.get_resource_name('pyvng') gw_params = { 'location': self.region, 'gateway_type': 'VPN', 'vpn_type': 'RouteBased',", "= self.network_client.load_balancers.list(self.group_name) lbs = list(lbs) self.assertGreater(len(lbs), 0) # Delete async_lb_delete", "End Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, be_name, {'address_prefix': '10.12.0.0/24'}", "self.assertEqual(len(auths), 1) async_auth = self.network_client.express_route_circuit_authorizations.delete( self.group_name, express_route_name, auth_name ) async_auth.wait()", "self.group_name, express_route_name ) self.assertIsNotNone(stats) async_peering = self.network_client.express_route_circuit_peerings.create_or_update( self.group_name, express_route_name, 'AzurePublicPeering',", "self.create_resource_group() @record def test_network_interface_card(self): vnet_name = self.get_resource_name('pyvnet') subnet_name = self.get_resource_name('pysubnet')", "# Should be available since new VNet sor Subnet 1", "security_group_name, new_security_rule_name, { 'access':azure.mgmt.network.models.SecurityRuleAccess.allow, 'description':'New Test security rule', 'destination_address_prefix':'*', 'destination_port_range':'123-3500',", "= self.network_client.express_route_circuits.get_peering_stats( self.group_name, express_route_name, 'AzurePublicPeering' ) self.assertIsNotNone(stats) auth_name = self.get_resource_name('pyauth')", "'number_of_probes': 4, 'request_path': 'healthprobe.aspx' }] # Building a LoadBalancer rule", "self.group_name, route_table.name, route.name ) self.assertEqual(route.name, route_name) routes = list(self.network_client.routes.list( self.group_name,", "tags={ 'key': 'value', }, ) result_create = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name,", ") async_lb_delete.wait() @record def test_public_ip_addresses(self): public_ip_name = self.get_resource_name('pyipname') params_create =", ") peerings = list(self.network_client.express_route_circuit_peerings.list( self.group_name, express_route_name )) self.assertEqual(len(peerings), 1) stats", "'id': back_end_id }, 'probe': { 'id': probe_id } }] #", "async_route_table.result() route_table = self.network_client.route_tables.get( self.group_name, route_table.name ) self.assertEqual(route_table.name, route_table_name) route_tables", "network_name = self.get_resource_name('pysubnet') subnet1_name = self.get_resource_name('pysubnetone') subnet2_name = self.get_resource_name('pysubnettwo') params_create", "nics = list(self.network_client.network_interfaces.list( self.group_name )) self.assertEqual(len(nics), 1) nics = list(self.network_client.network_interfaces.list_all())", "# Licensed under the MIT License. See License.txt in the", ") result_create = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create, ) result_create.wait() #", "= self.get_resource_name('pynewrule') async_security_rule = self.network_client.security_rules.create_or_update( self.group_name, security_group_name, new_security_rule_name, { 'access':azure.mgmt.network.models.SecurityRuleAccess.allow,", ") self.assertIsNotNone(stats) async_peering = self.network_client.express_route_circuit_peerings.create_or_update( self.group_name, express_route_name, 'AzurePublicPeering', { \"peering_type\":", "'backend_address_pools': backend_address_pools, 'probes': probes, 'load_balancing_rules': load_balancing_rules, 'inbound_nat_rules' :inbound_nat_rules } )", "HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list), 0) @record def test_virtual_networks(self): network_name", "new_security_rule_name ) result_delete.wait() # Delete NSG result_delete = self.network_client.network_security_groups.delete( self.group_name,", "'tier': 'Standard', 'capacity': 2, 'name': 'Standard'}, 'ip_configurations':[{ 'name': 'default', 'private_ip_allocation_method':", "self.group_name, route_table_name ) async_route_table_delete.wait() @record def test_usages(self): usages = list(self.network_client.usages.list(self.region))", "test_subnets(self): network_name = self.get_resource_name('pysubnet') subnet1_name = self.get_resource_name('pysubnetone') subnet2_name = self.get_resource_name('pysubnettwo')", "'10.12.255.0/27'} ) gateway_subnet_info = async_subnet_creation.result() # Public IP Address public_ip_name", ") self.assertIsNotNone(stats) auth_name = self.get_resource_name('pyauth') async_auth = self.network_client.express_route_circuit_authorizations.create_or_update( self.group_name, express_route_name,", "# Create Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, subnet_name, {'address_prefix':", "destination_port_range='123-3500', direction=azure.mgmt.network.models.SecurityRuleDirection.inbound, priority=500, protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp, source_address_prefix='*', source_port_range='655', ), ], ) result_create", "FrontEndIpPool frontend_ip_configurations = [{ 'name': frontend_ip_name, 'private_ip_allocation_method': 'Dynamic', 'public_ip_address': {", "lbs = list(lbs) self.assertGreater(len(lbs), 0) # List RG lbs =", "self.network_client.express_route_circuit_authorizations.create_or_update( self.group_name, express_route_name, auth_name, {} ) auth = async_auth.result() auth", "'Dynamic', 'subnet': { 'id': gateway_subnet_info.id }, 'public_ip_address': { 'id': public_ip_address.id", ") auths = list(self.network_client.express_route_circuit_authorizations.list( self.group_name, express_route_name )) self.assertEqual(len(auths), 1) async_auth", "vnet_name, 'GatewaySubnet', {'address_prefix': '10.12.255.0/27'} ) gateway_subnet_info = async_subnet_creation.result() # Public", "result_create = self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create, ) result_create.wait() # AzureOperationPoller", "= [{ 'name': addr_pool_name }] # Building a HealthProbe probes", "RG lbs = self.network_client.load_balancers.list(self.group_name) lbs = list(lbs) self.assertGreater(len(lbs), 0) #", "self.network_client.subnets.list( self.group_name, network_name, ) subnets = list(result_list) result_delete = self.network_client.subnets.delete(", "(c) Microsoft Corporation. All rights reserved. # Licensed under the", "\"service_provider_properties\": { \"service_provider_name\": \"Comcast\", \"peering_location\": \"Chicago\", \"bandwidth_in_mbps\": 100 } }", "[{ 'name': frontend_ip_name, 'private_ip_allocation_method': 'Dynamic', 'public_ip_address': { 'id': public_ip_info.id }", ") express_route = async_express_route.result() express_route = self.network_client.express_route_circuits.get( self.group_name, express_route_name )", "VNet async_vnet_creation = self.network_client.virtual_networks.create_or_update( self.group_name, vnet_name, { 'location': self.region, 'address_space':", "vng = async_create.result() self.assertEquals(vng.name, vng_name) #------------------------------------------------------------------------------ if __name__ == '__main__':", ") route_table = async_route_table.result() route_table = self.network_client.route_tables.get( self.group_name, route_table.name )", "self.group_name, route_table.name, route.name ) async_route_delete.wait() async_route_table_delete = self.network_client.route_tables.delete( self.group_name, route_table_name", "list(self.network_client.virtual_networks.list_all()) async_delete = self.network_client.virtual_networks.delete( self.group_name, network_name, ) async_delete.wait() @record def", "= list(self.network_client.express_route_circuits.list_all()) self.assertGreater(len(routes), 0) stats = self.network_client.express_route_circuits.get_stats( self.group_name, express_route_name )", "= self.network_client.virtual_networks.delete( self.group_name, network_name, ) async_delete.wait() @record def test_dns_availability(self): result_check", "['10.0.0.0/16'] } } ) async_vnet_creation.wait() # Create Subnet async_subnet_creation =", "self.group_name, vnet.name, ) ip_availability = self.network_client.virtual_networks.check_ip_address_availability( self.group_name, vnet.name, '10.0.1.35' #", "= azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[ '10.0.0.0/16', ], ), dhcp_options=azure.mgmt.network.models.DhcpOptions( dns_servers=[", "self.group_name, vnet_name, { 'location': self.region, 'address_space': { 'address_prefixes': [ '10.11.0.0/16',", "'/loadBalancers/{}' '/frontendIPConfigurations/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, frontend_ip_name ) back_end_id = ('/subscriptions/{}'", "'tcp', 'frontend_port': 80, 'backend_port': 80, 'idle_timeout_in_minutes': 4, 'enable_floating_ip': False, 'load_distribution':", "express_route_name = self.get_resource_name('pyexpressroute') async_express_route = self.network_client.express_route_circuits.create_or_update( self.group_name, express_route_name, { \"location\":", "auth = self.network_client.express_route_circuit_authorizations.get( self.group_name, express_route_name, auth_name ) auths = list(self.network_client.express_route_circuit_authorizations.list(", ") subnet_info = async_subnet_creation.result() # Create NIC async_nic_creation = self.network_client.network_interfaces.create_or_update(", "subnets=[ azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ), ],", "result_create.wait() # AzureOperationPoller #self.assertEqual(result_create.status_code, HttpStatusCode.OK) result_get = self.network_client.public_ip_addresses.get( self.group_name, public_ip_name,", "'subnet': { 'id': subnet_info.id } }] } ) nic_info =", "Create Gateway Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, 'GatewaySubnet', {'address_prefix':", "= self.get_resource_name('pysubnetga') # Create VNet async_vnet_creation = self.network_client.virtual_networks.create_or_update( self.group_name, vnet_name,", "for u in usages)) @record def test_express_route_service_providers(self): ersp = list(self.network_client.express_route_service_providers.list())", "self.assertGreater(len(lbs), 0) # Delete async_lb_delete = self.network_client.load_balancers.delete( self.group_name, lb_name )", "'probes': probes, 'load_balancing_rules': load_balancing_rules, 'inbound_nat_rules' :inbound_nat_rules } ) lb_info =", "'idle_timeout_in_minutes': 4 } async_publicip_creation = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, public_ip_parameters )", "'/providers/Microsoft.Network' '/loadBalancers/{}' '/backendAddressPools/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, addr_pool_name ) probe_id =", "list(self.network_client.route_tables.list( self.group_name )) self.assertEqual(len(route_tables), 1) route_tables = list(self.network_client.route_tables.list_all()) self.assertGreater(len(route_tables), 0)", "subnet2_name, ) result_list = self.network_client.subnets.list( self.group_name, network_name, ) subnets =", "self.get_resource_name('pyroute') async_route_table = self.network_client.route_tables.create_or_update( self.group_name, route_table_name, {'location': self.region} ) route_table", "Should be available since new VNet sor Subnet 1 )", "self.group_name, route_table.name, route_name, { 'address_prefix': '10.1.0.0/16', 'next_hop_type': 'None' } )", "{ 'location': self.region, 'address_space': { 'address_prefixes': ['10.0.0.0/16'] } } )", "Subnet 1 ) self.assertTrue(ip_availability.available) result_list = list(self.network_client.virtual_networks.list( self.group_name, )) self.assertEqual(len(result_list),", "= list(result_list) self.assertEqual(len(result_list), 1) result_list_all = self.network_client.public_ip_addresses.list_all() #self.assertEqual(result_list_all.status_code, HttpStatusCode.OK) result_list_all", "= async_create.result() self.assertEquals(vng.name, vng_name) #------------------------------------------------------------------------------ if __name__ == '__main__': unittest.main()", "}] } ) nic_info = async_nic_creation.result() nic_info = self.network_client.network_interfaces.get( self.group_name,", "security_group_name, params_create, ) result_create.wait() # AzureOperationPoller result_get = self.network_client.network_security_groups.get( self.group_name,", "'location': self.region, 'ip_configurations': [{ 'name': 'MyIpConfig', 'subnet': { 'id': subnet_info.id", ") result_delete.wait() # AzureOperationPoller #self.assertEqual(result_delete.status_code, HttpStatusCode.OK) result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code,", "route_table = async_route_table.result() route_table = self.network_client.route_tables.get( self.group_name, route_table.name ) self.assertEqual(route_table.name,", "back_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/backendAddressPools/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name,", "= self.network_client.network_interfaces.delete( self.group_name, nic_info.name ) async_delete.wait() @record def test_load_balancers(self): public_ip_name", "= self.get_resource_name('pyauth') async_auth = self.network_client.express_route_circuit_authorizations.create_or_update( self.group_name, express_route_name, auth_name, {} )", "gateway_subnet_info = async_subnet_creation.result() # Public IP Address public_ip_name = self.get_resource_name('pyipname')", "public_ip_info = async_publicip_creation.result() # Building a FrontEndIpPool frontend_ip_configurations = [{", "HttpStatusCode.OK) result_list = list(result_list) self.assertEqual(len(result_list), 1) result_list_all = self.network_client.public_ip_addresses.list_all() #self.assertEqual(result_list_all.status_code,", "= ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/probes/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, probe_name", "# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed", "self.group_name, network_name, subnet2_name, params_create, ) result_create.wait() # AzureOperationPoller result_get =", "# Building InboundNATRule1 inbound_nat_rules = [{ 'name': 'azure-sample-netrule1', 'protocol': 'tcp',", "self.group_name, express_route_name, auth_name ) async_auth.wait() async_peering = self.network_client.express_route_circuit_peerings.delete( self.group_name, express_route_name,", "), ], ) result_create = self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create, )", "IP Address public_ip_name = self.get_resource_name('pyipname') params_create = azure.mgmt.network.models.PublicIPAddress( location=self.region, public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic,", "probe_id } }] # Building InboundNATRule1 inbound_nat_rules = [{ 'name':", "self.network_client.public_ip_addresses.delete( self.group_name, public_ip_name, ) result_delete.wait() # AzureOperationPoller #self.assertEqual(result_delete.status_code, HttpStatusCode.OK) result_list", "async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, fe_name, {'address_prefix': '10.11.0.0/24'} ) fe_subnet_info", "Corporation. All rights reserved. # Licensed under the MIT License.", "= self.network_client.security_rules.create_or_update( self.group_name, security_group_name, new_security_rule_name, { 'access':azure.mgmt.network.models.SecurityRuleAccess.allow, 'description':'New Test security", "= self.get_resource_name('pyipname') params_create = azure.mgmt.network.models.PublicIPAddress( location=self.region, public_ip_allocation_method=azure.mgmt.network.models.IPAllocationMethod.dynamic, tags={ 'key': 'value',", ") result_create = self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create, ) result_create.wait() #", "= ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/frontendIPConfigurations/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name, frontend_ip_name", "be_subnet_info = async_subnet_creation.result() # Create Gateway Subnet async_subnet_creation = self.network_client.subnets.create_or_update(", "result_get = self.network_client.virtual_networks.get( self.group_name, network_name, ) self.assertEqual(len(result_get.subnets), 2) result_get =", ":inbound_nat_rules } ) lb_info = lb_async_creation.result() # Get it lb_info", "self.assertIsNotNone(stats) async_peering = self.network_client.express_route_circuit_peerings.create_or_update( self.group_name, express_route_name, 'AzurePublicPeering', { \"peering_type\": \"AzurePublicPeering\",", "result_delete = self.network_client.security_rules.delete( self.group_name, security_group_name, new_security_rule_name ) result_delete.wait() # Delete", "= async_express_route.result() express_route = self.network_client.express_route_circuits.get( self.group_name, express_route_name ) routes =", "80, 'interval_in_seconds': 15, 'number_of_probes': 4, 'request_path': 'healthprobe.aspx' }] # Building", "lb_name ) # List all lbs = self.network_client.load_balancers.list_all() lbs =", "self.region, 'address_space': { 'address_prefixes': ['10.0.0.0/16'] } } ) async_vnet_creation.wait() #", "= self.network_client.virtual_networks.check_ip_address_availability( self.group_name, vnet.name, '10.0.1.35' # Should be available since", "self.get_resource_name('pysubnetone') subnet2_name = self.get_resource_name('pysubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[", "= self.get_resource_name('pyvnetsubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[ '10.0.0.0/16', ],", "self.network_client.virtual_networks.create_or_update( self.group_name, vnet_name, { 'location': self.region, 'address_space': { 'address_prefixes': ['10.0.0.0/16']", "address_prefix='10.0.2.0/24', ), ], ) result_create = self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create,", "security_group_name = self.get_resource_name('pysecgroup') security_rule_name = self.get_resource_name('pysecgrouprule') params_create = azure.mgmt.network.models.NetworkSecurityGroup( location=self.region,", "{ \"peering_type\": \"AzurePublicPeering\", \"peer_asn\": 100, \"primary_peer_address_prefix\": \"192.168.1.0/30\", \"secondary_peer_address_prefix\": \"192.168.2.0/30\", \"vlan_id\":", "self.group_name, security_group_name, new_security_rule_name, { 'access':azure.mgmt.network.models.SecurityRuleAccess.allow, 'description':'New Test security rule', 'destination_address_prefix':'*',", "'id': public_ip_address.id } }], } async_create = self.network_client.virtual_network_gateways.create_or_update( self.group_name, vng_name,", "= self.network_client.virtual_networks.create_or_update( self.group_name, vnet_name, { 'location': self.region, 'address_space': { 'address_prefixes':", "1) result_list_all = list(self.network_client.virtual_networks.list_all()) async_delete = self.network_client.virtual_networks.delete( self.group_name, network_name, )", "'azure-sample-netrule1', 'protocol': 'tcp', 'frontend_port': 21, 'backend_port': 22, 'enable_floating_ip': False, 'idle_timeout_in_minutes':", "test_express_route_service_providers(self): ersp = list(self.network_client.express_route_service_providers.list()) self.assertGreater(len(ersp), 0) self.assertTrue(all(hasattr(u, 'bandwidths_offered') for u", "'backend_port': 22, 'enable_floating_ip': False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': { 'id': front_end_id", "self.network_client.express_route_circuit_authorizations.delete( self.group_name, express_route_name, auth_name ) async_auth.wait() async_peering = self.network_client.express_route_circuit_peerings.delete( self.group_name,", "source_address_prefix='*', source_port_range='655', ), ], ) result_create = self.network_client.network_security_groups.create_or_update( self.group_name, security_group_name,", "} ) lb_info = lb_async_creation.result() # Get it lb_info =", "@record def test_virtual_network_gateway_operations(self): # https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-site-to-site-resource-manager-portal vnet_name = self.get_resource_name('pyvirtnet') fe_name =", "= list(lbs) self.assertGreater(len(lbs), 0) # List RG lbs = self.network_client.load_balancers.list(self.group_name)", "self.network_client.network_interfaces.get( self.group_name, nic_info.name ) nics = list(self.network_client.network_interfaces.list( self.group_name )) self.assertEqual(len(nics),", "params_create, ) vnet = result_create.result() vnet = self.network_client.virtual_networks.get( self.group_name, vnet.name,", "self.group_name, network_name, subnet2_name, ) result_delete.wait() @record def test_network_security_groups(self): security_group_name =", "\"Standard_MeteredData\", \"tier\": \"Standard\", \"family\": \"MeteredData\" }, \"service_provider_properties\": { \"service_provider_name\": \"Comcast\",", "self.network_client.security_rules.delete( self.group_name, security_group_name, new_security_rule_name ) result_delete.wait() # Delete NSG result_delete", "self.get_resource_name('pysecgroup') security_rule_name = self.get_resource_name('pysecgrouprule') params_create = azure.mgmt.network.models.NetworkSecurityGroup( location=self.region, security_rules=[ azure.mgmt.network.models.SecurityRule(", "self.network_client.express_route_circuit_peerings.delete( self.group_name, express_route_name, 'AzurePublicPeering' ) async_peering.wait() async_express_route = self.network_client.express_route_circuits.delete( self.group_name,", "async_auth.wait() async_peering = self.network_client.express_route_circuit_peerings.delete( self.group_name, express_route_name, 'AzurePublicPeering' ) async_peering.wait() async_express_route", "public_ip_name, ) #self.assertEqual(result_get.status_code, HttpStatusCode.OK) self.assertEqual(result_get.location, self.region) self.assertEqual(result_get.tags['key'], 'value') result_list =", "'frontend_port': 21, 'backend_port': 22, 'enable_floating_ip': False, 'idle_timeout_in_minutes': 4, 'frontend_ip_configuration': {", "azure.mgmt.network.models.Subnet( name=subnet1_name, address_prefix='10.0.1.0/24', ), ], ) result_create = self.network_client.virtual_networks.create_or_update( self.group_name,", "= self.get_resource_name('pynic') # Create VNet async_vnet_creation = self.network_client.virtual_networks.create_or_update( self.group_name, vnet_name,", "self.get_resource_name('pyvnet') subnet1_name = self.get_resource_name('pyvnetsubnetone') subnet2_name = self.get_resource_name('pyvnetsubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork(", "{ \"name\": \"Standard_MeteredData\", \"tier\": \"Standard\", \"family\": \"MeteredData\" }, \"service_provider_properties\": {", "self.group_name, express_route_name, 'AzurePublicPeering', { \"peering_type\": \"AzurePublicPeering\", \"peer_asn\": 100, \"primary_peer_address_prefix\": \"192.168.1.0/30\",", "'direction':azure.mgmt.network.models.SecurityRuleDirection.outbound, 'priority':400, 'protocol':azure.mgmt.network.models.SecurityRuleProtocol.tcp, 'source_address_prefix':'*', 'source_port_range':'655', } ) security_rule = async_security_rule.result()", "self.get_resource_name('pysubnetfe') be_name = self.get_resource_name('pysubnetbe') gateway_name = self.get_resource_name('pysubnetga') # Create VNet", "result_list_all = list(self.network_client.network_security_groups.list_all()) # Security Rules new_security_rule_name = self.get_resource_name('pynewrule') async_security_rule", "front_end_id }, 'backend_address_pool': { 'id': back_end_id }, 'probe': { 'id':", "4 } async_publicip_creation = self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, public_ip_parameters ) public_ip_info", "@record def test_express_route_circuit(self): express_route_name = self.get_resource_name('pyexpressroute') async_express_route = self.network_client.express_route_circuits.create_or_update( self.group_name,", "self.assertTrue(result_check) @record def test_subnets(self): network_name = self.get_resource_name('pysubnet') subnet1_name = self.get_resource_name('pysubnetone')", "express_route_name )) self.assertEqual(len(auths), 1) async_auth = self.network_client.express_route_circuit_authorizations.delete( self.group_name, express_route_name, auth_name", "list(self.network_client.virtual_networks.list( self.group_name, )) self.assertEqual(len(result_list), 1) result_list_all = list(self.network_client.virtual_networks.list_all()) async_delete =", "'name': probe_name, 'protocol': 'Http', 'port': 80, 'interval_in_seconds': 15, 'number_of_probes': 4,", "routes = list(self.network_client.express_route_circuits.list( self.group_name )) self.assertEqual(len(routes), 1) routes = list(self.network_client.express_route_circuits.list_all())", "self.group_name, network_name, ) self.assertEqual(len(result_get.subnets), 2) result_get = self.network_client.subnets.get( self.group_name, network_name,", "test_dns_availability(self): result_check = self.network_client.check_dns_name_availability( self.region, 'pydomain', ) #self.assertEqual(result_check.status_code, HttpStatusCode.OK) self.assertTrue(result_check)", "= async_subnet_creation.result() # Create Gateway Subnet async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name,", "PublicIP public_ip_parameters = { 'location': self.region, 'public_ip_allocation_method': 'static', 'idle_timeout_in_minutes': 4", "async_subnet_creation = self.network_client.subnets.create_or_update( self.group_name, vnet_name, 'GatewaySubnet', {'address_prefix': '10.12.255.0/27'} ) gateway_subnet_info", "security_group_name )) self.assertEqual(len(new_security_rules), 2) result_delete = self.network_client.security_rules.delete( self.group_name, security_group_name, new_security_rule_name", "list(self.network_client.network_interfaces.list_all()) self.assertGreater(len(nics), 0) async_delete = self.network_client.network_interfaces.delete( self.group_name, nic_info.name ) async_delete.wait()", "async_nic_creation = self.network_client.network_interfaces.create_or_update( self.group_name, nic_name, { 'location': self.region, 'ip_configurations': [{", "reserved. # Licensed under the MIT License. See License.txt in", "self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create, ) public_ip_address = result_create.result() # Gateway", "self.network_client.security_rules.get( self.group_name, security_group_name, security_rule.name ) self.assertEqual(security_rule.name, new_security_rule_name) new_security_rules = list(self.network_client.security_rules.list(", "} ) express_route = async_express_route.result() express_route = self.network_client.express_route_circuits.get( self.group_name, express_route_name", "self.network_client.subnets.create_or_update( self.group_name, network_name, subnet2_name, params_create, ) result_create.wait() # AzureOperationPoller result_get", "= azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ) result_create = self.network_client.subnets.create_or_update( self.group_name, network_name,", "} ) security_rule = async_security_rule.result() security_rule = self.network_client.security_rules.get( self.group_name, security_group_name,", "= self.network_client.load_balancers.list_all() lbs = list(lbs) self.assertGreater(len(lbs), 0) # List RG", "async_auth.result() auth = self.network_client.express_route_circuit_authorizations.get( self.group_name, express_route_name, auth_name ) auths =", "self.get_resource_name('pyapname') probe_name = self.get_resource_name('pyprobename') lb_name = self.get_resource_name('pylbname') front_end_id = ('/subscriptions/{}'", "public_ip_parameters ) public_ip_info = async_publicip_creation.result() # Building a FrontEndIpPool frontend_ip_configurations", "route.name ) self.assertEqual(route.name, route_name) routes = list(self.network_client.routes.list( self.group_name, route_table.name ))", "frontend_ip_name, 'private_ip_allocation_method': 'Dynamic', 'public_ip_address': { 'id': public_ip_info.id } }] #", "= self.network_client.virtual_networks.create_or_update( self.group_name, network_name, params_create, ) vnet = result_create.result() vnet", "stats = self.network_client.express_route_circuits.get_peering_stats( self.group_name, express_route_name, 'AzurePublicPeering' ) self.assertIsNotNone(stats) auth_name =", "@record def test_virtual_networks(self): network_name = self.get_resource_name('pyvnet') subnet1_name = self.get_resource_name('pyvnetsubnetone') subnet2_name", "'10.1.0.0/16', 'next_hop_type': 'None' } ) route = async_route.result() route =", "self.assertGreater(len(routes), 0) stats = self.network_client.express_route_circuits.get_stats( self.group_name, express_route_name ) self.assertIsNotNone(stats) async_peering", "'description':'New Test security rule', 'destination_address_prefix':'*', 'destination_port_range':'123-3500', 'direction':azure.mgmt.network.models.SecurityRuleDirection.outbound, 'priority':400, 'protocol':azure.mgmt.network.models.SecurityRuleProtocol.tcp, 'source_address_prefix':'*',", "'source_address_prefix':'*', 'source_port_range':'655', } ) security_rule = async_security_rule.result() security_rule = self.network_client.security_rules.get(", "'port': 80, 'interval_in_seconds': 15, 'number_of_probes': 4, 'request_path': 'healthprobe.aspx' }] #", "self.group_name, express_route_name, 'AzurePublicPeering' ) async_peering.wait() async_express_route = self.network_client.express_route_circuits.delete( self.group_name, express_route_name", "probe_name, 'protocol': 'Http', 'port': 80, 'interval_in_seconds': 15, 'number_of_probes': 4, 'request_path':", "self.network_client.express_route_circuits.get_peering_stats( self.group_name, express_route_name, 'AzurePublicPeering' ) self.assertIsNotNone(stats) auth_name = self.get_resource_name('pyauth') async_auth", "HttpStatusCode.OK) self.assertTrue(result_check) @record def test_subnets(self): network_name = self.get_resource_name('pysubnet') subnet1_name =", "self.network_client.network_interfaces.delete( self.group_name, nic_info.name ) async_delete.wait() @record def test_load_balancers(self): public_ip_name =", ") async_express_route.wait() @record def test_virtual_network_gateway_operations(self): # https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-howto-site-to-site-resource-manager-portal vnet_name = self.get_resource_name('pyvirtnet')", "ip_availability = self.network_client.virtual_networks.check_ip_address_availability( self.group_name, vnet.name, '10.0.1.35' # Should be available", "{ 'location': self.region, 'gateway_type': 'VPN', 'vpn_type': 'RouteBased', 'enable_bgp': False, 'sku':", "self.assertEqual(result_get.tags['key'], 'value') result_list = self.network_client.public_ip_addresses.list(self.group_name) #self.assertEqual(result_list.status_code, HttpStatusCode.OK) result_list = list(result_list)", "= self.get_resource_name('pyprobename') lb_name = self.get_resource_name('pylbname') front_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network'", "= self.network_client.public_ip_addresses.create_or_update( self.group_name, public_ip_name, params_create, ) result_create.wait() # AzureOperationPoller #self.assertEqual(result_create.status_code,", "probes = [{ 'name': probe_name, 'protocol': 'Http', 'port': 80, 'interval_in_seconds':", "self.assertEqual(len(routes), 1) async_route_delete = self.network_client.routes.delete( self.group_name, route_table.name, route.name ) async_route_delete.wait()", "vnet_name, fe_name, {'address_prefix': '10.11.0.0/24'} ) fe_subnet_info = async_subnet_creation.result() # Create", "self.network_client.public_ip_addresses.list_all() #self.assertEqual(result_list_all.status_code, HttpStatusCode.OK) result_list_all = list(result_list_all) self.assertGreater(len(result_list_all), 0) result_delete =", "'AzurePublicPeering' ) peerings = list(self.network_client.express_route_circuit_peerings.list( self.group_name, express_route_name )) self.assertEqual(len(peerings), 1)", "rights reserved. # Licensed under the MIT License. See License.txt", "route_table_name) route_tables = list(self.network_client.route_tables.list( self.group_name )) self.assertEqual(len(route_tables), 1) route_tables =", "# AzureOperationPoller params_create = azure.mgmt.network.models.Subnet( name=subnet2_name, address_prefix='10.0.2.0/24', ) result_create =", "self.get_resource_name('pyvnetsubnetone') subnet2_name = self.get_resource_name('pyvnetsubnettwo') params_create = azure.mgmt.network.models.VirtualNetwork( location=self.region, address_space=azure.mgmt.network.models.AddressSpace( address_prefixes=[", "self.group_name, public_ip_name, public_ip_parameters ) public_ip_info = async_publicip_creation.result() # Building a", "auth_name ) async_auth.wait() async_peering = self.network_client.express_route_circuit_peerings.delete( self.group_name, express_route_name, 'AzurePublicPeering' )", "subnet_info.id } }] } ) nic_info = async_nic_creation.result() nic_info =", "async_route_table_delete = self.network_client.route_tables.delete( self.group_name, route_table_name ) async_route_table_delete.wait() @record def test_usages(self):", "front_end_id = ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/frontendIPConfigurations/{}').format( self.settings.SUBSCRIPTION_ID, self.group_name, lb_name,", "route_table.name )) self.assertEqual(len(routes), 1) async_route_delete = self.network_client.routes.delete( self.group_name, route_table.name, route.name", "gw_params = { 'location': self.region, 'gateway_type': 'VPN', 'vpn_type': 'RouteBased', 'enable_bgp':", "public_ip_address = result_create.result() # Gateway itself vng_name = self.get_resource_name('pyvng') gw_params", "list(result_list) result_delete = self.network_client.subnets.delete( self.group_name, network_name, subnet2_name, ) result_delete.wait() @record", "self.get_resource_name('pyauth') async_auth = self.network_client.express_route_circuit_authorizations.create_or_update( self.group_name, express_route_name, auth_name, {} ) auth" ]
[ "print('Cam client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def step(self): self.main_client_thread(self.conn1) self.cam_client_thread(self.conn2) if", "= np.array(12345, dtype=np.float32) # Socket Conneciton # MAC find WiFi", "__init__(self): # Robot State values that will be bounced with", "client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def cam_client_thread(self, conn): data = conn.recv(1024)", "IP - ipconfig getifaddr en0 HOST = '192.168.1.29' # Port", "> 1023) PORT = 65432 self.ThreadCount = 0 print('Connected') #", "import socket from _thread import * import os import numpy", "e: print(str(e)) print('Waiting for connection[s]...') self.s.listen() self.start = 0 #", "def step(self): self.main_client_thread(self.conn1) self.cam_client_thread(self.conn2) if __name__ == '__main__': # Construct", "with client self.robot_state = None self.pos = None self.message =", "self.message = np.array(12345, dtype=np.float32) # Socket Conneciton # MAC find", "0 print('Connected') # Set up Socket self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)", "Conneciton # MAC find WiFi IP - ipconfig getifaddr en0", "def cam_client_thread(self, conn): data = conn.recv(1024) print('Cam client says: {}'.format(data.decode('utf-8')))", "print('Waiting for connection[s]...') self.s.listen() self.start = 0 # Wait for", "(non-privileged ports are > 1023) PORT = 65432 self.ThreadCount =", "Port to listen on (non-privileged ports are > 1023) PORT", "WiFi IP - ipconfig getifaddr en0 HOST = '192.168.1.29' #", "are > 1023) PORT = 65432 self.ThreadCount = 0 print('Connected')", "client[s] to join socket self.conn1, addr1 = self.s.accept() print('Connected by:", "import pandas as pd import math as m import time", "'192.168.1.29' # Port to listen on (non-privileged ports are >", "to join socket self.conn1, addr1 = self.s.accept() print('Connected by: ',", "conn.sendall(str.encode('Hi')) def step(self): self.main_client_thread(self.conn1) self.cam_client_thread(self.conn2) if __name__ == '__main__': #", "{}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def cam_client_thread(self, conn): data = conn.recv(1024) print('Cam client", "# Port to listen on (non-privileged ports are > 1023)", "', addr2) start_new_thread(self.cam_client_thread, (self.conn2, )) def main_client_thread(self, conn): data =", "(self.conn2, )) def main_client_thread(self, conn): data = conn.recv(1024) print('Main client", "* import os import numpy as np import pandas as", "= None self.message = np.array(12345, dtype=np.float32) # Socket Conneciton #", "MAIN SERVER object env = NetEnv() # WALK for i", "en0 HOST = '192.168.1.29' # Port to listen on (non-privileged", "self.s.accept() print('Connected by: ', addr1) start_new_thread(self.main_client_thread, (self.conn1, )) self.conn2, addr2", "{}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def step(self): self.main_client_thread(self.conn1) self.cam_client_thread(self.conn2) if __name__ == '__main__':", "random class NetEnv(gym.Env): def __init__(self): # Robot State values that", "- ipconfig getifaddr en0 HOST = '192.168.1.29' # Port to", "join socket self.conn1, addr1 = self.s.accept() print('Connected by: ', addr1)", "be bounced with client self.robot_state = None self.pos = None", "sys import socket from _thread import * import os import", "_thread import * import os import numpy as np import", "def __init__(self): # Robot State values that will be bounced", "cam_client_thread(self, conn): data = conn.recv(1024) print('Cam client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi'))", "0 # Wait for client[s] to join socket self.conn1, addr1", "print('Main client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def cam_client_thread(self, conn): data =", "by: ', addr1) start_new_thread(self.main_client_thread, (self.conn1, )) self.conn2, addr2 = self.s.accept()", "# Construct MAIN SERVER object env = NetEnv() # WALK", "env = NetEnv() # WALK for i in range(100000): env.step()", "Robot State values that will be bounced with client self.robot_state", "m import time import random class NetEnv(gym.Env): def __init__(self): #", "NetEnv(gym.Env): def __init__(self): # Robot State values that will be", "1023) PORT = 65432 self.ThreadCount = 0 print('Connected') # Set", "= socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.s.bind((HOST, PORT)) except socket.error as e:", "start_new_thread(self.main_client_thread, (self.conn1, )) self.conn2, addr2 = self.s.accept() print('Connected by: ',", "class NetEnv(gym.Env): def __init__(self): # Robot State values that will", "start_new_thread(self.cam_client_thread, (self.conn2, )) def main_client_thread(self, conn): data = conn.recv(1024) print('Main", "import * import os import numpy as np import pandas", "# MAC find WiFi IP - ipconfig getifaddr en0 HOST", "= 0 # Wait for client[s] to join socket self.conn1,", ")) self.conn2, addr2 = self.s.accept() print('Connected by: ', addr2) start_new_thread(self.cam_client_thread,", "', addr1) start_new_thread(self.main_client_thread, (self.conn1, )) self.conn2, addr2 = self.s.accept() print('Connected", "print('Connected by: ', addr1) start_new_thread(self.main_client_thread, (self.conn1, )) self.conn2, addr2 =", "self.s.bind((HOST, PORT)) except socket.error as e: print(str(e)) print('Waiting for connection[s]...')", "math as m import time import random class NetEnv(gym.Env): def", "ports are > 1023) PORT = 65432 self.ThreadCount = 0", "conn.sendall(str.encode('Hi')) def cam_client_thread(self, conn): data = conn.recv(1024) print('Cam client says:", "SERVER object env = NetEnv() # WALK for i in", "State values that will be bounced with client self.robot_state =", "import gym.spaces as spaces import sys import socket from _thread", "print('Connected') # Set up Socket self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try:", "object env = NetEnv() # WALK for i in range(100000):", "MAC find WiFi IP - ipconfig getifaddr en0 HOST =", "gym.spaces as spaces import sys import socket from _thread import", "PORT = 65432 self.ThreadCount = 0 print('Connected') # Set up", "conn): data = conn.recv(1024) print('Cam client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def", "spaces import sys import socket from _thread import * import", "if __name__ == '__main__': # Construct MAIN SERVER object env", "except socket.error as e: print(str(e)) print('Waiting for connection[s]...') self.s.listen() self.start", "as e: print(str(e)) print('Waiting for connection[s]...') self.s.listen() self.start = 0", "main_client_thread(self, conn): data = conn.recv(1024) print('Main client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi'))", "from _thread import * import os import numpy as np", "numpy as np import pandas as pd import math as", "addr2 = self.s.accept() print('Connected by: ', addr2) start_new_thread(self.cam_client_thread, (self.conn2, ))", "# Socket Conneciton # MAC find WiFi IP - ipconfig", "= self.s.accept() print('Connected by: ', addr2) start_new_thread(self.cam_client_thread, (self.conn2, )) def", "find WiFi IP - ipconfig getifaddr en0 HOST = '192.168.1.29'", "pandas as pd import math as m import time import", "socket.error as e: print(str(e)) print('Waiting for connection[s]...') self.s.listen() self.start =", "Socket Conneciton # MAC find WiFi IP - ipconfig getifaddr", "dtype=np.float32) # Socket Conneciton # MAC find WiFi IP -", "np.array(12345, dtype=np.float32) # Socket Conneciton # MAC find WiFi IP", "== '__main__': # Construct MAIN SERVER object env = NetEnv()", "= conn.recv(1024) print('Cam client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def step(self): self.main_client_thread(self.conn1)", "that will be bounced with client self.robot_state = None self.pos", "step(self): self.main_client_thread(self.conn1) self.cam_client_thread(self.conn2) if __name__ == '__main__': # Construct MAIN", "says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def step(self): self.main_client_thread(self.conn1) self.cam_client_thread(self.conn2) if __name__ ==", "addr2) start_new_thread(self.cam_client_thread, (self.conn2, )) def main_client_thread(self, conn): data = conn.recv(1024)", "= NetEnv() # WALK for i in range(100000): env.step() print('Done')", "self.robot_state = None self.pos = None self.message = np.array(12345, dtype=np.float32)", "self.s.listen() self.start = 0 # Wait for client[s] to join", "import os import numpy as np import pandas as pd", "self.ThreadCount = 0 print('Connected') # Set up Socket self.s =", "values that will be bounced with client self.robot_state = None", "= 0 print('Connected') # Set up Socket self.s = socket.socket(socket.AF_INET,", "data = conn.recv(1024) print('Cam client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def step(self):", "as np import pandas as pd import math as m", "Socket self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.s.bind((HOST, PORT)) except socket.error", "client self.robot_state = None self.pos = None self.message = np.array(12345,", "connection[s]...') self.s.listen() self.start = 0 # Wait for client[s] to", "client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def step(self): self.main_client_thread(self.conn1) self.cam_client_thread(self.conn2) if __name__", "import sys import socket from _thread import * import os", "self.cam_client_thread(self.conn2) if __name__ == '__main__': # Construct MAIN SERVER object", "self.s.accept() print('Connected by: ', addr2) start_new_thread(self.cam_client_thread, (self.conn2, )) def main_client_thread(self,", "bounced with client self.robot_state = None self.pos = None self.message", ")) def main_client_thread(self, conn): data = conn.recv(1024) print('Main client says:", "addr1 = self.s.accept() print('Connected by: ', addr1) start_new_thread(self.main_client_thread, (self.conn1, ))", "conn.recv(1024) print('Cam client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def step(self): self.main_client_thread(self.conn1) self.cam_client_thread(self.conn2)", "(self.conn1, )) self.conn2, addr2 = self.s.accept() print('Connected by: ', addr2)", "socket from _thread import * import os import numpy as", "# Wait for client[s] to join socket self.conn1, addr1 =", "ipconfig getifaddr en0 HOST = '192.168.1.29' # Port to listen", "by: ', addr2) start_new_thread(self.cam_client_thread, (self.conn2, )) def main_client_thread(self, conn): data", "HOST = '192.168.1.29' # Port to listen on (non-privileged ports", "pd import math as m import time import random class", "= '192.168.1.29' # Port to listen on (non-privileged ports are", "None self.pos = None self.message = np.array(12345, dtype=np.float32) # Socket", "socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.s.bind((HOST, PORT)) except socket.error as e: print(str(e))", "says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def cam_client_thread(self, conn): data = conn.recv(1024) print('Cam", "'__main__': # Construct MAIN SERVER object env = NetEnv() #", "os import numpy as np import pandas as pd import", "up Socket self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.s.bind((HOST, PORT)) except", "for client[s] to join socket self.conn1, addr1 = self.s.accept() print('Connected", "will be bounced with client self.robot_state = None self.pos =", "try: self.s.bind((HOST, PORT)) except socket.error as e: print(str(e)) print('Waiting for", "Set up Socket self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.s.bind((HOST, PORT))", "self.pos = None self.message = np.array(12345, dtype=np.float32) # Socket Conneciton", "self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.s.bind((HOST, PORT)) except socket.error as", "# Set up Socket self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.s.bind((HOST,", "= None self.pos = None self.message = np.array(12345, dtype=np.float32) #", "listen on (non-privileged ports are > 1023) PORT = 65432", "import random class NetEnv(gym.Env): def __init__(self): # Robot State values", "self.start = 0 # Wait for client[s] to join socket", "Wait for client[s] to join socket self.conn1, addr1 = self.s.accept()", "for connection[s]...') self.s.listen() self.start = 0 # Wait for client[s]", "on (non-privileged ports are > 1023) PORT = 65432 self.ThreadCount", "socket.SOCK_STREAM) try: self.s.bind((HOST, PORT)) except socket.error as e: print(str(e)) print('Waiting", "# Robot State values that will be bounced with client", "= conn.recv(1024) print('Main client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def cam_client_thread(self, conn):", "np import pandas as pd import math as m import", "data = conn.recv(1024) print('Main client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def cam_client_thread(self,", "Construct MAIN SERVER object env = NetEnv() # WALK for", "gym import gym.spaces as spaces import sys import socket from", "getifaddr en0 HOST = '192.168.1.29' # Port to listen on", "conn.recv(1024) print('Main client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def cam_client_thread(self, conn): data", "import gym import gym.spaces as spaces import sys import socket", "import time import random class NetEnv(gym.Env): def __init__(self): # Robot", "socket self.conn1, addr1 = self.s.accept() print('Connected by: ', addr1) start_new_thread(self.main_client_thread,", "self.conn1, addr1 = self.s.accept() print('Connected by: ', addr1) start_new_thread(self.main_client_thread, (self.conn1,", "None self.message = np.array(12345, dtype=np.float32) # Socket Conneciton # MAC", "65432 self.ThreadCount = 0 print('Connected') # Set up Socket self.s", "time import random class NetEnv(gym.Env): def __init__(self): # Robot State", "self.main_client_thread(self.conn1) self.cam_client_thread(self.conn2) if __name__ == '__main__': # Construct MAIN SERVER", "to listen on (non-privileged ports are > 1023) PORT =", "PORT)) except socket.error as e: print(str(e)) print('Waiting for connection[s]...') self.s.listen()", "import math as m import time import random class NetEnv(gym.Env):", "print('Connected by: ', addr2) start_new_thread(self.cam_client_thread, (self.conn2, )) def main_client_thread(self, conn):", "self.conn2, addr2 = self.s.accept() print('Connected by: ', addr2) start_new_thread(self.cam_client_thread, (self.conn2,", "def main_client_thread(self, conn): data = conn.recv(1024) print('Main client says: {}'.format(data.decode('utf-8')))", "conn): data = conn.recv(1024) print('Main client says: {}'.format(data.decode('utf-8'))) conn.sendall(str.encode('Hi')) def", "addr1) start_new_thread(self.main_client_thread, (self.conn1, )) self.conn2, addr2 = self.s.accept() print('Connected by:", "import numpy as np import pandas as pd import math", "as m import time import random class NetEnv(gym.Env): def __init__(self):", "as spaces import sys import socket from _thread import *", "print(str(e)) print('Waiting for connection[s]...') self.s.listen() self.start = 0 # Wait", "= 65432 self.ThreadCount = 0 print('Connected') # Set up Socket", "as pd import math as m import time import random", "__name__ == '__main__': # Construct MAIN SERVER object env =", "= self.s.accept() print('Connected by: ', addr1) start_new_thread(self.main_client_thread, (self.conn1, )) self.conn2," ]
[ "参考: https://www.osgeo.cn/sqlalchemy/orm/session_basics.html https://landybird.github.io/python/2020/03/02/fastapi%E4%B8%8Easgi(5)/ 处理session的不同方法 https://github.com/tiangolo/fastapi/issues/726 处理数据库session的方法 1. sqlalchemy.orm 自带的 scoped_session", "https://www.osgeo.cn/sqlalchemy/orm/session_basics.html https://landybird.github.io/python/2020/03/02/fastapi%E4%B8%8Easgi(5)/ 处理session的不同方法 https://github.com/tiangolo/fastapi/issues/726 处理数据库session的方法 1. sqlalchemy.orm 自带的 scoped_session 2.", "处理数据库session的方法 1. sqlalchemy.orm 自带的 scoped_session 2. 采用中间件的方法,每个请求建立一个 db 连接 3.", "# 为了保证线程安全,需使用scoped_session方法 # db_session = scoped_session( # sessionmaker(autocommit=False, autoflush=False, bind=engine)", "# db_session = scoped_session( # sessionmaker(autocommit=False, autoflush=False, bind=engine) # )", "import scoped_session from sqlalchemy.orm import sessionmaker from app.core.config import settings", "@Time : 2021/1/3 9:12 下午 # @Desc : from sqlalchemy", "# -*- coding: utf-8 -*- # @File : session.py #", "db_session = scoped_session( # sessionmaker(autocommit=False, autoflush=False, bind=engine) # ) SessionLocal", "zhkuo # @Time : 2021/1/3 9:12 下午 # @Desc :", "from sqlalchemy import create_engine # from sqlalchemy.orm import scoped_session from", "自带的 scoped_session 2. 采用中间件的方法,每个请求建立一个 db 连接 3. dependency 依赖的方法(官方文档推荐方法) \"\"\"", "sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker from app.core.config import", "3. dependency 依赖的方法(官方文档推荐方法) \"\"\" # 创建连接数据库的 engine engine = create_engine(settings.SQLALCHEMY_DATABASE_URI,", "sessionmaker from app.core.config import settings \"\"\" 参考: https://www.osgeo.cn/sqlalchemy/orm/session_basics.html https://landybird.github.io/python/2020/03/02/fastapi%E4%B8%8Easgi(5)/ 处理session的不同方法", "为了保证线程安全,需使用scoped_session方法 # db_session = scoped_session( # sessionmaker(autocommit=False, autoflush=False, bind=engine) #", "# sessionmaker(autocommit=False, autoflush=False, bind=engine) # ) SessionLocal = sessionmaker(autocommit=False, autoflush=False,", "from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker from app.core.config", "sqlalchemy.orm import sessionmaker from app.core.config import settings \"\"\" 参考: https://www.osgeo.cn/sqlalchemy/orm/session_basics.html", "dependency 依赖的方法(官方文档推荐方法) \"\"\" # 创建连接数据库的 engine engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, connect_args={\"check_same_thread\":", "依赖的方法(官方文档推荐方法) \"\"\" # 创建连接数据库的 engine engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, connect_args={\"check_same_thread\": False})", "connect_args={\"check_same_thread\": False}) # 为了保证线程安全,需使用scoped_session方法 # db_session = scoped_session( # sessionmaker(autocommit=False,", "False}) # 为了保证线程安全,需使用scoped_session方法 # db_session = scoped_session( # sessionmaker(autocommit=False, autoflush=False,", "app.core.config import settings \"\"\" 参考: https://www.osgeo.cn/sqlalchemy/orm/session_basics.html https://landybird.github.io/python/2020/03/02/fastapi%E4%B8%8Easgi(5)/ 处理session的不同方法 https://github.com/tiangolo/fastapi/issues/726 处理数据库session的方法", "1. sqlalchemy.orm 自带的 scoped_session 2. 采用中间件的方法,每个请求建立一个 db 连接 3. dependency", "@Desc : from sqlalchemy import create_engine # from sqlalchemy.orm import", "2021/1/3 9:12 下午 # @Desc : from sqlalchemy import create_engine", "@File : session.py # @Author : zhkuo # @Time :", "\"\"\" 参考: https://www.osgeo.cn/sqlalchemy/orm/session_basics.html https://landybird.github.io/python/2020/03/02/fastapi%E4%B8%8Easgi(5)/ 处理session的不同方法 https://github.com/tiangolo/fastapi/issues/726 处理数据库session的方法 1. sqlalchemy.orm 自带的", "2. 采用中间件的方法,每个请求建立一个 db 连接 3. dependency 依赖的方法(官方文档推荐方法) \"\"\" # 创建连接数据库的", "create_engine(settings.SQLALCHEMY_DATABASE_URI, connect_args={\"check_same_thread\": False}) # 为了保证线程安全,需使用scoped_session方法 # db_session = scoped_session( #", "create_engine # from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker", "-*- # @File : session.py # @Author : zhkuo #", "sqlalchemy.orm 自带的 scoped_session 2. 采用中间件的方法,每个请求建立一个 db 连接 3. dependency 依赖的方法(官方文档推荐方法)", "db 连接 3. dependency 依赖的方法(官方文档推荐方法) \"\"\" # 创建连接数据库的 engine engine", "\"\"\" # 创建连接数据库的 engine engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, connect_args={\"check_same_thread\": False}) #", "engine engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, connect_args={\"check_same_thread\": False}) # 为了保证线程安全,需使用scoped_session方法 # db_session", "sessionmaker(autocommit=False, autoflush=False, bind=engine) # ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)", "settings \"\"\" 参考: https://www.osgeo.cn/sqlalchemy/orm/session_basics.html https://landybird.github.io/python/2020/03/02/fastapi%E4%B8%8Easgi(5)/ 处理session的不同方法 https://github.com/tiangolo/fastapi/issues/726 处理数据库session的方法 1. sqlalchemy.orm", "https://github.com/tiangolo/fastapi/issues/726 处理数据库session的方法 1. sqlalchemy.orm 自带的 scoped_session 2. 采用中间件的方法,每个请求建立一个 db 连接", "连接 3. dependency 依赖的方法(官方文档推荐方法) \"\"\" # 创建连接数据库的 engine engine =", "处理session的不同方法 https://github.com/tiangolo/fastapi/issues/726 处理数据库session的方法 1. sqlalchemy.orm 自带的 scoped_session 2. 采用中间件的方法,每个请求建立一个 db", "采用中间件的方法,每个请求建立一个 db 连接 3. dependency 依赖的方法(官方文档推荐方法) \"\"\" # 创建连接数据库的 engine", "# @Time : 2021/1/3 9:12 下午 # @Desc : from", "@Author : zhkuo # @Time : 2021/1/3 9:12 下午 #", "9:12 下午 # @Desc : from sqlalchemy import create_engine #", "import sessionmaker from app.core.config import settings \"\"\" 参考: https://www.osgeo.cn/sqlalchemy/orm/session_basics.html https://landybird.github.io/python/2020/03/02/fastapi%E4%B8%8Easgi(5)/", "= scoped_session( # sessionmaker(autocommit=False, autoflush=False, bind=engine) # ) SessionLocal =", ": session.py # @Author : zhkuo # @Time : 2021/1/3", "utf-8 -*- # @File : session.py # @Author : zhkuo", "# @Author : zhkuo # @Time : 2021/1/3 9:12 下午", "# @File : session.py # @Author : zhkuo # @Time", "import settings \"\"\" 参考: https://www.osgeo.cn/sqlalchemy/orm/session_basics.html https://landybird.github.io/python/2020/03/02/fastapi%E4%B8%8Easgi(5)/ 处理session的不同方法 https://github.com/tiangolo/fastapi/issues/726 处理数据库session的方法 1.", "from sqlalchemy.orm import sessionmaker from app.core.config import settings \"\"\" 参考:", "sqlalchemy import create_engine # from sqlalchemy.orm import scoped_session from sqlalchemy.orm", "= create_engine(settings.SQLALCHEMY_DATABASE_URI, connect_args={\"check_same_thread\": False}) # 为了保证线程安全,需使用scoped_session方法 # db_session = scoped_session(", "下午 # @Desc : from sqlalchemy import create_engine # from", "scoped_session( # sessionmaker(autocommit=False, autoflush=False, bind=engine) # ) SessionLocal = sessionmaker(autocommit=False,", ": 2021/1/3 9:12 下午 # @Desc : from sqlalchemy import", "coding: utf-8 -*- # @File : session.py # @Author :", "https://landybird.github.io/python/2020/03/02/fastapi%E4%B8%8Easgi(5)/ 处理session的不同方法 https://github.com/tiangolo/fastapi/issues/726 处理数据库session的方法 1. sqlalchemy.orm 自带的 scoped_session 2. 采用中间件的方法,每个请求建立一个", "# 创建连接数据库的 engine engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, connect_args={\"check_same_thread\": False}) # 为了保证线程安全,需使用scoped_session方法", "engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, connect_args={\"check_same_thread\": False}) # 为了保证线程安全,需使用scoped_session方法 # db_session =", "<reponame>zhkuo24/full-stack-fastapi-demo<gh_stars>1-10 # -*- coding: utf-8 -*- # @File : session.py", "创建连接数据库的 engine engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, connect_args={\"check_same_thread\": False}) # 为了保证线程安全,需使用scoped_session方法 #", "scoped_session 2. 采用中间件的方法,每个请求建立一个 db 连接 3. dependency 依赖的方法(官方文档推荐方法) \"\"\" #", "import create_engine # from sqlalchemy.orm import scoped_session from sqlalchemy.orm import", "-*- coding: utf-8 -*- # @File : session.py # @Author", "# from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker from", "session.py # @Author : zhkuo # @Time : 2021/1/3 9:12", ": zhkuo # @Time : 2021/1/3 9:12 下午 # @Desc", ": from sqlalchemy import create_engine # from sqlalchemy.orm import scoped_session", "scoped_session from sqlalchemy.orm import sessionmaker from app.core.config import settings \"\"\"", "from app.core.config import settings \"\"\" 参考: https://www.osgeo.cn/sqlalchemy/orm/session_basics.html https://landybird.github.io/python/2020/03/02/fastapi%E4%B8%8Easgi(5)/ 处理session的不同方法 https://github.com/tiangolo/fastapi/issues/726", "# @Desc : from sqlalchemy import create_engine # from sqlalchemy.orm" ]
[ "- initialdir: str, default Path.cwd() - multiple: bool, default False", "'': # canceled return None with Path(fn).open(mode) as f: data", "---------- Options will be passed to `tkinter.filedialog.askopenfilename`. See also tkinter's", "with a filename assigned by tkinter's open dialog. kwargs will", "Options will be passed to `tkinter.filedialog.asksaveasfilename`. See also tkinter's document.", "Options will be passed to `tkinter.filedialog.askopenfilename`. See also tkinter's document.", "dialog. kwargs will be passed to saveas_dialog. \"\"\" opt_default =", "= open_dialog(**_opt) if fn == '': # canceled return None", "tkinter's document. Followings are example of frequently used options. -", "a filename assigned by tkinter's open dialog. kwargs will be", "dict(filetypes=[('pickled data', '*.pkl'), ('all', '*')]) _opt = dict(opt_default, **opt) fn", "saveas_dialog. \"\"\" opt_default = dict(filetypes=[('pickled data', '*.pkl'), ('all', '*')]) _opt", "extentions - initialdir: str, default Path.cwd() - initialfile: str, default", "**opt) fn = open_dialog(**_opt) if fn == '': # canceled", "'' # note: 上書き確認はtkinterがやってくれるのでここではチェックしない with Path(fn).open(mode) as f: pickle.dump(obj, f)", "def open_dialog(**opt): \"\"\"Parameters ---------- Options will be passed to `tkinter.filedialog.askopenfilename`.", "default Path.cwd() - initialfile: str, default isn't set Returns --------", "See also tkinter's document. Followings are example of frequently used", "tkinter's saveas dialog. kwargs will be passed to saveas_dialog. Returns", "\"\"\"Parameters ---------- Options will be passed to `tkinter.filedialog.askopenfilename`. See also", "as f: data = pickle.load(f) return data def dump_pickle_with_dialog(obj, mode='wb',", "'*.pkl'), ('all', '*')]) _opt = dict(opt_default, **opt) fn = open_dialog(**_opt)", "tkinter.filedialog def open_dialog(**opt): \"\"\"Parameters ---------- Options will be passed to", "= dict(initialdir=Path.cwd()) _opt = dict(opt_default, **opt) return tk.filedialog.askopenfilename(**_opt) def saveas_dialog(**opt):", "multiple: bool, default False Returns -------- filename, str \"\"\" root", "passed to saveas_dialog. Returns -------- filename: str \"\"\" opt_default =", "of frequently used options. - filetypes=[(label, ext), ...] - label:", "return None with Path(fn).open(mode) as f: data = pickle.load(f) return", "Returns -------- filename: str \"\"\" opt_default = dict(filetypes=[('pickled data', '*.pkl'),", "= dict(opt_default, **opt) return tk.filedialog.asksaveasfilename(**_opt) def load_pickle_with_dialog(mode='rb', **opt): \"\"\"Load a", "return tk.filedialog.asksaveasfilename(**_opt) def load_pickle_with_dialog(mode='rb', **opt): \"\"\"Load a pickled object with", "True) opt_default = dict(initialdir=Path.cwd()) _opt = dict(opt_default, **opt) return tk.filedialog.asksaveasfilename(**_opt)", "object with a filename assigned by tkinter's saveas dialog. kwargs", "<reponame>KosukeMizuno/tkdialog from pathlib import Path import pickle import tkinter as", "- multiple: bool, default False Returns -------- filename, str \"\"\"", "Path.cwd() - multiple: bool, default False Returns -------- filename, str", "-------- filename: str \"\"\" opt_default = dict(filetypes=[('pickled data', '*.pkl'), ('all',", "will be passed to `tkinter.filedialog.asksaveasfilename`. See also tkinter's document. Followings", "if fn == '': # canceled return None with Path(fn).open(mode)", "passed to `tkinter.filedialog.askopenfilename`. See also tkinter's document. Followings are example", "frequently used options. - filetypes=[(label, ext), ...] - label: str", "will be passed to saveas_dialog. Returns -------- filename: str \"\"\"", "will be passed to `tkinter.filedialog.askopenfilename`. See also tkinter's document. Followings", "'*')]) _opt = dict(opt_default, **opt) fn = saveas_dialog(**_opt) if fn", "label: str - ext: str, semicolon separated extentions - initialdir:", "kwargs will be passed to saveas_dialog. Returns -------- filename: str", "isn't set Returns -------- filename, str \"\"\" root = tk.Tk()", "to saveas_dialog. \"\"\" opt_default = dict(filetypes=[('pickled data', '*.pkl'), ('all', '*')])", "True) opt_default = dict(initialdir=Path.cwd()) _opt = dict(opt_default, **opt) return tk.filedialog.askopenfilename(**_opt)", "dict(initialdir=Path.cwd()) _opt = dict(opt_default, **opt) return tk.filedialog.asksaveasfilename(**_opt) def load_pickle_with_dialog(mode='rb', **opt):", "data', '*.pkl'), ('all', '*')]) _opt = dict(opt_default, **opt) fn =", "def load_pickle_with_dialog(mode='rb', **opt): \"\"\"Load a pickled object with a filename", "also tkinter's document. Followings are example of frequently used options.", "('all', '*')]) _opt = dict(opt_default, **opt) fn = open_dialog(**_opt) if", "an object with a filename assigned by tkinter's saveas dialog.", "pathlib import Path import pickle import tkinter as tk import", "'*')]) _opt = dict(opt_default, **opt) fn = open_dialog(**_opt) if fn", "to `tkinter.filedialog.asksaveasfilename`. See also tkinter's document. Followings are example of", "**opt) fn = saveas_dialog(**_opt) if fn == '': # canceled", "import tkinter.filedialog def open_dialog(**opt): \"\"\"Parameters ---------- Options will be passed", "= saveas_dialog(**_opt) if fn == '': # canceled return ''", "str, default isn't set Returns -------- filename, str \"\"\" root", "import Path import pickle import tkinter as tk import tkinter.filedialog", "a pickled object with a filename assigned by tkinter's open", "by tkinter's saveas dialog. kwargs will be passed to saveas_dialog.", "mode='wb', **opt): \"\"\"Pickle an object with a filename assigned by", "str, default Path.cwd() - multiple: bool, default False Returns --------", "_opt = dict(opt_default, **opt) return tk.filedialog.asksaveasfilename(**_opt) def load_pickle_with_dialog(mode='rb', **opt): \"\"\"Load", "document. Followings are example of frequently used options. - filetypes=[(label,", "kwargs will be passed to saveas_dialog. \"\"\" opt_default = dict(filetypes=[('pickled", "dialog. kwargs will be passed to saveas_dialog. Returns -------- filename:", "example of frequently used options. - filetypes=[(label, ext), ...] -", "pickled object with a filename assigned by tkinter's open dialog.", "tkinter as tk import tkinter.filedialog def open_dialog(**opt): \"\"\"Parameters ---------- Options", "filetypes=[(label, ext), ...] - label: str - ext: str, semicolon", "be passed to saveas_dialog. Returns -------- filename: str \"\"\" opt_default", "filename, str \"\"\" root = tk.Tk() root.withdraw() root.wm_attributes(\"-topmost\", True) opt_default", "semicolon separated extentions - initialdir: str, default Path.cwd() - multiple:", "to `tkinter.filedialog.askopenfilename`. See also tkinter's document. Followings are example of", "`tkinter.filedialog.asksaveasfilename`. See also tkinter's document. Followings are example of frequently", "fn = open_dialog(**_opt) if fn == '': # canceled return", "open_dialog(**_opt) if fn == '': # canceled return None with", "pickle import tkinter as tk import tkinter.filedialog def open_dialog(**opt): \"\"\"Parameters", "---------- Options will be passed to `tkinter.filedialog.asksaveasfilename`. See also tkinter's", "pickle.load(f) return data def dump_pickle_with_dialog(obj, mode='wb', **opt): \"\"\"Pickle an object", "saveas dialog. kwargs will be passed to saveas_dialog. Returns --------", "with a filename assigned by tkinter's saveas dialog. kwargs will", "saveas_dialog. Returns -------- filename: str \"\"\" opt_default = dict(filetypes=[('pickled data',", "canceled return None with Path(fn).open(mode) as f: data = pickle.load(f)", "\"\"\"Load a pickled object with a filename assigned by tkinter's", "None with Path(fn).open(mode) as f: data = pickle.load(f) return data", "default False Returns -------- filename, str \"\"\" root = tk.Tk()", "assigned by tkinter's saveas dialog. kwargs will be passed to", "return data def dump_pickle_with_dialog(obj, mode='wb', **opt): \"\"\"Pickle an object with", "semicolon separated extentions - initialdir: str, default Path.cwd() - initialfile:", "- initialfile: str, default isn't set Returns -------- filename, str", "'*.pkl'), ('all', '*')]) _opt = dict(opt_default, **opt) fn = saveas_dialog(**_opt)", "by tkinter's open dialog. kwargs will be passed to saveas_dialog.", "ext), ...] - label: str - ext: str, semicolon separated", "fn == '': # canceled return '' # note: 上書き確認はtkinterがやってくれるのでここではチェックしない", "note: 上書き確認はtkinterがやってくれるのでここではチェックしない with Path(fn).open(mode) as f: pickle.dump(obj, f) return fn", "be passed to `tkinter.filedialog.asksaveasfilename`. See also tkinter's document. Followings are", "opt_default = dict(filetypes=[('pickled data', '*.pkl'), ('all', '*')]) _opt = dict(opt_default,", "saveas_dialog(**opt): \"\"\"Parameters ---------- Options will be passed to `tkinter.filedialog.asksaveasfilename`. See", "False Returns -------- filename, str \"\"\" root = tk.Tk() root.withdraw()", "= dict(filetypes=[('pickled data', '*.pkl'), ('all', '*')]) _opt = dict(opt_default, **opt)", "return tk.filedialog.askopenfilename(**_opt) def saveas_dialog(**opt): \"\"\"Parameters ---------- Options will be passed", "open dialog. kwargs will be passed to saveas_dialog. \"\"\" opt_default", "- initialdir: str, default Path.cwd() - initialfile: str, default isn't", "_opt = dict(opt_default, **opt) fn = saveas_dialog(**_opt) if fn ==", "import pickle import tkinter as tk import tkinter.filedialog def open_dialog(**opt):", "str, semicolon separated extentions - initialdir: str, default Path.cwd() -", "Path.cwd() - initialfile: str, default isn't set Returns -------- filename,", "Returns -------- filename, str \"\"\" root = tk.Tk() root.withdraw() root.wm_attributes(\"-topmost\",", "Path import pickle import tkinter as tk import tkinter.filedialog def", "str, default Path.cwd() - initialfile: str, default isn't set Returns", "\"\"\" opt_default = dict(filetypes=[('pickled data', '*.pkl'), ('all', '*')]) _opt =", "filename assigned by tkinter's open dialog. kwargs will be passed", "canceled return '' # note: 上書き確認はtkinterがやってくれるのでここではチェックしない with Path(fn).open(mode) as f:", "separated extentions - initialdir: str, default Path.cwd() - multiple: bool,", "filename: str \"\"\" opt_default = dict(filetypes=[('pickled data', '*.pkl'), ('all', '*')])", "object with a filename assigned by tkinter's open dialog. kwargs", "# canceled return '' # note: 上書き確認はtkinterがやってくれるのでここではチェックしない with Path(fn).open(mode) as", "will be passed to saveas_dialog. \"\"\" opt_default = dict(filetypes=[('pickled data',", "== '': # canceled return '' # note: 上書き確認はtkinterがやってくれるのでここではチェックしない with", "initialfile: str, default isn't set Returns -------- filename, str \"\"\"", "default isn't set Returns -------- filename, str \"\"\" root =", "dict(opt_default, **opt) return tk.filedialog.asksaveasfilename(**_opt) def load_pickle_with_dialog(mode='rb', **opt): \"\"\"Load a pickled", "== '': # canceled return None with Path(fn).open(mode) as f:", "\"\"\" root = tk.Tk() root.withdraw() root.wm_attributes(\"-topmost\", True) opt_default = dict(initialdir=Path.cwd())", "root.wm_attributes(\"-topmost\", True) opt_default = dict(initialdir=Path.cwd()) _opt = dict(opt_default, **opt) return", "set Returns -------- filename, str \"\"\" root = tk.Tk() root.withdraw()", "with Path(fn).open(mode) as f: data = pickle.load(f) return data def", "_opt = dict(opt_default, **opt) fn = open_dialog(**_opt) if fn ==", "root.withdraw() root.wm_attributes(\"-topmost\", True) opt_default = dict(initialdir=Path.cwd()) _opt = dict(opt_default, **opt)", "\"\"\"Parameters ---------- Options will be passed to `tkinter.filedialog.asksaveasfilename`. See also", "as tk import tkinter.filedialog def open_dialog(**opt): \"\"\"Parameters ---------- Options will", "root = tk.Tk() root.withdraw() root.wm_attributes(\"-topmost\", True) opt_default = dict(initialdir=Path.cwd()) _opt", "initialdir: str, default Path.cwd() - initialfile: str, default isn't set", "opt_default = dict(initialdir=Path.cwd()) _opt = dict(opt_default, **opt) return tk.filedialog.askopenfilename(**_opt) def", "def saveas_dialog(**opt): \"\"\"Parameters ---------- Options will be passed to `tkinter.filedialog.asksaveasfilename`.", "tk.filedialog.asksaveasfilename(**_opt) def load_pickle_with_dialog(mode='rb', **opt): \"\"\"Load a pickled object with a", "= dict(opt_default, **opt) fn = open_dialog(**_opt) if fn == '':", "data = pickle.load(f) return data def dump_pickle_with_dialog(obj, mode='wb', **opt): \"\"\"Pickle", "dump_pickle_with_dialog(obj, mode='wb', **opt): \"\"\"Pickle an object with a filename assigned", "fn = saveas_dialog(**_opt) if fn == '': # canceled return", "dict(initialdir=Path.cwd()) _opt = dict(opt_default, **opt) return tk.filedialog.askopenfilename(**_opt) def saveas_dialog(**opt): \"\"\"Parameters", "initialdir: str, default Path.cwd() - multiple: bool, default False Returns", "opt_default = dict(initialdir=Path.cwd()) _opt = dict(opt_default, **opt) return tk.filedialog.asksaveasfilename(**_opt) def", "# note: 上書き確認はtkinterがやってくれるのでここではチェックしない with Path(fn).open(mode) as f: pickle.dump(obj, f) return", "fn == '': # canceled return None with Path(fn).open(mode) as", "str - ext: str, semicolon separated extentions - initialdir: str,", "used options. - filetypes=[(label, ext), ...] - label: str -", "def dump_pickle_with_dialog(obj, mode='wb', **opt): \"\"\"Pickle an object with a filename", "**opt) return tk.filedialog.askopenfilename(**_opt) def saveas_dialog(**opt): \"\"\"Parameters ---------- Options will be", "dict(opt_default, **opt) fn = saveas_dialog(**_opt) if fn == '': #", "dict(opt_default, **opt) fn = open_dialog(**_opt) if fn == '': #", "\"\"\"Pickle an object with a filename assigned by tkinter's saveas", "tk.filedialog.askopenfilename(**_opt) def saveas_dialog(**opt): \"\"\"Parameters ---------- Options will be passed to", "tkinter's open dialog. kwargs will be passed to saveas_dialog. \"\"\"", "extentions - initialdir: str, default Path.cwd() - multiple: bool, default", "return '' # note: 上書き確認はtkinterがやってくれるのでここではチェックしない with Path(fn).open(mode) as f: pickle.dump(obj,", "= dict(initialdir=Path.cwd()) _opt = dict(opt_default, **opt) return tk.filedialog.asksaveasfilename(**_opt) def load_pickle_with_dialog(mode='rb',", "('all', '*')]) _opt = dict(opt_default, **opt) fn = saveas_dialog(**_opt) if", "-------- filename, str \"\"\" root = tk.Tk() root.withdraw() root.wm_attributes(\"-topmost\", True)", "- filetypes=[(label, ext), ...] - label: str - ext: str,", "import tkinter as tk import tkinter.filedialog def open_dialog(**opt): \"\"\"Parameters ----------", "load_pickle_with_dialog(mode='rb', **opt): \"\"\"Load a pickled object with a filename assigned", "dict(opt_default, **opt) return tk.filedialog.askopenfilename(**_opt) def saveas_dialog(**opt): \"\"\"Parameters ---------- Options will", "assigned by tkinter's open dialog. kwargs will be passed to", "passed to saveas_dialog. \"\"\" opt_default = dict(filetypes=[('pickled data', '*.pkl'), ('all',", "**opt): \"\"\"Pickle an object with a filename assigned by tkinter's", "bool, default False Returns -------- filename, str \"\"\" root =", "passed to `tkinter.filedialog.asksaveasfilename`. See also tkinter's document. Followings are example", "data def dump_pickle_with_dialog(obj, mode='wb', **opt): \"\"\"Pickle an object with a", "tk.Tk() root.withdraw() root.wm_attributes(\"-topmost\", True) opt_default = dict(initialdir=Path.cwd()) _opt = dict(opt_default,", "to saveas_dialog. Returns -------- filename: str \"\"\" opt_default = dict(filetypes=[('pickled", "are example of frequently used options. - filetypes=[(label, ext), ...]", "= dict(opt_default, **opt) fn = saveas_dialog(**_opt) if fn == '':", "`tkinter.filedialog.askopenfilename`. See also tkinter's document. Followings are example of frequently", "= tk.Tk() root.withdraw() root.wm_attributes(\"-topmost\", True) opt_default = dict(initialdir=Path.cwd()) _opt =", "_opt = dict(opt_default, **opt) return tk.filedialog.askopenfilename(**_opt) def saveas_dialog(**opt): \"\"\"Parameters ----------", "a filename assigned by tkinter's saveas dialog. kwargs will be", "**opt) return tk.filedialog.asksaveasfilename(**_opt) def load_pickle_with_dialog(mode='rb', **opt): \"\"\"Load a pickled object", "open_dialog(**opt): \"\"\"Parameters ---------- Options will be passed to `tkinter.filedialog.askopenfilename`. See", "= pickle.load(f) return data def dump_pickle_with_dialog(obj, mode='wb', **opt): \"\"\"Pickle an", "from pathlib import Path import pickle import tkinter as tk", "'': # canceled return '' # note: 上書き確認はtkinterがやってくれるのでここではチェックしない with Path(fn).open(mode)", "be passed to `tkinter.filedialog.askopenfilename`. See also tkinter's document. Followings are", "- label: str - ext: str, semicolon separated extentions -", "separated extentions - initialdir: str, default Path.cwd() - initialfile: str,", "Path(fn).open(mode) as f: data = pickle.load(f) return data def dump_pickle_with_dialog(obj,", "filename assigned by tkinter's saveas dialog. kwargs will be passed", "str \"\"\" opt_default = dict(filetypes=[('pickled data', '*.pkl'), ('all', '*')]) _opt", "f: data = pickle.load(f) return data def dump_pickle_with_dialog(obj, mode='wb', **opt):", "default Path.cwd() - multiple: bool, default False Returns -------- filename,", "str \"\"\" root = tk.Tk() root.withdraw() root.wm_attributes(\"-topmost\", True) opt_default =", "**opt): \"\"\"Load a pickled object with a filename assigned by", "= dict(opt_default, **opt) return tk.filedialog.askopenfilename(**_opt) def saveas_dialog(**opt): \"\"\"Parameters ---------- Options", "ext: str, semicolon separated extentions - initialdir: str, default Path.cwd()", "be passed to saveas_dialog. \"\"\" opt_default = dict(filetypes=[('pickled data', '*.pkl'),", "# canceled return None with Path(fn).open(mode) as f: data =", "saveas_dialog(**_opt) if fn == '': # canceled return '' #", "tk import tkinter.filedialog def open_dialog(**opt): \"\"\"Parameters ---------- Options will be", "...] - label: str - ext: str, semicolon separated extentions", "if fn == '': # canceled return '' # note:", "- ext: str, semicolon separated extentions - initialdir: str, default", "Followings are example of frequently used options. - filetypes=[(label, ext),", "options. - filetypes=[(label, ext), ...] - label: str - ext:" ]
[ "fake_db_group_snapshot(**updates): db_group_snapshot = { 'id': fake.GROUP_SNAPSHOT_ID, 'name': 'group-1', 'status': 'available',", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "from cinder import objects from cinder.tests.unit import fake_constants as fake", "may obtain # a copy of the License at #", "'available', 'user_id': fake.USER_ID, 'project_id': fake.PROJECT_ID, 'group_type_id': fake.GROUP_TYPE_ID, 'group_id': fake.GROUP_ID, }", "{ 'id': fake.GROUP_SNAPSHOT_ID, 'name': 'group-1', 'status': 'available', 'user_id': fake.USER_ID, 'project_id':", "# # Licensed under the Apache License, Version 2.0 (the", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "'user_id': fake.USER_ID, 'project_id': fake.PROJECT_ID, 'group_type_id': fake.GROUP_TYPE_ID, 'group_id': fake.GROUP_ID, } for", "distributed under the License is distributed on an \"AS IS\"", "raise Exception('fake_db_group_snapshot needs help with %s.' % name) if updates:", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "obtain # a copy of the License at # #", "continue if field.nullable: db_group_snapshot[name] = None elif field.default != fields.UnspecifiedDefault:", "applicable law or agreed to in writing, software # distributed", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "Version 2.0 (the \"License\"); you may # not use this", "specific language governing permissions and limitations # under the License.", "db_group_snapshot[name] = field.default else: raise Exception('fake_db_group_snapshot needs help with %s.'", "2016 EMC Corporation # # Licensed under the Apache License,", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "name, field in objects.GroupSnapshot.fields.items(): if name in db_group_snapshot: continue if", "= None elif field.default != fields.UnspecifiedDefault: db_group_snapshot[name] = field.default else:", "'group_id': fake.GROUP_ID, } for name, field in objects.GroupSnapshot.fields.items(): if name", "!= fields.UnspecifiedDefault: db_group_snapshot[name] = field.default else: raise Exception('fake_db_group_snapshot needs help", "writing, software # distributed under the License is distributed on", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "field.nullable: db_group_snapshot[name] = None elif field.default != fields.UnspecifiedDefault: db_group_snapshot[name] =", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "name) if updates: db_group_snapshot.update(updates) return db_group_snapshot def fake_group_snapshot_obj(context, **updates): return", "if updates: db_group_snapshot.update(updates) return db_group_snapshot def fake_group_snapshot_obj(context, **updates): return objects.GroupSnapshot._from_db_object(", "objects.GroupSnapshot.fields.items(): if name in db_group_snapshot: continue if field.nullable: db_group_snapshot[name] =", "the License. You may obtain # a copy of the", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "You may obtain # a copy of the License at", "governing permissions and limitations # under the License. from oslo_versionedobjects", "elif field.default != fields.UnspecifiedDefault: db_group_snapshot[name] = field.default else: raise Exception('fake_db_group_snapshot", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "needs help with %s.' % name) if updates: db_group_snapshot.update(updates) return", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "} for name, field in objects.GroupSnapshot.fields.items(): if name in db_group_snapshot:", "import fake_constants as fake def fake_db_group_snapshot(**updates): db_group_snapshot = { 'id':", "from cinder.tests.unit import fake_constants as fake def fake_db_group_snapshot(**updates): db_group_snapshot =", "fake.GROUP_TYPE_ID, 'group_id': fake.GROUP_ID, } for name, field in objects.GroupSnapshot.fields.items(): if", "'id': fake.GROUP_SNAPSHOT_ID, 'name': 'group-1', 'status': 'available', 'user_id': fake.USER_ID, 'project_id': fake.PROJECT_ID,", "EMC Corporation # # Licensed under the Apache License, Version", "either express or implied. See the # License for the", "help with %s.' % name) if updates: db_group_snapshot.update(updates) return db_group_snapshot", "'group_type_id': fake.GROUP_TYPE_ID, 'group_id': fake.GROUP_ID, } for name, field in objects.GroupSnapshot.fields.items():", "under the License is distributed on an \"AS IS\" BASIS,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "import fields from cinder import objects from cinder.tests.unit import fake_constants", "updates: db_group_snapshot.update(updates) return db_group_snapshot def fake_group_snapshot_obj(context, **updates): return objects.GroupSnapshot._from_db_object( context,", "db_group_snapshot.update(updates) return db_group_snapshot def fake_group_snapshot_obj(context, **updates): return objects.GroupSnapshot._from_db_object( context, objects.GroupSnapshot(),", "may # not use this file except in compliance with", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "= { 'id': fake.GROUP_SNAPSHOT_ID, 'name': 'group-1', 'status': 'available', 'user_id': fake.USER_ID,", "from oslo_versionedobjects import fields from cinder import objects from cinder.tests.unit", "fake def fake_db_group_snapshot(**updates): db_group_snapshot = { 'id': fake.GROUP_SNAPSHOT_ID, 'name': 'group-1',", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "fake_constants as fake def fake_db_group_snapshot(**updates): db_group_snapshot = { 'id': fake.GROUP_SNAPSHOT_ID,", "you may # not use this file except in compliance", "\"License\"); you may # not use this file except in", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "# under the License. from oslo_versionedobjects import fields from cinder", "cinder.tests.unit import fake_constants as fake def fake_db_group_snapshot(**updates): db_group_snapshot = {", "express or implied. See the # License for the specific", "this file except in compliance with the License. You may", "language governing permissions and limitations # under the License. from", "permissions and limitations # under the License. from oslo_versionedobjects import", "compliance with the License. You may obtain # a copy", "%s.' % name) if updates: db_group_snapshot.update(updates) return db_group_snapshot def fake_group_snapshot_obj(context,", "the Apache License, Version 2.0 (the \"License\"); you may #", "def fake_db_group_snapshot(**updates): db_group_snapshot = { 'id': fake.GROUP_SNAPSHOT_ID, 'name': 'group-1', 'status':", "with %s.' % name) if updates: db_group_snapshot.update(updates) return db_group_snapshot def", "field in objects.GroupSnapshot.fields.items(): if name in db_group_snapshot: continue if field.nullable:", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "fake.GROUP_SNAPSHOT_ID, 'name': 'group-1', 'status': 'available', 'user_id': fake.USER_ID, 'project_id': fake.PROJECT_ID, 'group_type_id':", "Copyright 2016 EMC Corporation # # Licensed under the Apache", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "See the # License for the specific language governing permissions", "if field.nullable: db_group_snapshot[name] = None elif field.default != fields.UnspecifiedDefault: db_group_snapshot[name]", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "name in db_group_snapshot: continue if field.nullable: db_group_snapshot[name] = None elif", "# Copyright 2016 EMC Corporation # # Licensed under the", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "'status': 'available', 'user_id': fake.USER_ID, 'project_id': fake.PROJECT_ID, 'group_type_id': fake.GROUP_TYPE_ID, 'group_id': fake.GROUP_ID,", "the # License for the specific language governing permissions and", "fields.UnspecifiedDefault: db_group_snapshot[name] = field.default else: raise Exception('fake_db_group_snapshot needs help with", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "if name in db_group_snapshot: continue if field.nullable: db_group_snapshot[name] = None", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "field.default else: raise Exception('fake_db_group_snapshot needs help with %s.' % name)", "in objects.GroupSnapshot.fields.items(): if name in db_group_snapshot: continue if field.nullable: db_group_snapshot[name]", "file except in compliance with the License. You may obtain", "Exception('fake_db_group_snapshot needs help with %s.' % name) if updates: db_group_snapshot.update(updates)", "limitations # under the License. from oslo_versionedobjects import fields from", "oslo_versionedobjects import fields from cinder import objects from cinder.tests.unit import", "% name) if updates: db_group_snapshot.update(updates) return db_group_snapshot def fake_group_snapshot_obj(context, **updates):", "for the specific language governing permissions and limitations # under", "law or agreed to in writing, software # distributed under", "<filename>cinder/tests/unit/fake_group_snapshot.py # Copyright 2016 EMC Corporation # # Licensed under", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "db_group_snapshot[name] = None elif field.default != fields.UnspecifiedDefault: db_group_snapshot[name] = field.default", "field.default != fields.UnspecifiedDefault: db_group_snapshot[name] = field.default else: raise Exception('fake_db_group_snapshot needs", "in db_group_snapshot: continue if field.nullable: db_group_snapshot[name] = None elif field.default", "under the Apache License, Version 2.0 (the \"License\"); you may", "License. from oslo_versionedobjects import fields from cinder import objects from", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "None elif field.default != fields.UnspecifiedDefault: db_group_snapshot[name] = field.default else: raise", "implied. See the # License for the specific language governing", "fake.USER_ID, 'project_id': fake.PROJECT_ID, 'group_type_id': fake.GROUP_TYPE_ID, 'group_id': fake.GROUP_ID, } for name,", "return db_group_snapshot def fake_group_snapshot_obj(context, **updates): return objects.GroupSnapshot._from_db_object( context, objects.GroupSnapshot(), fake_db_group_snapshot(**updates))", "the License. from oslo_versionedobjects import fields from cinder import objects", "else: raise Exception('fake_db_group_snapshot needs help with %s.' % name) if", "db_group_snapshot: continue if field.nullable: db_group_snapshot[name] = None elif field.default !=", "under the License. from oslo_versionedobjects import fields from cinder import", "'project_id': fake.PROJECT_ID, 'group_type_id': fake.GROUP_TYPE_ID, 'group_id': fake.GROUP_ID, } for name, field", "License. You may obtain # a copy of the License", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "# Unless required by applicable law or agreed to in", "import objects from cinder.tests.unit import fake_constants as fake def fake_db_group_snapshot(**updates):", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "cinder import objects from cinder.tests.unit import fake_constants as fake def", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "'group-1', 'status': 'available', 'user_id': fake.USER_ID, 'project_id': fake.PROJECT_ID, 'group_type_id': fake.GROUP_TYPE_ID, 'group_id':", "or agreed to in writing, software # distributed under the", "= field.default else: raise Exception('fake_db_group_snapshot needs help with %s.' %", "required by applicable law or agreed to in writing, software", "objects from cinder.tests.unit import fake_constants as fake def fake_db_group_snapshot(**updates): db_group_snapshot", "Corporation # # Licensed under the Apache License, Version 2.0", "and limitations # under the License. from oslo_versionedobjects import fields", "db_group_snapshot = { 'id': fake.GROUP_SNAPSHOT_ID, 'name': 'group-1', 'status': 'available', 'user_id':", "fake.GROUP_ID, } for name, field in objects.GroupSnapshot.fields.items(): if name in", "'name': 'group-1', 'status': 'available', 'user_id': fake.USER_ID, 'project_id': fake.PROJECT_ID, 'group_type_id': fake.GROUP_TYPE_ID,", "fields from cinder import objects from cinder.tests.unit import fake_constants as", "for name, field in objects.GroupSnapshot.fields.items(): if name in db_group_snapshot: continue", "fake.PROJECT_ID, 'group_type_id': fake.GROUP_TYPE_ID, 'group_id': fake.GROUP_ID, } for name, field in", "as fake def fake_db_group_snapshot(**updates): db_group_snapshot = { 'id': fake.GROUP_SNAPSHOT_ID, 'name':", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not" ]
[ "for node, attr in tree.nodes.items(): custom_node_attrs[node] = str(node) nodes_bbox =", "node_size=150, edge_color='#7d7d7d') # nodes labels pos_attrs = {} for node,", "pos_attrs[node] = (coords[0], coords[1] - 10) custom_node_attrs = {} for", "plt.show() def _draw_resolution_tree_(tree: nx.classes.DiGraph, enable_edge_labels: bool = True, rotate_edge_labels: bool", "as plt import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout", "nodes_pos.items(): pos_attrs[node] = (coords[0], coords[1] - 10) custom_node_attrs = {}", "from networkx.drawing.nx_agraph import graphviz_layout def display_resolution_tree(resolution_tree: nx.classes.DiGraph): _draw_resolution_tree_(resolution_tree) plt.show() def", "labels pos_attrs = {} for node, coords in nodes_pos.items(): pos_attrs[node]", "edge_color='#7d7d7d') # nodes labels pos_attrs = {} for node, coords", "in nodes_pos.items(): pos_attrs[node] = (coords[0], coords[1] - 10) custom_node_attrs =", "= {} for node, coords in nodes_pos.items(): pos_attrs[node] = (coords[0],", "True, rotate_edge_labels: bool = False): plt.figure() # graph nodes_pos =", "nodes_bbox = dict(facecolor=\"w\", edgecolor=\"#d3d3d3\", pad=6, lw=0.1) nx.draw_networkx_labels( tree, pos_attrs, labels=custom_node_attrs,", "bbox=nodes_bbox) # edge labels if enable_edge_labels: edges_pos = graphviz_layout(tree, prog='dot')", "font_size=13, bbox=nodes_bbox) # edge labels if enable_edge_labels: edges_pos = graphviz_layout(tree,", "_draw_resolution_tree_(resolution_tree) plt.show() def _draw_resolution_tree_(tree: nx.classes.DiGraph, enable_edge_labels: bool = True, rotate_edge_labels:", "node, coords in nodes_pos.items(): pos_attrs[node] = (coords[0], coords[1] - 10)", "= str(node) nodes_bbox = dict(facecolor=\"w\", edgecolor=\"#d3d3d3\", pad=6, lw=0.1) nx.draw_networkx_labels( tree,", "<gh_stars>0 import matplotlib.pyplot as plt import networkx as nx from", "coords[1] - 10) custom_node_attrs = {} for node, attr in", "matplotlib.pyplot as plt import networkx as nx from networkx.drawing.nx_agraph import", "graphviz_layout(tree, prog='dot') nx.draw(tree, nodes_pos, node_size=150, edge_color='#7d7d7d') # nodes labels pos_attrs", "nodes_pos, node_size=150, edge_color='#7d7d7d') # nodes labels pos_attrs = {} for", "as nx from networkx.drawing.nx_agraph import graphviz_layout def display_resolution_tree(resolution_tree: nx.classes.DiGraph): _draw_resolution_tree_(resolution_tree)", "networkx.drawing.nx_agraph import graphviz_layout def display_resolution_tree(resolution_tree: nx.classes.DiGraph): _draw_resolution_tree_(resolution_tree) plt.show() def _draw_resolution_tree_(tree:", "pad=6, lw=0.1) nx.draw_networkx_labels( tree, pos_attrs, labels=custom_node_attrs, font_size=13, bbox=nodes_bbox) # edge", "= graphviz_layout(tree, prog='dot') edge_labels = nx.get_edge_attributes(tree, 'transformation') nx.draw_networkx_edge_labels( tree, pos=edges_pos,", "nodes_pos = graphviz_layout(tree, prog='dot') nx.draw(tree, nodes_pos, node_size=150, edge_color='#7d7d7d') # nodes", "in tree.nodes.items(): custom_node_attrs[node] = str(node) nodes_bbox = dict(facecolor=\"w\", edgecolor=\"#d3d3d3\", pad=6,", "nx.draw_networkx_labels( tree, pos_attrs, labels=custom_node_attrs, font_size=13, bbox=nodes_bbox) # edge labels if", "nx.draw(tree, nodes_pos, node_size=150, edge_color='#7d7d7d') # nodes labels pos_attrs = {}", "custom_node_attrs = {} for node, attr in tree.nodes.items(): custom_node_attrs[node] =", "False): plt.figure() # graph nodes_pos = graphviz_layout(tree, prog='dot') nx.draw(tree, nodes_pos,", "nodes labels pos_attrs = {} for node, coords in nodes_pos.items():", "= True, rotate_edge_labels: bool = False): plt.figure() # graph nodes_pos", "edge labels if enable_edge_labels: edges_pos = graphviz_layout(tree, prog='dot') edge_labels =", "edgecolor=\"#d3d3d3\", pad=6, lw=0.1) nx.draw_networkx_labels( tree, pos_attrs, labels=custom_node_attrs, font_size=13, bbox=nodes_bbox) #", "graph nodes_pos = graphviz_layout(tree, prog='dot') nx.draw(tree, nodes_pos, node_size=150, edge_color='#7d7d7d') #", "tree.nodes.items(): custom_node_attrs[node] = str(node) nodes_bbox = dict(facecolor=\"w\", edgecolor=\"#d3d3d3\", pad=6, lw=0.1)", "pos_attrs = {} for node, coords in nodes_pos.items(): pos_attrs[node] =", "= graphviz_layout(tree, prog='dot') nx.draw(tree, nodes_pos, node_size=150, edge_color='#7d7d7d') # nodes labels", "# edge labels if enable_edge_labels: edges_pos = graphviz_layout(tree, prog='dot') edge_labels", "def display_resolution_tree(resolution_tree: nx.classes.DiGraph): _draw_resolution_tree_(resolution_tree) plt.show() def _draw_resolution_tree_(tree: nx.classes.DiGraph, enable_edge_labels: bool", "- 10) custom_node_attrs = {} for node, attr in tree.nodes.items():", "pos_attrs, labels=custom_node_attrs, font_size=13, bbox=nodes_bbox) # edge labels if enable_edge_labels: edges_pos", "= (coords[0], coords[1] - 10) custom_node_attrs = {} for node,", "plt import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout def", "{} for node, attr in tree.nodes.items(): custom_node_attrs[node] = str(node) nodes_bbox", "dict(facecolor=\"w\", edgecolor=\"#d3d3d3\", pad=6, lw=0.1) nx.draw_networkx_labels( tree, pos_attrs, labels=custom_node_attrs, font_size=13, bbox=nodes_bbox)", "= False): plt.figure() # graph nodes_pos = graphviz_layout(tree, prog='dot') nx.draw(tree,", "str(node) nodes_bbox = dict(facecolor=\"w\", edgecolor=\"#d3d3d3\", pad=6, lw=0.1) nx.draw_networkx_labels( tree, pos_attrs,", "import matplotlib.pyplot as plt import networkx as nx from networkx.drawing.nx_agraph", "{} for node, coords in nodes_pos.items(): pos_attrs[node] = (coords[0], coords[1]", "= dict(facecolor=\"w\", edgecolor=\"#d3d3d3\", pad=6, lw=0.1) nx.draw_networkx_labels( tree, pos_attrs, labels=custom_node_attrs, font_size=13,", "for node, coords in nodes_pos.items(): pos_attrs[node] = (coords[0], coords[1] -", "attr in tree.nodes.items(): custom_node_attrs[node] = str(node) nodes_bbox = dict(facecolor=\"w\", edgecolor=\"#d3d3d3\",", "bool = False): plt.figure() # graph nodes_pos = graphviz_layout(tree, prog='dot')", "networkx as nx from networkx.drawing.nx_agraph import graphviz_layout def display_resolution_tree(resolution_tree: nx.classes.DiGraph):", "rotate_edge_labels: bool = False): plt.figure() # graph nodes_pos = graphviz_layout(tree,", "(coords[0], coords[1] - 10) custom_node_attrs = {} for node, attr", "plt.figure() # graph nodes_pos = graphviz_layout(tree, prog='dot') nx.draw(tree, nodes_pos, node_size=150,", "node, attr in tree.nodes.items(): custom_node_attrs[node] = str(node) nodes_bbox = dict(facecolor=\"w\",", "labels if enable_edge_labels: edges_pos = graphviz_layout(tree, prog='dot') edge_labels = nx.get_edge_attributes(tree,", "graphviz_layout def display_resolution_tree(resolution_tree: nx.classes.DiGraph): _draw_resolution_tree_(resolution_tree) plt.show() def _draw_resolution_tree_(tree: nx.classes.DiGraph, enable_edge_labels:", "display_resolution_tree(resolution_tree: nx.classes.DiGraph): _draw_resolution_tree_(resolution_tree) plt.show() def _draw_resolution_tree_(tree: nx.classes.DiGraph, enable_edge_labels: bool =", "custom_node_attrs[node] = str(node) nodes_bbox = dict(facecolor=\"w\", edgecolor=\"#d3d3d3\", pad=6, lw=0.1) nx.draw_networkx_labels(", "tree, pos_attrs, labels=custom_node_attrs, font_size=13, bbox=nodes_bbox) # edge labels if enable_edge_labels:", "_draw_resolution_tree_(tree: nx.classes.DiGraph, enable_edge_labels: bool = True, rotate_edge_labels: bool = False):", "= {} for node, attr in tree.nodes.items(): custom_node_attrs[node] = str(node)", "# graph nodes_pos = graphviz_layout(tree, prog='dot') nx.draw(tree, nodes_pos, node_size=150, edge_color='#7d7d7d')", "graphviz_layout(tree, prog='dot') edge_labels = nx.get_edge_attributes(tree, 'transformation') nx.draw_networkx_edge_labels( tree, pos=edges_pos, edge_labels=edge_labels,", "nx.classes.DiGraph): _draw_resolution_tree_(resolution_tree) plt.show() def _draw_resolution_tree_(tree: nx.classes.DiGraph, enable_edge_labels: bool = True,", "enable_edge_labels: bool = True, rotate_edge_labels: bool = False): plt.figure() #", "edge_labels = nx.get_edge_attributes(tree, 'transformation') nx.draw_networkx_edge_labels( tree, pos=edges_pos, edge_labels=edge_labels, font_size=13, rotate=rotate_edge_labels)", "bool = True, rotate_edge_labels: bool = False): plt.figure() # graph", "prog='dot') nx.draw(tree, nodes_pos, node_size=150, edge_color='#7d7d7d') # nodes labels pos_attrs =", "def _draw_resolution_tree_(tree: nx.classes.DiGraph, enable_edge_labels: bool = True, rotate_edge_labels: bool =", "prog='dot') edge_labels = nx.get_edge_attributes(tree, 'transformation') nx.draw_networkx_edge_labels( tree, pos=edges_pos, edge_labels=edge_labels, font_size=13,", "if enable_edge_labels: edges_pos = graphviz_layout(tree, prog='dot') edge_labels = nx.get_edge_attributes(tree, 'transformation')", "import graphviz_layout def display_resolution_tree(resolution_tree: nx.classes.DiGraph): _draw_resolution_tree_(resolution_tree) plt.show() def _draw_resolution_tree_(tree: nx.classes.DiGraph,", "enable_edge_labels: edges_pos = graphviz_layout(tree, prog='dot') edge_labels = nx.get_edge_attributes(tree, 'transformation') nx.draw_networkx_edge_labels(", "lw=0.1) nx.draw_networkx_labels( tree, pos_attrs, labels=custom_node_attrs, font_size=13, bbox=nodes_bbox) # edge labels", "10) custom_node_attrs = {} for node, attr in tree.nodes.items(): custom_node_attrs[node]", "nx from networkx.drawing.nx_agraph import graphviz_layout def display_resolution_tree(resolution_tree: nx.classes.DiGraph): _draw_resolution_tree_(resolution_tree) plt.show()", "edges_pos = graphviz_layout(tree, prog='dot') edge_labels = nx.get_edge_attributes(tree, 'transformation') nx.draw_networkx_edge_labels( tree,", "labels=custom_node_attrs, font_size=13, bbox=nodes_bbox) # edge labels if enable_edge_labels: edges_pos =", "coords in nodes_pos.items(): pos_attrs[node] = (coords[0], coords[1] - 10) custom_node_attrs", "nx.classes.DiGraph, enable_edge_labels: bool = True, rotate_edge_labels: bool = False): plt.figure()", "# nodes labels pos_attrs = {} for node, coords in", "import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout def display_resolution_tree(resolution_tree:" ]
[ "setuptools.setup( name = 'sili-canvas', version = '0.0.1', license = 'MIT',", "'MIT', url = 'https://github.com/SilicalNZ/canvas', description = 'A series of easy", "= '0.0.1', license = 'MIT', url = 'https://github.com/SilicalNZ/canvas', description =", "use classes to perform complex 2D array transformations', long_description =", "to perform complex 2D array transformations', long_description = '', author", "2D array transformations', long_description = '', author = 'SilicalNZ', packages", "<filename>setup.py import setuptools setuptools.setup( name = 'sili-canvas', version = '0.0.1',", "description = 'A series of easy to use classes to", "setuptools setuptools.setup( name = 'sili-canvas', version = '0.0.1', license =", "url = 'https://github.com/SilicalNZ/canvas', description = 'A series of easy to", "= 'MIT', url = 'https://github.com/SilicalNZ/canvas', description = 'A series of", "= '', author = 'SilicalNZ', packages = ['canvas', 'canvas.common', 'canvas.tools']", "transformations', long_description = '', author = 'SilicalNZ', packages = ['canvas',", "'', author = 'SilicalNZ', packages = ['canvas', 'canvas.common', 'canvas.tools'] )", "easy to use classes to perform complex 2D array transformations',", "'https://github.com/SilicalNZ/canvas', description = 'A series of easy to use classes", "= 'A series of easy to use classes to perform", "perform complex 2D array transformations', long_description = '', author =", "'A series of easy to use classes to perform complex", "license = 'MIT', url = 'https://github.com/SilicalNZ/canvas', description = 'A series", "of easy to use classes to perform complex 2D array", "name = 'sili-canvas', version = '0.0.1', license = 'MIT', url", "to use classes to perform complex 2D array transformations', long_description", "complex 2D array transformations', long_description = '', author = 'SilicalNZ',", "= 'sili-canvas', version = '0.0.1', license = 'MIT', url =", "version = '0.0.1', license = 'MIT', url = 'https://github.com/SilicalNZ/canvas', description", "long_description = '', author = 'SilicalNZ', packages = ['canvas', 'canvas.common',", "array transformations', long_description = '', author = 'SilicalNZ', packages =", "import setuptools setuptools.setup( name = 'sili-canvas', version = '0.0.1', license", "'0.0.1', license = 'MIT', url = 'https://github.com/SilicalNZ/canvas', description = 'A", "series of easy to use classes to perform complex 2D", "classes to perform complex 2D array transformations', long_description = '',", "'sili-canvas', version = '0.0.1', license = 'MIT', url = 'https://github.com/SilicalNZ/canvas',", "= 'https://github.com/SilicalNZ/canvas', description = 'A series of easy to use" ]
[ "mock_d = {} form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl", "50, 60, 70, 80, 90] raw[\"metric3\"] = [100, 200, 300,", "pd.DataFrame(raw) test_viz = viz.NVD3TimeSeriesViz(datasource, form_data) viz_data = {} viz_data =", "\"count\": [30, 42, 3, 29]}) test_viz = viz.DistributionBarViz(datasource, form_data) data", "query_obj[\"extras\"][\"where\"]) self.assertEqual(\"\", query_obj[\"extras\"][\"having\"]) def test_query_obj_merges_percent_metrics(self): datasource = self.get_datasource_mock() form_data =", "{\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, } ] form_data = { \"metrics\":", "\"metric2\", \"metric3\"] self.assertEqual(sorted(cols), sorted(levels[0].columns.tolist())) cols += [\"groupA\"] self.assertEqual(sorted(cols), sorted(levels[1].columns.tolist())) cols", "= viz.PartitionViz(Mock(), {}) groups = [\"groupA\", \"groupB\", \"groupC\"] levels =", "{\"x\": \"0.0\", \"y\": 30}, {\"x\": \"2.0\", \"y\": 29}, {\"x\": NULL_STRING,", "test_viz_deckgl.form_data[\"adhoc_filters\"] assert expected_results.get(mock_key) == adhoc_filters class TimeSeriesVizTestCase(SupersetTestCase): def test_timeseries_unicode_data(self): datasource", "def test_timeseries_unicode_data(self): datasource = self.get_datasource_mock() form_data = {\"groupby\": [\"name\"], \"metrics\":", "\"key\": (\"c1\",), \"name\": (\"c1\",)}, ], } self.assertEqual(expected, res) class TimeSeriesTableVizTestCase(SupersetTestCase):", "datasource = self.get_datasource_mock() form_data = {\"include_time\": True} with self.assertRaises(Exception): test_viz", "class BigNumberVizTestCase(SupersetTestCase): def test_get_data(self): datasource = self.get_datasource_mock() df = pd.DataFrame(", "{ \"values\": [ {\"x\": 100, \"y\": 70}, {\"x\": 200, \"y\":", "t3, \"value\": 6, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t3, \"value\":", "2.0 (the # \"License\"); you may not use this file", "\"metric3\": {\"a1\": 200, \"b1\": 200, \"c1\": 200}, } self.assertEqual(expected, levels[1].to_dict())", "\"b1\": 5, \"c1\": 8}, \"metric2\": {\"a1\": 20, \"b1\": 50, \"c1\":", "= Mock() datasource.type = \"table\" test_viz = viz.BaseViz(datasource, form_data) expect_metric_labels", "class PairedTTestTestCase(SupersetTestCase): def test_get_data_transforms_dataframe(self): form_data = { \"groupby\": [\"groupA\", \"groupB\",", "df = pd.DataFrame(raw) test_viz = viz.PartitionViz(Mock(), {}) groups = [\"groupA\",", "= test_viz.get_data(df)[0] self.assertEqual(\"count\", data[\"key\"]) expected_values = [ {\"x\": \"1.0\", \"y\":", "\"All\", } ], } self.assertEqual(data, expected) class PartitionVizTestCase(SupersetTestCase): @patch(\"superset.viz.BaseViz.query_obj\") def", "300, \"y\": 3}, ], \"group\": (\"a1\", \"a2\", \"a3\"), }, {", "0)], name=DTTM_ALIAS) ) mock_dttm_col.python_date_format = None result = test_viz.get_df(query_obj) pd.testing.assert_series_equal(", "= self.get_datasource_mock() form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed", "(u\"Real Madrid Basket\",), }, { u\"values\": [ {u\"y\": 2, u\"x\":", "procs[i] = pivot nest = test_viz.nest_procs(procs) self.assertEqual(3, len(nest)) for i", "\"groupB\": [\"x\", \"x\", \"y\", \"z\"], } ) test_viz = viz.TableViz(datasource,", "\"markdown\", \"where\": \"\", \"compare_suffix\": \"o10Y\", } datasource = Mock() datasource.type", "\"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lonlat\",", "= self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual(", "C.F.\\U0001f1fa\\U0001f1f8\\U0001f1ec\\U0001f1e7\",), }, ] self.assertEqual(expected, viz_data) def test_process_data_resample(self): datasource = self.get_datasource_mock()", "+= [\"groupB\"] self.assertEqual(sorted(cols), sorted(levels[2].columns.tolist())) cols += [\"groupC\"] self.assertEqual(sorted(cols), sorted(levels[3].columns.tolist())) self.assertEqual(4,", "df = pd.DataFrame({\"beds\": [0, 1, nan, 2], \"count\": [30, 42,", "= Mock() results.query = Mock() results.status = Mock() results.error_message =", "viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual([\"colA\", \"colB\", metric], query_obj[\"metrics\"]) self.assertEqual([(metric,", "42, 3, 29]}) test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0]", "def test_nest_procs_returns_hierarchy(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300,", "\"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t2, \"value\": 8, \"key\": (\"c1\",),", "load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(SpatialException):", "result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS) ) datasource.offset =", "\"y\": 400}, {\"x\": 200, \"y\": 500}, {\"x\": 300, \"y\": 600},", "procs = {} for i in range(0, 4): df_drop =", "test_get_data_calls_correct_method(self): test_viz = viz.PartitionViz(Mock(), {}) df = Mock() with self.assertRaises(ValueError):", "{\"x\": \"2.0\", \"y\": 29}, {\"x\": NULL_STRING, \"y\": 3}, ] self.assertEqual(expected_values,", "form_data) with self.assertRaises(Exception): test_viz.query_obj() class BaseDeckGLVizTestCase(SupersetTestCase): def test_get_metrics(self): form_data =", "800, 900] df = pd.DataFrame(raw) test_viz = viz.PartitionViz(Mock(), {}) groups", "3}, ] self.assertEqual(expected_values, data[\"values\"]) def test_column_nulls(self): form_data = { \"metrics\":", "\"dummy2\", \"c\": \"dummy3\"} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_js_columns(mock_d)", "\"percent_metrics\": [\"count\"], \"slice_id\": 74, \"time_grain_sqla\": None, \"order_by_cols\": [], \"groupby\": [\"country_name\"],", "data[\"records\"]) def test_parse_adhoc_filters(self): form_data = { \"metrics\": [ { \"expressionType\":", "query_obj[\"metrics\"] ) def test_query_obj_throws_columns_and_metrics(self): datasource = self.get_datasource_mock() form_data = {\"all_columns\":", "[ {\"x\": \"pepperoni\", \"y\": 5}, {\"x\": \"cheese\", \"y\": 3}, {\"x\":", "= test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected = { DTTM_ALIAS:", "df) self.assertEqual(4, len(levels)) cols = [DTTM_ALIAS, \"metric1\", \"metric2\", \"metric3\"] self.assertEqual(sorted(cols),", "See the License for the # specific language governing permissions", "\"delimited\", \"lonlatCol\": \"lonlat\"}, \"geohash_key\": {\"type\": \"geohash\", \"geohashCol\": \"geo\"}, } datasource", "viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"votes\", data[\"key\"]) expected_values = [", "test_viz = viz.BaseViz(datasource, form_data) expect_metric_labels = [ u\"sum__SP_POP_TOTL\", u\"SUM(SE_PRM_NENR_MA)\", u\"SUM(SP_URB_TOTL)\",", "\"name\": (\"b1\",)}, {\"time\": t3, \"value\": 9, \"key\": (\"c1\",), \"name\": (\"c1\",)},", "test_levels_for_computes_levels(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300, 100,", "\"metric3\"] procs = {} for i in range(0, 4): df_drop", "= [2, 2, 4, 4] df = pd.DataFrame(raw) test_viz =", "t2 = pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t1, t1, t2, t2,", "sorted(levels[1].columns.tolist())) cols += [\"groupB\"] self.assertEqual(sorted(cols), sorted(levels[2].columns.tolist())) cols += [\"groupC\"] self.assertEqual(sorted(cols),", "BaseDeckGLVizTestCase(SupersetTestCase): def test_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl", "result = test_viz_deckgl.get_metrics() assert result == [] def test_scatterviz_get_metrics(self): form_data", "123} query_obj = {\"granularity\": \"day\"} results = Mock() results.query =", "test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) assert expected_results.get(mock_key) == mock_gb def test_geojson_query_obj(self): form_data =", ".apply_rolling(df)[\"y\"] .tolist(), [1.0, 1.5, 2.0, 2.5], ) class BigNumberVizTestCase(SupersetTestCase): def", "test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected = {DTTM_ALIAS: 1800, \"metric1\":", "self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) data = test_viz.get_data(df) self.assertEqual([\"sum_value\"], data[\"columns\"])", "viz.TableViz(datasource, form_data) data = test_viz.get_data(df) self.assertEqual([\"sum_value\"], data[\"columns\"]) class DistBarVizTestCase(SupersetTestCase): def", "= \"not_time\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" test_viz.get_data(df) self.assertEqual(\"agg_sum\",", "200, \"y\": 20}, {\"x\": 300, \"y\": 30}, ], \"group\": (\"a1\",", "\"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lat\",", "groups = [\"groupA\", \"groupB\", \"groupC\"] time_op = \"agg_sum\" test_viz =", "= test_viz_deckgl.get_metrics() assert result == [] def test_scatterviz_get_metrics(self): form_data =", "pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") t3 = pd.Timestamp(\"2004\") raw[DTTM_ALIAS] = [t1,", "data = test_viz.get_data(df) # Check method correctly transforms data self.assertEqual(set([\"a1\",", "\"name\": (\"c1\",)}, ], } self.assertEqual(expected, res) class TimeSeriesTableVizTestCase(SupersetTestCase): def test_get_data_metrics(self):", "20] raw[\"count\"] = [6, 7] df = pd.DataFrame(raw) test_viz =", "\"cheese\", \"y\": 1}], }, { \"key\": \"engineer\", \"values\": [{\"x\": \"pepperoni\",", "{DTTM_ALIAS: 1800, \"metric1\": 45, \"metric2\": 450, \"metric3\": 4500} self.assertEqual(expected, levels[0].to_dict())", "= pd.Timestamp(\"2004\") raw[DTTM_ALIAS] = [t1, t2, t3, t1, t2, t3,", "= test_viz.get_data(df) # Check method correctly transforms data self.assertEqual(set([\"count\", \"sum__A\"]),", "('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"(SUM(value1) > 5)\", query_obj[\"extras\"][\"having\"]) def test_adhoc_filters_overwrite_legacy_filters(self): form_data", "], } self.assertEqual(data, expected) def test_get_data_empty_null_keys(self): form_data = {\"groupby\": [],", "self.assertEqual(sorted(cols), sorted(levels[1].columns.tolist())) cols += [\"groupB\"] self.assertEqual(sorted(cols), sorted(levels[2].columns.tolist())) cols += [\"groupC\"]", "[ {\"time\": t1, \"value\": 1, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\":", "1, 5, 0)], name=DTTM_ALIAS) ) datasource.offset = 1 result =", "self.assertTrue(result.empty) def test_get_df_handles_dttm_col(self): form_data = {\"dummy\": 123} query_obj = {\"granularity\":", "super_query_obj.return_value = { \"columns\": [\"colD\", \"colC\"], \"groupby\": [\"colA\", \"colB\"], }", "self.get_datasource_mock() form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed =", "test_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource,", "test_viz = viz.NVD3TimeSeriesViz(datasource, form_data) viz_data = {} viz_data = test_viz.get_data(df)", "1, 1, 5, 0)], name=DTTM_ALIAS) ) datasource.offset = 1 result", "\"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, } ] form_data = {", "\"A\", \"groupB\": \"x\", \"SUM(value1)\": 15, \"count\": 6, \"avg__C\": 11, \"%SUM(value1)\":", "11, \"%SUM(value1)\": 0.15, \"%avg__B\": 0.2, }, { \"groupA\": \"B\", \"groupB\":", "class TimeSeriesTableVizTestCase(SupersetTestCase): def test_get_data_metrics(self): form_data = {\"metrics\": [\"sum__A\", \"count\"], \"groupby\":", "\"lonlat\"}, \"geohash_key\": {\"type\": \"geohash\", \"geohashCol\": \"geo\"}, } datasource = self.get_datasource_mock()", "None} def test_get_properties(self): mock_d = {} form_data = load_fixture(\"deck_path_form_data.json\") datasource", "= pd.DataFrame(raw) fd = {\"metrics\": [\"metric1\"], \"groupby\": [\"groupA\"]} test_viz =", "test_viz.cache_timeout) datasource.database.cache_timeout = None test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(app.config[\"CACHE_DEFAULT_TIMEOUT\"], test_viz.cache_timeout)", "test_get_data_applies_percentage(self): form_data = { \"groupby\": [\"groupA\", \"groupB\"], \"metrics\": [ {", "= self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(NotImplementedError) as context:", "= self.get_datasource_mock() mock_d = {\"a\": \"dummy1\", \"b\": \"dummy2\", \"c\": \"dummy3\"}", "0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 1.5, 2.0, 2.5], )", "[], \"groupby\": [\"toppings\"], \"columns\": [\"role\"], } datasource = self.get_datasource_mock() df", "[ {\"x\": 100, \"y\": 700}, {\"x\": 200, \"y\": 800}, {\"x\":", "10, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 1.5, 2.0,", "data expected = { \"N/A\": [ { \"values\": [ {\"x\":", "2.0, 2.5], ) class BigNumberVizTestCase(SupersetTestCase): def test_get_data(self): datasource = self.get_datasource_mock()", "= \"time_series\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[3][1][0]) self.assertEqual(7, len(test_viz.nest_values.mock_calls)) class RoseVisTestCase(SupersetTestCase): def", "form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"votes\", data[\"key\"]) expected_values = [ {\"x\":", "{} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {\"type\": \"metric\", \"value\":", "transforms data expected = { \"N/A\": [ { \"values\": [", "4.0], } ) data = viz.BigNumberViz(datasource, {\"metrics\": [\"y\"]}).get_data(df) self.assertEqual(data[2], {DTTM_ALIAS:", "}, ] self.assertEqual(expected, data[\"records\"]) def test_parse_adhoc_filters(self): form_data = { \"metrics\":", "\"0.0\", \"y\": 30}, {\"x\": \"2.0\", \"y\": 29}, {\"x\": NULL_STRING, \"y\":", "= \"table\" test_viz = viz.BaseViz(datasource, form_data) expect_metric_labels = [ u\"sum__SP_POP_TOTL\",", "\"lonlatCol\": \"lonlat\"}, \"geohash_key\": {\"type\": \"geohash\", \"geohashCol\": \"geo\"}, } datasource =", "values=metrics ) procs[i] = pivot nest = test_viz.nest_procs(procs) self.assertEqual(3, len(nest))", "{\"a1\": 15, \"a2\": 20, \"a3\": 25}, t2.strftime(time_format): {\"a1\": 30, \"a2\":", "from superset import app from superset.constants import NULL_STRING from superset.exceptions", "[ \"groupA\", \"groupB\", \"SUM(value1)\", \"count\", \"avg__C\", \"%SUM(value1)\", \"%avg__B\", ], list(data[\"columns\"]),", "\"c3\", \"c3\"] raw[\"metric1\"] = [1, 2, 3, 4, 5, 6,", "\"value\": 9, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], } self.assertEqual(expected, res)", "viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() class BaseDeckGLVizTestCase(SupersetTestCase): def test_get_metrics(self): form_data", "\"lonCol\": \"lon\", \"latCol\": \"lat\"}, \"delimited_key\": {\"type\": \"delimited\", \"lonlatCol\": \"lonlat\"}, \"geohash_key\":", "raw[\"groupC\"] = [\"a3\", \"a3\", \"a3\", \"b3\", \"b3\", \"b3\", \"c3\", \"c3\",", "\"until\": \"2014-01-02\", \"metrics\": [\"sum__SP_POP_TOTL\", \"SUM(SE_PRM_NENR_MA)\", \"SUM(SP_URB_TOTL)\"], \"country_fieldtype\": \"cca3\", \"percent_metrics\": [\"count\"],", "156 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(156, test_viz.cache_timeout) datasource.cache_timeout = None", "None test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(app.config[\"CACHE_DEFAULT_TIMEOUT\"], test_viz.cache_timeout) class TableVizTestCase(SupersetTestCase): def", "See the NOTICE file # distributed with this work for", "np.nan, np.nan, 5.0, np.nan, 7.0], ) def test_apply_rolling(self): datasource =", "\"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_diff_computes_difference(self): raw = {} raw[DTTM_ALIAS] =", "df = pd.DataFrame(raw) groups = [\"groupA\", \"groupB\", \"groupC\"] time_op =", "30}, {\"x\": \"2.0\", \"y\": 29}, {\"x\": NULL_STRING, \"y\": 3}, ]", "run_test(metric): form_data[\"timeseries_limit_metric\"] = metric test_viz = viz.TableViz(datasource, form_data) query_obj =", "Apache License, Version 2.0 (the # \"License\"); you may not", "= pd.DataFrame({\"beds\": [0, 1, nan, 2], \"count\": [30, 42, 3,", "\"y\": 40}, {\"x\": 200, \"y\": 50}, {\"x\": 300, \"y\": 60},", "\"name\": (\"c1\",)}, ], 1072915200000000000: [ {\"time\": t3, \"value\": 3, \"key\":", "data expected = { \"metric1\": [ { \"values\": [ {\"x\":", "1.5, 2.0, 2.5], ) class BigNumberVizTestCase(SupersetTestCase): def test_get_data(self): datasource =", "90] raw[\"metric3\"] = [100, 200, 300, 400, 500, 600, 700,", "self.assertEqual(expected, res) class TimeSeriesTableVizTestCase(SupersetTestCase): def test_get_data_metrics(self): form_data = {\"metrics\": [\"sum__A\",", "[\"latlong_key\", \"delimited_key\", \"geohash_key\"]: mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data)", "raw[\"sum__A\"] = [15, 20] raw[\"count\"] = [6, 7] df =", "[\"a\"]} super_query_obj.return_value = {} test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception):", "datasource, {\"metrics\": [\"y\"], \"resample_method\": \"sum\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(),", "= load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() viz_instance = viz.BaseDeckGLViz(datasource, form_data) coord", "datasource = self.get_datasource_mock() # Test data raw = {} raw[DTTM_ALIAS]", "\"y\": 30}, ], \"group\": (\"a1\", \"a2\", \"a3\"), }, { \"values\":", "0.0, 5.0, 0.0, 7.0], ) np.testing.assert_equal( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"],", "test_parse_adhoc_filters(self): form_data = { \"metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\":", "= {\"metrics\": [\"metric1\"], \"groupby\": [\"groupA\"]} test_viz = viz.RoseViz(Mock(), fd) test_viz.metrics", "\"2019-01-05\", \"2019-01-07\"] ), data={\"y\": [1.0, 2.0, 3.0, 4.0]}, ) self.assertEqual(", "= self.get_datasource_mock() form_data = { \"metrics\": [\"sum__A\", \"count\", \"avg__C\"], \"percent_metrics\":", "\"c3\"), }, ], } self.assertEqual(data, expected) def test_get_data_empty_null_keys(self): form_data =", "\"val\": \"10\", \"col\": \"SUM(value1)\"}], query_obj[\"extras\"][\"having_druid\"], ) self.assertEqual(\"(value3 in ('North America'))\",", "[\"count\"], \"adhoc_filters\": [], \"groupby\": [\"beds\"], \"columns\": [], } datasource =", "test_viz = viz.PartitionViz(Mock(), {}) groups = [\"groupA\", \"groupB\", \"groupC\"] metrics", "test_viz.get_data(df) # Check method correctly transforms data self.assertEqual(set([\"a1\", \"a2\", \"a3\"]),", "[\"groupA\", \"groupB\", \"groupC\"] test_viz = viz.PartitionViz(Mock(), {}) time_op = \"point_diff\"", "fd) test_viz.metrics = fd[\"metrics\"] res = test_viz.get_data(df) expected = {", "test_scatterviz_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() form_data = {}", "800, 900] df = pd.DataFrame(raw) groups = [\"groupA\", \"groupB\", \"groupC\"]", "= \"agg_mean\" test_viz.get_data(df) self.assertEqual(\"agg_mean\", test_viz.levels_for.mock_calls[2][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_diff\" test_viz.levels_for_diff =", "\"colB\", metric], query_obj[\"metrics\"]) self.assertEqual([(metric, True)], query_obj[\"orderby\"]) run_test(\"simple_metric\") run_test( { \"label\":", "200, 300, 100, 200, 300] raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\",", "use this file except in compliance # with the License.", "assert expected_results.get(mock_key) == adhoc_filters class TimeSeriesVizTestCase(SupersetTestCase): def test_timeseries_unicode_data(self): datasource =", "\"metric2\", \"metric3\"] procs = {} for i in range(0, 4):", "6, 7, 8, 9] raw[\"metric2\"] = [10, 20, 30, 40,", "[], \"groupby\": [\"country_name\"], \"compare_lag\": \"10\", \"limit\": \"25\", \"datasource\": \"2__table\", \"table_timestamp_format\":", "self.get_datasource_mock() test_viz = viz.BaseViz(datasource, form_data) result = test_viz.get_df(query_obj) self.assertEqual(type(result), pd.DataFrame)", "\"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", ] raw[\"sum__payout\"] = [2, 2, 4, 4] df", "{} raw[DTTM_ALIAS] = [100, 200, 300] raw[\"\"] = [1, 2,", "transforms data expected = { \"metric1\": [ { \"values\": [", "\"DOUBLE\"}, } ] form_data = { \"metrics\": metrics, \"timeseries_limit_metric\": {", "aggregate): return df_drop test_viz.process_data = Mock(side_effect=return_args) levels = test_viz.levels_for_time(groups, df)", "= viz.PartitionViz(Mock(), {}) time_op = \"point_diff\" levels = test_viz.levels_for_diff(time_op, groups,", "100, \"y\": 7}, {\"x\": 200, \"y\": 8}, {\"x\": 300, \"y\":", "{\"metrics\": [\"sum__A\"], \"groupby\": [\"groupby1\"]} datasource = self.get_datasource_mock() raw = {}", "expected = { t1.strftime(time_format): {\"a1\": 15, \"a2\": 20, \"a3\": 25},", "] self.assertEqual(expected, data) class PairedTTestTestCase(SupersetTestCase): def test_get_data_transforms_dataframe(self): form_data = {", "None with self.assertRaises(Exception): viz.BaseViz(datasource, form_data) def test_process_metrics(self): # test TableViz", "} self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names)", "test_constructor_exception_no_datasource(self): form_data = {} datasource = None with self.assertRaises(Exception): viz.BaseViz(datasource,", "\"y\": 200}, {\"x\": 300, \"y\": 300}, ], \"group\": (\"a1\", \"a2\",", "100, \"y\": 700}, {\"x\": 200, \"y\": 800}, {\"x\": 300, \"y\":", "900] df = pd.DataFrame(raw) test_viz = viz.PartitionViz(Mock(), {}) groups =", "} ) test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"votes\",", "{ \"metric1\": [ { \"values\": [ {\"x\": 100, \"y\": 1},", "= {} test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() form_data[\"metrics\"]", "data={\"y\": [1.0, 2.0, 3.0, 4.0]}, ) self.assertEqual( viz.BigNumberViz( datasource, {", "{\"x\": 300, \"y\": 3}, ], \"group\": (\"a1\", \"a2\", \"a3\"), },", "\"2019-01-07\"] ), \"y\": [1.0, 2.0, 5.0, 7.0], } ) self.assertEqual(", "6}, t2.strftime(time_format): {\"sum__A\": 20, \"count\": 7}, } self.assertEqual(expected, data[\"records\"]) def", "uuid.UUID(\"12345678123456781234567812345678\") test_form_data = { \"latlong_key\": {\"type\": \"latlong\", \"lonCol\": \"lon\", \"latCol\":", "None result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5,", "load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result =", "self.assertEqual(1, len(test_viz.levels_for_time.mock_calls)) self.assertEqual(1, len(test_viz.nest_procs.mock_calls)) test_viz.form_data[\"time_series_option\"] = \"time_series\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[3][1][0])", "7, \"avg__C\": 22, \"%SUM(value1)\": 0.2, \"%avg__B\": 0.4, }, { \"groupA\":", "= viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df) expected = [ {", "cols += [\"groupB\"] self.assertEqual(sorted(cols), sorted(levels[2].columns.tolist())) cols += [\"groupC\"] self.assertEqual(sorted(cols), sorted(levels[3].columns.tolist()))", "= self.get_datasource_mock() df = pd.DataFrame( data={ DTTM_ALIAS: pd.to_datetime( [\"2019-01-01\", \"2019-01-02\",", "{\"x\": 200, \"y\": 2}, {\"x\": 300, \"y\": 3}, ], \"group\":", "work for additional information # regarding copyright ownership. The ASF", "Mock(return_value=1) test_viz.form_data[\"time_series_option\"] = \"adv_anal\" test_viz.get_data(df) self.assertEqual(1, len(test_viz.levels_for_time.mock_calls)) self.assertEqual(1, len(test_viz.nest_procs.mock_calls)) test_viz.form_data[\"time_series_option\"]", "8}, \"metric2\": {\"a1\": 20, \"b1\": 50, \"c1\": 80}, \"metric3\": {\"a1\":", "{\"dummy\": 123} query_obj = {\"granularity\": \"day\"} results = Mock() results.query", "None], \"votes\": [3, 5, 1, 2], } ) test_viz =", "the License. # isort:skip_file import uuid from datetime import datetime", "'[\"colC\"]'], } super_query_obj.return_value = { \"columns\": [\"colD\", \"colC\"], \"groupby\": [\"colA\",", "transforms data self.assertEqual(set([\"count\", \"sum__A\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\" expected", "[\"sum__A\"], \"groupby\": [\"groupby1\"]} datasource = self.get_datasource_mock() raw = {} t1", "\"10\", \"limit\": \"25\", \"datasource\": \"2__table\", \"table_timestamp_format\": \"%Y-%m-%d %H:%M:%S\", \"markup_type\": \"markdown\",", "= test_viz.get_data(df) expected = { 946684800000000000: [ {\"time\": t1, \"value\":", "], } datasource = self.get_datasource_mock() df = pd.DataFrame( { \"SUM(value1)\":", "# software distributed under the License is distributed on an", "{ \"values\": [ {\"x\": 100, \"y\": 700}, {\"x\": 200, \"y\":", "\"groupA\": \"B\", \"groupB\": \"x\", \"SUM(value1)\": 20, \"count\": 7, \"avg__C\": 22,", "{\"x\": 100, \"y\": 10}, {\"x\": 200, \"y\": 20}, {\"x\": 300,", "= {} test_viz = viz.PartitionViz(datasource, form_data) super_query_obj.return_value = {} query_obj", "[\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, None, 4.0],", "t2] raw[\"sum__A\"] = [15, 20, 25, 30, 35, 40] raw[\"groupby1\"]", "the License. You may obtain a copy of the License", "= { \"metrics\": [\"votes\"], \"adhoc_filters\": [], \"groupby\": [\"toppings\"], \"columns\": [],", "(\"a1\",)}, {\"time\": t1, \"value\": 4, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\":", "}, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 6.0, 10.0], ) self.assertEqual(", "}, { \"groupA\": \"B\", \"groupB\": \"x\", \"SUM(value1)\": 20, \"count\": 7,", "True} with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.should_be_timeseries() def test_adhoc_metric_with_sortby(self):", "= viz.PartitionViz(Mock(), {\"groupby\": groups}) def return_args(df_drop, aggregate): return df_drop test_viz.process_data", "\"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t3, \"value\": 6, \"key\": (\"b1\",),", "self.assertEqual([(metric, True)], query_obj[\"orderby\"]) run_test(\"simple_metric\") run_test( { \"label\": \"adhoc_metric\", \"expressionType\": \"SIMPLE\",", "test_viz_deckgl.point_radius_fixed = {} result = test_viz_deckgl.get_metrics() assert result == []", "= {} raw[DTTM_ALIAS] = [100, 200, 300] raw[\"\"] = [1,", "self.assertEqual(sorted(cols), sorted(levels[3].columns.tolist())) self.assertEqual(4, len(test_viz.process_data.mock_calls)) def test_nest_values_returns_hierarchy(self): raw = {} raw[\"groupA\"]", "\"2019-01-07\"] ), \"y\": [1.0, 2.0, 3.0, 4.0], } ) data", "[ { \"values\": [ {\"x\": 100, \"y\": 1}, {\"x\": 200,", "test_query_obj_merges_all_columns(self, super_query_obj): datasource = self.get_datasource_mock() form_data = { \"all_columns\": [\"colA\",", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "test_viz.form_data[\"time_series_option\"] = \"agg_mean\" test_viz.get_data(df) self.assertEqual(\"agg_mean\", test_viz.levels_for.mock_calls[2][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_diff\" test_viz.levels_for_diff", ") def test_get_data_calls_correct_method(self): test_viz = viz.PartitionViz(Mock(), {}) df = Mock()", "viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual( [{\"col\": \"value2\", \"val\": \"100\",", "test_viz.form_data[\"time_series_option\"] = \"time_series\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[3][1][0]) self.assertEqual(7, len(test_viz.nest_values.mock_calls)) class RoseVisTestCase(SupersetTestCase):", "200, \"y\": 80}, {\"x\": 300, \"y\": 90}, ], \"group\": (\"c1\",", "], \"metric3\": [ { \"values\": [ {\"x\": 100, \"y\": 100},", "import SupersetTestCase from .utils import load_fixture logger = logging.getLogger(__name__) class", "import load_fixture logger = logging.getLogger(__name__) class BaseVizTestCase(SupersetTestCase): def test_constructor_exception_no_datasource(self): form_data", "test_get_js_columns(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_d = {\"a\":", "== [] assert results[\"columns\"] == [\"test_col\"] def test_parse_coordinates(self): form_data =", "\"latlong\", \"lonCol\": \"lon\", \"latCol\": \"lat\"}, \"delimited_key\": {\"type\": \"delimited\", \"lonlatCol\": \"lonlat\"},", "1, 1, 6, 0)], name=DTTM_ALIAS) ) datasource.offset = 0 results.df", "\"table\" test_viz = viz.BaseViz(datasource, form_data) expect_metric_labels = [ u\"sum__SP_POP_TOTL\", u\"SUM(SE_PRM_NENR_MA)\",", "form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() form_data = {} test_viz_deckgl", "\"c1\", \"c1\"] raw[\"groupB\"] = [\"a2\", \"a2\", \"a2\", \"b2\", \"b2\", \"b2\",", "False, } def run_test(metric): form_data[\"timeseries_limit_metric\"] = metric test_viz = viz.TableViz(datasource,", "\"avg__B\", \"max__Y\"], } test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj()", "[ {\"x\": \"1.0\", \"y\": 42}, {\"x\": \"0.0\", \"y\": 30}, {\"x\":", "\"granularity_sqla\": \"year\", \"page_length\": 0, \"all_columns\": [], \"viz_type\": \"table\", \"since\": \"2014-01-01\",", "test_viz.process_data = Mock(side_effect=return_args) levels = test_viz.levels_for_time(groups, df) self.assertEqual(4, len(levels)) cols", ".tolist(), [1.0, 3.0, 6.0, 10.0], ) self.assertEqual( viz.BigNumberViz( datasource, {", "{\"time\": t2, \"value\": 8, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], 1072915200000000000:", "def test_groupby_nans(self): form_data = { \"metrics\": [\"count\"], \"adhoc_filters\": [], \"groupby\":", "(\"c1\",)}, ], 1009843200000000000: [ {\"time\": t2, \"value\": 2, \"key\": (\"a1\",),", "query_obj[\"extras\"][\"having_druid\"], ) self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"(SUM(value1) > 5)\",", "test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {} result = test_viz_deckgl.get_metrics()", "self.get_datasource_mock() form_data = {\"groupby\": [\"name\"], \"metrics\": [\"sum__payout\"]} raw = {}", "this work for additional information # regarding copyright ownership. The", "in range(0, 4): df_drop = df.drop(groups[i:], 1) pivot = df_drop.pivot_table(", "\"%Y-%m-%d %H:%M:%S\", \"markup_type\": \"markdown\", \"where\": \"\", \"compare_suffix\": \"o10Y\", } datasource", "the NOTICE file # distributed with this work for additional", "100, \"y\": 4}, {\"x\": 200, \"y\": 5}, {\"x\": 300, \"y\":", "\"y\": 90}, ], \"group\": (\"c1\", \"c2\", \"c3\"), }, ], \"metric3\":", "{} t1 = pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1,", "test_viz.form_data[\"time_series_option\"] = \"point_percent\" test_viz.get_data(df) self.assertEqual(\"point_percent\", test_viz.levels_for_diff.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_factor\" test_viz.get_data(df)", "[\"colD\", \"colC\"], \"groupby\": [\"colA\", \"colB\"], } test_viz = viz.TableViz(datasource, form_data)", "= Mock() datasource.get_column = Mock(return_value=mock_dttm_col) test_viz = viz.BaseViz(datasource, form_data) test_viz.df_metrics_to_num", "= df.drop(groups[i:], 1) pivot = df_drop.pivot_table( index=DTTM_ALIAS, columns=groups[:i], values=metrics )", "{}) groups = [\"groupA\", \"groupB\", \"groupC\"] levels = test_viz.levels_for(\"agg_sum\", groups,", "viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual(form_data[\"all_columns\"], query_obj[\"columns\"]) self.assertEqual([], query_obj[\"groupby\"]) self.assertEqual([[\"colA\",", "test_viz.query_obj() class BaseDeckGLVizTestCase(SupersetTestCase): def test_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource =", "\"groupby\": [\"country_name\"], \"compare_lag\": \"10\", \"limit\": \"25\", \"datasource\": \"2__table\", \"table_timestamp_format\": \"%Y-%m-%d", "\"delimited_key\", \"geohash_key\"]: test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data.copy()) test_viz_deckgl.spatial_control_keys = [mock_key] test_viz_deckgl.add_null_filters()", "for mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: mock_gb = [] test_viz_deckgl", "Check method correctly transforms data and computes percents self.assertEqual( [", "= pd.DataFrame({\"SUM(value1)\": [15], \"sum_value\": [15]}) datasource = self.get_datasource_mock() test_viz =", "(\"a1\",), \"name\": (\"a1\",)}, {\"time\": t2, \"value\": 5, \"key\": (\"b1\",), \"name\":", "correctly transforms data self.assertEqual(set([\"count\", \"sum__A\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\"", "\"b\": \"dummy2\", \"c\": \"dummy3\"} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result =", "test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual([\"colA\", \"colB\", metric],", "self.assertEqual(\"point_factor\", test_viz.levels_for_diff.mock_calls[2][1][0]) test_viz.levels_for_time = Mock(return_value=1) test_viz.nest_procs = Mock(return_value=1) test_viz.form_data[\"time_series_option\"] =", "300, \"y\": 9}, ], \"group\": (\"c1\", \"c2\", \"c3\"), }, ],", "nest = test_viz.nest_procs(procs) self.assertEqual(3, len(nest)) for i in range(0, 3):", "License. # isort:skip_file import uuid from datetime import datetime import", "super_query_obj.return_value = {} query_obj = test_viz.query_obj() self.assertFalse(query_obj[\"is_timeseries\"]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\"", "\"point_diff\" levels = test_viz.levels_for_diff(time_op, groups, df) expected = {\"metric1\": 6,", "6, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t3, \"value\": 9, \"key\":", "self.get_datasource_mock() form_data = {\"include_time\": True} with self.assertRaises(Exception): test_viz = viz.TableViz(datasource,", "\"latCol\": \"lat\"}, \"delimited_key\": {\"type\": \"delimited\", \"lonlatCol\": \"lonlat\"}, \"geohash_key\": {\"type\": \"geohash\",", "{\"a1\": 20, \"b1\": 20, \"c1\": 20}, \"metric3\": {\"a1\": 200, \"b1\":", "data[\"columns\"]) class DistBarVizTestCase(SupersetTestCase): def test_groupby_nulls(self): form_data = { \"metrics\": [\"votes\"],", "\"pepperoni\", \"y\": 5}, {\"x\": \"cheese\", \"y\": 3}], }, ] self.assertEqual(expected,", "[\"y\"], \"resample_method\": \"asfreq\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0, 2.0,", "results = Mock() results.query = Mock() results.status = Mock() results.error_message", "5, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t2, \"value\": 8, \"key\":", "datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(NotImplementedError) as", "= {\"type\": \"metric\", \"value\": \"int\"} result = test_viz_deckgl.get_metrics() assert result", "[1, 2, 3] raw[None] = [10, 20, 30] df =", "= self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) data = test_viz.get_data(df) self.assertEqual([\"sum_value\"],", "viz.viz_types[\"paired_ttest\"](datasource, form_data) data = pairedTTestViz.get_data(df) # Check method correctly transforms", "> 5)\", query_obj[\"extras\"][\"having\"]) def test_adhoc_filters_overwrite_legacy_filters(self): form_data = { \"metrics\": [", "[\"x\", \"y\"] test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() class", "}, { \"key\": \"engineer\", \"values\": [{\"x\": \"pepperoni\", \"y\": 5}, {\"x\":", "len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) self.assertEqual( 1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"][0][\"children\"]) ) def test_get_data_calls_correct_method(self): test_viz = viz.PartitionViz(Mock(),", "expected_results = { \"latlong_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\",", "\"y\": 5}, {\"x\": \"cheese\", \"y\": 3}], }, ] self.assertEqual(expected, data)", "\"y\": 3}) def test_get_data_with_none(self): datasource = self.get_datasource_mock() df = pd.DataFrame(", "result == [\"int\"] form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data)", "{ \"values\": [ {\"x\": 100, \"y\": 1}, {\"x\": 200, \"y\":", "6.0, 10.0], ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\":", "{\"color\": None} def test_get_properties(self): mock_d = {} form_data = load_fixture(\"deck_path_form_data.json\")", "= { DTTM_ALIAS: 200.0, \"metric1\": 5.0, \"metric2\": 50.0, \"metric3\": 500.0,", "datasource.cache_timeout = 0 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(0, test_viz.cache_timeout) datasource.cache_timeout", "load_fixture(\"deck_geojson_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.DeckGeoJson(datasource, form_data) results =", "= { \"metrics\": [\"votes\"], \"adhoc_filters\": [], \"groupby\": [\"toppings\"], \"columns\": [\"role\"],", "8, 9], \"groupA\": [\"A\", \"B\", \"C\", \"C\"], \"groupB\": [\"x\", \"x\",", "{\"x\": 100, \"y\": 700}, {\"x\": 200, \"y\": 800}, {\"x\": 300,", "{\"x\": 300, \"y\": 30}, ], \"group\": (\"a1\", \"a2\", \"a3\"), },", "[\"toppings\"], \"columns\": [\"role\"], } datasource = self.get_datasource_mock() df = pd.DataFrame(", "= self.get_datasource_mock() df = pd.DataFrame( { \"toppings\": [\"cheese\", \"pepperoni\", \"cheese\",", "Mock(return_value=1) test_viz.nest_procs = Mock(return_value=1) test_viz.form_data[\"time_series_option\"] = \"adv_anal\" test_viz.get_data(df) self.assertEqual(1, len(test_viz.levels_for_time.mock_calls))", "\"y\": 60}, ], \"group\": (\"b1\", \"b2\", \"b3\"), }, { \"values\":", "groups = [\"groupA\", \"groupB\", \"groupC\"] test_viz = viz.PartitionViz(Mock(), {}) time_op", "300, \"y\": 300}, ], \"group\": (\"a1\", \"a2\", \"a3\"), }, {", "\"rolling_type\": \"mean\", \"rolling_periods\": 10, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(),", "governing permissions and limitations # under the License. # isort:skip_file", "self.assertFalse(query_obj[\"is_timeseries\"]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" query_obj = test_viz.query_obj() self.assertTrue(query_obj[\"is_timeseries\"]) def test_levels_for_computes_levels(self):", "1666 self.assertEqual(1666, test_viz.cache_timeout) datasource.database.cache_timeout = None test_viz = viz.BaseViz(datasource, form_data={})", "{\"a1\": 30, \"a2\": 35, \"a3\": 40}, } self.assertEqual(expected, data[\"records\"]) @patch(\"superset.viz.BaseViz.query_obj\")", "\"type\": \"DOUBLE\"}, }, \"avg__B\", ], } datasource = self.get_datasource_mock() df", "\"a2\", \"a3\"] df = pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource, form_data) data", "\"b2\", \"b3\"), }, { \"values\": [ {\"x\": 100, \"y\": 7},", "\"value1\", \"type\": \"DOUBLE\"}, }, \"avg__B\", ], } datasource = self.get_datasource_mock()", "[\"metric1\"], \"groupby\": [\"groupA\"]} test_viz = viz.RoseViz(Mock(), fd) test_viz.metrics = fd[\"metrics\"]", "datasource = self.get_datasource_mock() form_data = { \"all_columns\": [\"colA\", \"colB\", \"colC\"],", "data[\"values\"]) def test_groupby_nans(self): form_data = { \"metrics\": [\"count\"], \"adhoc_filters\": [],", "self.get_datasource_mock() raw = {} t1 = pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\")", "datasource.database.cache_timeout = 1666 self.assertEqual(1666, test_viz.cache_timeout) datasource.database.cache_timeout = None test_viz =", "= pd.DataFrame( { \"toppings\": [\"cheese\", \"pepperoni\", \"cheese\", \"pepperoni\"], \"role\": [\"engineer\",", "{u\"y\": 4, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid Basket\",), },", "= viz_instance.parse_coordinates(\"1.23, 3.21\") self.assertEqual(coord, (1.23, 3.21)) coord = viz_instance.parse_coordinates(\"1.23 3.21\")", "= load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with", "= \"table\" datasource.query = Mock(return_value=results) mock_dttm_col = Mock() datasource.get_column =", "query_obj = test_viz.query_obj() self.assertEqual( [\"sum__A\", \"count\", \"avg__C\", \"avg__B\", \"max__Y\"], query_obj[\"metrics\"]", "self.assertEqual(coord, (1.23, 3.21)) coord = viz_instance.parse_coordinates(\"1.23 3.21\") self.assertEqual(coord, (1.23, 3.21))", "\"comparator\": \"100\", }, { \"expressionType\": \"SIMPLE\", \"clause\": \"HAVING\", \"subject\": \"SUM(value1)\",", "\"x\", \"y\", \"z\"], } ) test_viz = viz.TableViz(datasource, form_data) data", "{\"x\": 200, \"y\": 800}, {\"x\": 300, \"y\": 900}, ], \"group\":", "def test_constructor_exception_no_datasource(self): form_data = {} datasource = None with self.assertRaises(Exception):", "u\"sum__SP_POP_TOTL\", u\"SUM(SE_PRM_NENR_MA)\", u\"SUM(SP_URB_TOTL)\", u\"count\", ] self.assertEqual(test_viz.metric_labels, expect_metric_labels) self.assertEqual(test_viz.all_metrics, expect_metric_labels) def", "[\"country_name\"], \"compare_lag\": \"10\", \"limit\": \"25\", \"datasource\": \"2__table\", \"table_timestamp_format\": \"%Y-%m-%d %H:%M:%S\",", "} ) self.assertEqual( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\": \"sum\", \"resample_rule\":", "2, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t2, \"value\": 5, \"key\":", "self.assertEqual(\"agg_mean\", test_viz.levels_for.mock_calls[2][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_diff\" test_viz.levels_for_diff = Mock(return_value=1) test_viz.get_data(df) self.assertEqual(\"point_diff\",", "\"WHERE\", \"subject\": \"value2\", \"operator\": \">\", \"comparator\": \"100\", }, { \"expressionType\":", "u\"SUM(SP_URB_TOTL)\", u\"count\", ] self.assertEqual(test_viz.metric_labels, expect_metric_labels) self.assertEqual(test_viz.all_metrics, expect_metric_labels) def test_get_df_returns_empty_df(self): form_data", "[\"groupA\", \"groupB\", \"groupC\"] levels = test_viz.levels_for(\"agg_sum\", groups, df) nest =", "\"clause\": \"WHERE\", \"sqlExpression\": \"value3 in ('North America')\", }, ], }", "test_viz.query_obj() self.assertEqual( [\"sum__A\", \"count\", \"avg__C\", \"avg__B\", \"max__Y\"], query_obj[\"metrics\"] ) def", "query_obj[\"extras\"][\"where\"]) self.assertEqual(\"(SUM(value1) > 5)\", query_obj[\"extras\"][\"having\"]) def test_adhoc_filters_overwrite_legacy_filters(self): form_data = {", "\"sum__SP_POP_TOTL\", \"granularity_sqla\": \"year\", \"page_length\": 0, \"all_columns\": [], \"viz_type\": \"table\", \"since\":", "\">\"}], query_obj[\"filter\"] ) self.assertEqual([], query_obj[\"extras\"][\"having_druid\"]) self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"])", "{\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"count\", \"avg__C\", ], \"percent_metrics\": [", "\"aggregate\": \"SUM\", \"label\": \"sum_value\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }", "df) self.assertEqual(4, len(levels)) expected = {DTTM_ALIAS: 1800, \"metric1\": 45, \"metric2\":", "mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data) test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) assert", "raw[\"metric1\"] = [1, 2, 3, 4, 5, 6, 7, 8,", "form_data) data = pairedTTestViz.get_data(df) # Check method correctly transforms data", "\"colB\", \"colC\"], \"order_by_cols\": ['[\"colA\", \"colB\"]', '[\"colC\"]'], } super_query_obj.return_value = {", "\"markup_type\": \"markdown\", \"where\": \"\", \"compare_suffix\": \"o10Y\", } datasource = Mock()", "test_viz.get_data(df) self.assertEqual(\"agg_mean\", test_viz.levels_for.mock_calls[2][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_diff\" test_viz.levels_for_diff = Mock(return_value=1) test_viz.get_data(df)", "t1.strftime(time_format): {\"sum__A\": 15, \"count\": 6}, t2.strftime(time_format): {\"sum__A\": 20, \"count\": 7},", "\"value\": 7, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], 1009843200000000000: [ {\"time\":", "{ \"values\": [ {\"x\": 100, \"y\": 7}, {\"x\": 200, \"y\":", "= pd.DataFrame( { \"SUM(value1)\": [15, 20, 25, 40], \"avg__B\": [10,", "+= [\"groupC\"] self.assertEqual(sorted(cols), sorted(levels[3].columns.tolist())) self.assertEqual(4, len(test_viz.process_data.mock_calls)) def test_nest_values_returns_hierarchy(self): raw =", "in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource,", "self.assertEqual(0, test_viz.cache_timeout) datasource.database.cache_timeout = 1666 self.assertEqual(1666, test_viz.cache_timeout) datasource.database.cache_timeout = None", "False, }, { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\":", "9, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], } self.assertEqual(expected, res) class", "[ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\",", "\"delimited_key\", \"geohash_key\"]: mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data) test_viz_deckgl.process_spatial_query_obj(mock_key,", "= self.get_datasource_mock() df = pd.DataFrame( { \"SUM(value1)\": [15, 20, 25,", "44], \"count\": [6, 7, 8, 9], \"groupA\": [\"A\", \"B\", \"C\",", "= Mock(side_effect=return_args) levels = test_viz.levels_for_time(groups, df) self.assertEqual(4, len(levels)) cols =", "load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_key = \"spatial_key\" mock_gb = []", "300, \"y\": 900}, ], \"group\": (\"c1\", \"c2\", \"c3\"), }, ],", "levels[3].index.names) def test_levels_for_diff_computes_difference(self): raw = {} raw[DTTM_ALIAS] = [100, 200,", "t1, \"value\": 7, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], 1009843200000000000: [", "viz.TableViz(datasource, form_data) test_viz.should_be_timeseries() def test_adhoc_metric_with_sortby(self): metrics = [ { \"expressionType\":", "5\", } datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) query_obj", "\"sum\", \"rolling_periods\": 2, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0,", "def run_test(metric): form_data[\"timeseries_limit_metric\"] = metric test_viz = viz.TableViz(datasource, form_data) query_obj", "import superset.viz as viz from superset import app from superset.constants", "[], \"groupby\": [\"toppings\"], \"columns\": [], } datasource = self.get_datasource_mock() df", "(\"a1\", \"a2\", \"a3\"), }, { \"values\": [ {\"x\": 100, \"y\":", "= {\"metric1\": 6, \"metric2\": 60, \"metric3\": 600} self.assertEqual(expected, levels[0].to_dict()) expected", "df = pd.DataFrame(raw) test_viz = viz.NVD3TimeSeriesViz(datasource, form_data) viz_data = {}", "}, { \"values\": [ {\"x\": 100, \"y\": 40}, {\"x\": 200,", "= self.get_datasource_mock() raw = {} t1 = pd.Timestamp(\"2000\") t2 =", "{\"groupby\": groups}) def return_args(df_drop, aggregate): return df_drop test_viz.process_data = Mock(side_effect=return_args)", "NULL\", \"subject\": \"lat\", \"isExtra\": False, }, { \"clause\": \"WHERE\", \"expressionType\":", "with self.assertRaises(Exception): viz.BaseViz(datasource, form_data) def test_process_metrics(self): # test TableViz metrics", "\"%Y-%m-%d\" result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 0,", "= viz.TableViz(datasource, form_data) test_viz.query_obj() del form_data[\"metrics\"] form_data[\"groupby\"] = [\"B\", \"C\"]", "= viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() form_data[\"metrics\"] = [\"x\", \"y\"]", "\"y\": 30}, {\"x\": \"2.0\", \"y\": 29}, {\"x\": NULL_STRING, \"y\": 3},", "{\"x\": \"1.0\", \"y\": 42}, {\"x\": \"0.0\", \"y\": 30}, {\"x\": \"2.0\",", "from superset.utils.core import DTTM_ALIAS from .base_tests import SupersetTestCase from .utils", "form_data) test_viz.query_obj() del form_data[\"metrics\"] form_data[\"groupby\"] = [\"B\", \"C\"] with self.assertRaises(Exception):", "0.4, \"%avg__B\": 0.3, }, ] self.assertEqual(expected, data[\"records\"]) def test_parse_adhoc_filters(self): form_data", "\"values\": [{\"x\": \"pepperoni\", \"y\": 2}, {\"x\": \"cheese\", \"y\": 1}], },", "import app from superset.constants import NULL_STRING from superset.exceptions import SpatialException", "datasource = self.get_datasource_mock() form_data = {\"all_columns\": [\"A\", \"B\"], \"metrics\": [\"x\",", "query_obj[\"orderby\"]) run_test(\"simple_metric\") run_test( { \"label\": \"adhoc_metric\", \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\",", "\"groupC\"] test_viz = viz.PartitionViz(Mock(), {\"groupby\": groups}) def return_args(df_drop, aggregate): return", "{\"a1\": 60, \"b1\": 150, \"c1\": 240}, \"metric3\": {\"a1\": 600, \"b1\":", "\"metric3\": [ { \"values\": [ {\"x\": 100, \"y\": 100}, {\"x\":", "\"key\": NULL_STRING, \"values\": [{\"x\": \"pepperoni\", \"y\": 2}, {\"x\": \"cheese\", \"y\":", "result == [] def test_scatterviz_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource =", "test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj() @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_merges_all_columns(self, super_query_obj): datasource", "= 1666 self.assertEqual(1666, test_viz.cache_timeout) datasource.database.cache_timeout = None test_viz = viz.BaseViz(datasource,", "2}, {\"x\": \"cheese\", \"y\": 1}], }, { \"key\": \"engineer\", \"values\":", "self.assertEqual(expected_values, data[\"values\"]) def test_column_nulls(self): form_data = { \"metrics\": [\"votes\"], \"adhoc_filters\":", "TimeSeriesTableVizTestCase(SupersetTestCase): def test_get_data_metrics(self): form_data = {\"metrics\": [\"sum__A\", \"count\"], \"groupby\": []}", "len(levels)) expected = {DTTM_ALIAS: 1800, \"metric1\": 45, \"metric2\": 450, \"metric3\":", "[] test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(ValueError) as context: test_viz_deckgl.process_spatial_query_obj(mock_key,", "Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid Basket\", \"Real Madrid", "0, \"all_columns\": [], \"viz_type\": \"table\", \"since\": \"2014-01-01\", \"until\": \"2014-01-02\", \"metrics\":", "test_viz.levels_for.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_mean\" test_viz.get_data(df) self.assertEqual(\"agg_mean\", test_viz.levels_for.mock_calls[2][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_diff\"", "# \"License\"); you may not use this file except in", "\"SUM(value1)\": [15, 20, 25, 40], \"avg__B\": [10, 20, 5, 15],", "5)\", query_obj[\"extras\"][\"having\"]) def test_adhoc_filters_overwrite_legacy_filters(self): form_data = { \"metrics\": [ {", "df = pd.DataFrame({\"SUM(value1)\": [15], \"sum_value\": [15]}) datasource = self.get_datasource_mock() test_viz", "70}, {\"x\": 200, \"y\": 80}, {\"x\": 300, \"y\": 90}, ],", "== adhoc_filters class TimeSeriesVizTestCase(SupersetTestCase): def test_timeseries_unicode_data(self): datasource = self.get_datasource_mock() form_data", "form_data = {\"groupby\": [\"name\"], \"metrics\": [\"sum__payout\"]} raw = {} raw[\"name\"]", "[{\"x\": \"pepperoni\", \"y\": 2}, {\"x\": \"cheese\", \"y\": 1}], }, {", "pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS) ) datasource.offset", "[\"y\"], \"rolling_type\": \"cumsum\", \"rolling_periods\": 0, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"]", "\"agg_mean\" levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected =", "[ {\"x\": 100, \"y\": 1}, {\"x\": 200, \"y\": 2}, {\"x\":", "3): self.assertEqual(\"metric\" + str(i + 1), nest[i][\"name\"]) self.assertEqual(None, nest[i].get(\"val\")) self.assertEqual(3,", "\"colB\"], [\"colC\"]], query_obj[\"orderby\"]) def test_query_obj_uses_sortby(self): datasource = self.get_datasource_mock() form_data =", "self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual( [{\"col\":", "data = test_viz.get_data(df) expected = [ { \"key\": NULL_STRING, \"values\":", "200, \"b1\": 500, \"c1\": 800}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"],", "viz.PartitionViz(Mock(), {}) df = Mock() with self.assertRaises(ValueError): test_viz.get_data(df) test_viz.levels_for =", "], 1072915200000000000: [ {\"time\": t3, \"value\": 3, \"key\": (\"a1\",), \"name\":", "\"c1\": 240}, \"metric3\": {\"a1\": 600, \"b1\": 1500, \"c1\": 2400}, }", "{ \"all_columns\": [\"colA\", \"colB\", \"colC\"], \"order_by_cols\": ['[\"colA\", \"colB\"]', '[\"colC\"]'], }", "\"table_timestamp_format\": \"%Y-%m-%d %H:%M:%S\", \"markup_type\": \"markdown\", \"where\": \"\", \"compare_suffix\": \"o10Y\", }", "writing, # software distributed under the License is distributed on", "{\"x\": 200, \"y\": 5}, {\"x\": 300, \"y\": 6}, ], \"group\":", "np.testing.assert_equal( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\": \"asfreq\", \"resample_rule\": \"1D\"}, )", "{ DTTM_ALIAS: {\"a1\": 200, \"c1\": 200, \"b1\": 200}, \"metric1\": {\"a1\":", "expected = { DTTM_ALIAS: {\"a1\": 200, \"c1\": 200, \"b1\": 200},", "{} query_obj = test_viz.query_obj() self.assertFalse(query_obj[\"is_timeseries\"]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" query_obj =", "viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() form_data[\"metrics\"] = [\"x\", \"y\"] test_viz", "\"25\", \"datasource\": \"2__table\", \"table_timestamp_format\": \"%Y-%m-%d %H:%M:%S\", \"markup_type\": \"markdown\", \"where\": \"\",", "\"c2\", \"c2\"] raw[\"groupC\"] = [\"a3\", \"a3\", \"a3\", \"b3\", \"b3\", \"b3\",", "self.assertEqual(expected, levels[0].to_dict()) expected = { \"metric1\": {\"a1\": 2, \"b1\": 2,", "= pd.DataFrame(raw) test_viz = viz.NVD3TimeSeriesViz(datasource, form_data) viz_data = {} viz_data", "len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) self.assertEqual( 1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"][0][\"children\"]) ) def test_get_data_calls_correct_method(self): test_viz", "levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected = {", "\"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 6.0, 10.0],", "\"pepperoni\", \"y\": 5}, {\"x\": \"cheese\", \"y\": 3}, {\"x\": NULL_STRING, \"y\":", "= { t1.strftime(time_format): {\"a1\": 15, \"a2\": 20, \"a3\": 25}, t2.strftime(time_format):", "150, \"c1\": 240}, \"metric3\": {\"a1\": 600, \"b1\": 1500, \"c1\": 2400},", "Mock() datasource = Mock() datasource.type = \"table\" datasource.query = Mock(return_value=results)", "[ { \"expressionType\": \"SIMPLE\", \"clause\": \"WHERE\", \"subject\": \"value2\", \"operator\": \">\",", "123} query_obj = {\"granularity\": \"day\"} datasource = self.get_datasource_mock() test_viz =", "\"a2\", \"a3\"), }, { \"values\": [ {\"x\": 100, \"y\": 4},", "100}, {\"x\": 200, \"y\": 200}, {\"x\": 300, \"y\": 300}, ],", "0.1, }, { \"groupA\": \"C\", \"groupB\": \"z\", \"SUM(value1)\": 40, \"count\":", "}, ], \"delimited_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\":", "\"geohashCol\": \"geo\"}, } datasource = self.get_datasource_mock() expected_results = { \"latlong_key\":", "0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 6.0, 10.0], )", "NULL\", \"subject\": \"geo\", \"isExtra\": False, } ], } for mock_key", "# # Unless required by applicable law or agreed to", "pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS) ) datasource.offset = 1", "Version 2.0 (the # \"License\"); you may not use this", "\"y\": 1}, {\"x\": 200, \"y\": 2}, {\"x\": 300, \"y\": 3},", "self.assertEqual(viz_instance.parse_coordinates(\"\"), None) def test_parse_coordinates_raises(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock()", "test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(app.config[\"CACHE_DEFAULT_TIMEOUT\"], test_viz.cache_timeout) class TableVizTestCase(SupersetTestCase): def test_get_data_applies_percentage(self):", "one # or more contributor license agreements. See the NOTICE", "df_drop = df.drop(groups[i:], 1) pivot = df_drop.pivot_table( index=DTTM_ALIAS, columns=groups[:i], values=metrics", "Mock(return_value=mock_dttm_col) mock_dttm_col.python_date_format = \"epoch_ms\" result = test_viz.get_df(query_obj) import logging logger.info(result)", "], 1009843200000000000: [ {\"time\": t2, \"value\": 2, \"key\": (\"a1\",), \"name\":", "# isort:skip_file import uuid from datetime import datetime import logging", "[\"groupC\"] self.assertEqual(sorted(cols), sorted(levels[3].columns.tolist())) self.assertEqual(4, len(test_viz.process_data.mock_calls)) def test_nest_values_returns_hierarchy(self): raw = {}", "= pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t1, t1, t2, t2, t2]", "\"a1\", \"a2\", \"a3\"] df = pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource, form_data)", "form_data={}) self.assertEqual(156, test_viz.cache_timeout) datasource.cache_timeout = None datasource.database.cache_timeout = 0 self.assertEqual(0,", "= test_viz.get_data(df) # Check method correctly transforms data self.assertEqual(set([\"a1\", \"a2\",", "u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 2, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid", "\"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), data={\"y\": [1.0, 2.0, 3.0, 4.0]}, )", "self.get_datasource_mock() form_data = {} test_viz = viz.PartitionViz(datasource, form_data) super_query_obj.return_value =", "test_viz_deckgl.parse_coordinates(\"NULL\") with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"fldkjsalkj,fdlaskjfjadlksj\") @patch(\"superset.utils.core.uuid.uuid4\") def test_filter_nulls(self, mock_uuid4): mock_uuid4.return_value =", "result = test_viz_deckgl.get_metrics() assert result == [] def test_get_js_columns(self): form_data", "[\"cheese\", \"pepperoni\", \"anchovies\", None], \"votes\": [3, 5, 1, 2], }", "self.assertTrue(\"\" in str(context.exception)) def test_process_spatial_query_obj(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource =", "+ 1), nest[i][\"name\"]) self.assertEqual(None, nest[i].get(\"val\")) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(3, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1,", "test_viz_deckgl.get_properties(mock_d) self.assertTrue(\"\" in str(context.exception)) def test_process_spatial_query_obj(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource", "\"lat\"}, \"delimited_key\": {\"type\": \"delimited\", \"lonlatCol\": \"lonlat\"}, \"geohash_key\": {\"type\": \"geohash\", \"geohashCol\":", "results.error_message = Mock() datasource = Mock() datasource.type = \"table\" datasource.query", "\"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lat\", \"isExtra\": False,", "(1.23, 3.21)) coord = viz_instance.parse_coordinates(\"1.23 3.21\") self.assertEqual(coord, (1.23, 3.21)) self.assertEqual(viz_instance.parse_coordinates(None),", "= viz.NVD3TimeSeriesViz(datasource, form_data) viz_data = {} viz_data = test_viz.get_data(df) expected", "expected = { \"N/A\": [ { \"values\": [ {\"x\": 100,", "40] raw[\"groupby1\"] = [\"a1\", \"a2\", \"a3\", \"a1\", \"a2\", \"a3\"] df", "NOTICE file # distributed with this work for additional information", "= test_viz.query_obj() self.assertEqual( [\"sum__A\", \"count\", \"avg__C\", \"avg__B\", \"max__Y\"], query_obj[\"metrics\"] )", "800, 900] df = pd.DataFrame(raw) pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource, form_data) data", "test_query_obj_throws_columns_and_metrics(self): datasource = self.get_datasource_mock() form_data = {\"all_columns\": [\"A\", \"B\"], \"metrics\":", "this file except in compliance # with the License. You", "self.assertEqual( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\": \"sum\", \"resample_rule\": \"1D\"}, )", "(\"c1\",)}, ], 1072915200000000000: [ {\"time\": t3, \"value\": 3, \"key\": (\"a1\",),", "t1 = pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") t3 = pd.Timestamp(\"2004\") raw[DTTM_ALIAS]", "], \"adhoc_filters\": [ { \"expressionType\": \"SIMPLE\", \"clause\": \"WHERE\", \"subject\": \"value2\",", "200}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual(4, len(levels)) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names)", "], \"group\": (\"c1\", \"c2\", \"c3\"), }, ], \"metric3\": [ {", "return df_drop test_viz.process_data = Mock(side_effect=return_args) levels = test_viz.levels_for_time(groups, df) self.assertEqual(4,", "946684800000000000: [ {\"time\": t1, \"value\": 1, \"key\": (\"a1\",), \"name\": (\"a1\",)},", "\"metric3\": 500.0, } self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS: {\"a1\":", "\"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, 5.0, 7.0], }", "\"role\": [\"engineer\", \"engineer\", None, None], \"votes\": [3, 5, 1, 2],", "= [\"a1\", \"a2\", \"a3\", \"a1\", \"a2\", \"a3\"] df = pd.DataFrame(raw)", "\"count\": 6, \"avg__C\": 11, \"%SUM(value1)\": 0.15, \"%avg__B\": 0.2, }, {", "raw[DTTM_ALIAS] = [t1, t1, t1, t2, t2, t2] raw[\"sum__A\"] =", "run_test( { \"label\": \"adhoc_metric\", \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"column\": {\"column_name\":", "class TimeSeriesVizTestCase(SupersetTestCase): def test_timeseries_unicode_data(self): datasource = self.get_datasource_mock() form_data = {\"groupby\":", "= pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01 05:00:00\"]}) datasource.offset = 0 mock_dttm_col = Mock()", "\"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, 5.0, 7.0], } )", "data = pairedTTestViz.get_data(df) # Check method correctly transforms data expected", "test_adhoc_filters_overwrite_legacy_filters(self): form_data = { \"metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\":", "= viz.BaseViz(datasource, form_data) test_viz.df_metrics_to_num = Mock() test_viz.get_fillna_for_columns = Mock(return_value=0) results.df", "form_data = { \"metrics\": [\"count\"], \"adhoc_filters\": [], \"groupby\": [\"beds\"], \"columns\":", "\"toppings\": [\"cheese\", \"pepperoni\", \"anchovies\", None], \"votes\": [3, 5, 1, 2],", "40}, } self.assertEqual(expected, data[\"records\"]) @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_throws_metrics_and_groupby(self, super_query_obj): datasource =", "self.assertEqual( [{\"col\": \"value2\", \"val\": \"100\", \"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual(", "\"groupA\", \"groupB\", \"SUM(value1)\", \"count\", \"avg__C\", \"%SUM(value1)\", \"%avg__B\", ], list(data[\"columns\"]), )", "\"%avg__B\": 0.1, }, { \"groupA\": \"C\", \"groupB\": \"z\", \"SUM(value1)\": 40,", "\"avg__C\", \"%SUM(value1)\", \"%avg__B\", ], list(data[\"columns\"]), ) expected = [ {", "= load_fixture(\"deck_geojson_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.DeckGeoJson(datasource, form_data) results", "\"sqlExpression\": \"value3 in ('North America')\", }, ], \"having\": \"SUM(value1) >", "\"asfreq\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0, 2.0, np.nan, np.nan,", "(\"c1\",), \"name\": (\"c1\",)}, ], 1009843200000000000: [ {\"time\": t2, \"value\": 2,", "viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"count\", data[\"key\"]) expected_values = [", "[1.0, 2.0, 0.0, 0.0, 5.0, 0.0, 7.0], ) np.testing.assert_equal( viz.NVD3TimeSeriesViz(", "from .base_tests import SupersetTestCase from .utils import load_fixture logger =", "self.assertEqual(1666, test_viz.cache_timeout) datasource.database.cache_timeout = None test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(app.config[\"CACHE_DEFAULT_TIMEOUT\"],", "[15, 20, 25, 40], \"avg__B\": [10, 20, 5, 15], \"avg__C\":", "\"B\", \"C\", \"C\"], \"groupB\": [\"x\", \"x\", \"y\", \"z\"], } )", "Mock(side_effect=return_args) levels = test_viz.levels_for_time(groups, df) self.assertEqual(4, len(levels)) cols = [DTTM_ALIAS,", "= { \"columns\": [\"colD\", \"colC\"], \"groupby\": [\"colA\", \"colB\"], } test_viz", "query_obj[\"extras\"][\"having\"]) def test_adhoc_filters_overwrite_legacy_filters(self): form_data = { \"metrics\": [ { \"expressionType\":", "viz.DeckGeoJson(datasource, form_data) results = test_viz_deckgl.query_obj() assert results[\"metrics\"] == [] assert", "not use this file except in compliance # with the", "1}], }, { \"key\": \"engineer\", \"values\": [{\"x\": \"pepperoni\", \"y\": 5},", "\"b2\", \"b2\", \"b2\", \"c2\", \"c2\", \"c2\"] raw[\"groupC\"] = [\"a3\", \"a3\",", "= self.get_datasource_mock() df = pd.DataFrame({\"beds\": [0, 1, nan, 2], \"count\":", "} datasource = Mock() datasource.type = \"table\" test_viz = viz.BaseViz(datasource,", "= \"%Y-%m-%d\" result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1,", "{ u\"values\": [ {u\"y\": 4, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 4, u\"x\":", "def test_get_data_empty_null_keys(self): form_data = {\"groupby\": [], \"metrics\": [\"\", None]} datasource", "Unless required by applicable law or agreed to in writing,", "3}, ], \"group\": (\"a1\", \"a2\", \"a3\"), }, { \"values\": [", "datasource = self.get_datasource_mock() viz_instance = viz.BaseDeckGLViz(datasource, form_data) coord = viz_instance.parse_coordinates(\"1.23,", "pd.DataFrame(raw) groups = [\"groupA\", \"groupB\", \"groupC\"] time_op = \"agg_sum\" test_viz", "df.drop(groups[i:], 1) pivot = df_drop.pivot_table( index=DTTM_ALIAS, columns=groups[:i], values=metrics ) procs[i]", "\"metric3\"] self.assertEqual(sorted(cols), sorted(levels[0].columns.tolist())) cols += [\"groupA\"] self.assertEqual(sorted(cols), sorted(levels[1].columns.tolist())) cols +=", "\"y\": 3}], }, ] self.assertEqual(expected, data) class PairedTTestTestCase(SupersetTestCase): def test_get_data_transforms_dataframe(self):", "= {\"groupby\": [\"name\"], \"metrics\": [\"sum__payout\"]} raw = {} raw[\"name\"] =", "test_viz = viz.TableViz(datasource, form_data) test_viz.should_be_timeseries() def test_adhoc_metric_with_sortby(self): metrics = [", "pd.DataFrame(raw) fd = {\"metrics\": [\"metric1\"], \"groupby\": [\"groupA\"]} test_viz = viz.RoseViz(Mock(),", "def test_scatterviz_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() form_data =", "import uuid from datetime import datetime import logging from math", "= {} t1 = pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") raw[DTTM_ALIAS] =", "(\"a1\",)}, {\"time\": t3, \"value\": 6, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\":", "\"all_columns\": [], \"viz_type\": \"table\", \"since\": \"2014-01-01\", \"until\": \"2014-01-02\", \"metrics\": [\"sum__SP_POP_TOTL\",", "\"expressionType\": \"SQL\", \"clause\": \"HAVING\", \"sqlExpression\": \"SUM(value1) > 5\", }, {", "test_viz = viz.PartitionViz(Mock(), {}) groups = [\"groupA\", \"groupB\", \"groupC\"] levels", "= [ u\"sum__SP_POP_TOTL\", u\"SUM(SE_PRM_NENR_MA)\", u\"SUM(SP_URB_TOTL)\", u\"count\", ] self.assertEqual(test_viz.metric_labels, expect_metric_labels) self.assertEqual(test_viz.all_metrics,", "= pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t2] raw[\"sum__A\"]", "def test_should_be_timeseries_raises_when_no_granularity(self): datasource = self.get_datasource_mock() form_data = {\"include_time\": True} with", "\"value\": 3, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t3, \"value\": 6,", "self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"cumsum\", \"rolling_periods\": 0,", "\"limit\": \"25\", \"datasource\": \"2__table\", \"table_timestamp_format\": \"%Y-%m-%d %H:%M:%S\", \"markup_type\": \"markdown\", \"where\":", "== mock_gb def test_geojson_query_obj(self): form_data = load_fixture(\"deck_geojson_form_data.json\") datasource = self.get_datasource_mock()", "test_get_data_with_none(self): datasource = self.get_datasource_mock() df = pd.DataFrame( data={ DTTM_ALIAS: pd.to_datetime(", "= viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual( [\"sum__A\", \"count\", \"avg__C\",", "self.assertEqual(set([\"a1\", \"a2\", \"a3\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\" expected =", "} self.assertEqual(expected, levels[1].to_dict()) self.assertEqual(4, len(levels)) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def", "False, }, ], \"delimited_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\",", "[\"sum__SP_POP_TOTL\", \"SUM(SE_PRM_NENR_MA)\", \"SUM(SP_URB_TOTL)\"], \"country_fieldtype\": \"cca3\", \"percent_metrics\": [\"count\"], \"slice_id\": 74, \"time_grain_sqla\":", "test_viz.nest_values = Mock(return_value=1) test_viz.form_data[\"groupby\"] = [\"groups\"] test_viz.form_data[\"time_series_option\"] = \"not_time\" test_viz.get_data(df)", "= pd.DataFrame(raw) groups = [\"groupA\", \"groupB\", \"groupC\"] test_viz = viz.PartitionViz(Mock(),", "\"subject\": \"lonlat\", \"isExtra\": False, } ], \"geohash_key\": [ { \"clause\":", "{\"x\": 100, \"y\": 70}, {\"x\": 200, \"y\": 80}, {\"x\": 300,", "3.0, 5.0, 7.0], ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"],", "viz.BaseViz(datasource, form_data={}) self.assertEqual(0, test_viz.cache_timeout) datasource.cache_timeout = 156 test_viz = viz.BaseViz(datasource,", "= [ {\"x\": \"pepperoni\", \"y\": 5}, {\"x\": \"cheese\", \"y\": 3},", "tests.test_app import superset.viz as viz from superset import app from", "form_data[\"groupby\"] = [\"B\", \"C\"] with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data)", "False, } ], \"geohash_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\",", "df) self.assertEqual(4, len(levels)) expected = { DTTM_ALIAS: 200.0, \"metric1\": 5.0,", "\"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, None, 4.0], }", "datasource = self.get_datasource_mock() form_data = { \"metrics\": [\"sum__A\", \"count\", \"avg__C\"],", "test_viz.nest_values(levels) self.assertEqual(3, len(nest)) for i in range(0, 3): self.assertEqual(\"metric\" +", "\"geohash_key\"]: test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data.copy()) test_viz_deckgl.spatial_control_keys = [mock_key] test_viz_deckgl.add_null_filters() adhoc_filters", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "raw = {} raw[\"name\"] = [ \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real", "expected = { 946684800000000000: [ {\"time\": t1, \"value\": 1, \"key\":", "form_data) result = test_viz_deckgl.get_metrics() assert result == [] def test_scatterviz_get_metrics(self):", "= 0 mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col) mock_dttm_col.python_date_format =", "40], \"avg__B\": [10, 20, 5, 15], \"avg__C\": [11, 22, 33,", "0.2, \"%avg__B\": 0.4, }, { \"groupA\": \"C\", \"groupB\": \"y\", \"SUM(value1)\":", "data = test_viz.get_data(df) self.assertEqual([\"sum_value\"], data[\"columns\"]) class DistBarVizTestCase(SupersetTestCase): def test_groupby_nulls(self): form_data", "\"a3\", \"a3\", \"b3\", \"b3\", \"b3\", \"c3\", \"c3\", \"c3\"] raw[\"metric1\"] =", "t1, t2, t2, t2] raw[\"sum__A\"] = [15, 20, 25, 30,", "{ \"metrics\": [\"sum__A\", \"count\", \"avg__C\"], \"percent_metrics\": [\"sum__A\", \"avg__B\", \"max__Y\"], }", "[\"groupA\", \"groupB\", \"groupC\"], \"metrics\": [\"metric1\", \"metric2\", \"metric3\"], } datasource =", "pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01\"]}) mock_dttm_col.python_date_format = \"%Y-%m-%d\" result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS],", "self.assertRaises(ValueError) as context: test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) self.assertTrue(\"Bad spatial key\" in str(context.exception))", "100, \"y\": 40}, {\"x\": 200, \"y\": 50}, {\"x\": 300, \"y\":", "form_data) super_query_obj.return_value = {} query_obj = test_viz.query_obj() self.assertFalse(query_obj[\"is_timeseries\"]) test_viz.form_data[\"time_series_option\"] =", "time_op = \"point_diff\" levels = test_viz.levels_for_diff(time_op, groups, df) expected =", "= test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected = {DTTM_ALIAS: 1800,", "patch import numpy as np import pandas as pd import", "name=DTTM_ALIAS) ) mock_dttm_col.python_date_format = None result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS],", "= pd.DataFrame( { \"toppings\": [\"cheese\", \"pepperoni\", \"anchovies\", None], \"votes\": [3,", "\"a3\"), }, { \"values\": [ {\"x\": 100, \"y\": 4}, {\"x\":", "\"b2\", \"b3\"), }, { \"values\": [ {\"x\": 100, \"y\": 700},", "{ \"label\": \"adhoc_metric\", \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"column\": {\"column_name\": \"sort_column\",},", "form_data) with self.assertRaises(NotImplementedError) as context: test_viz_deckgl.get_properties(mock_d) self.assertTrue(\"\" in str(context.exception)) def", "0, 0)], name=DTTM_ALIAS) ) def test_cache_timeout(self): datasource = self.get_datasource_mock() datasource.cache_timeout", "\"y\": 3}, ], \"group\": \"All\", } ], \"NULL\": [ {", "= [ { \"groupA\": \"A\", \"groupB\": \"x\", \"SUM(value1)\": 15, \"count\":", "Check method correctly transforms data expected = { \"metric1\": [", "25, \"count\": 8, \"avg__C\": 33, \"%SUM(value1)\": 0.25, \"%avg__B\": 0.1, },", "@patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_time_series_option(self, super_query_obj): datasource = self.get_datasource_mock() form_data = {}", "= self.get_datasource_mock() form_data = { \"metrics\": [\"colA\", \"colB\"], \"order_desc\": False,", "0.2, }, { \"groupA\": \"B\", \"groupB\": \"x\", \"SUM(value1)\": 20, \"count\":", "= {} t1 = pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") t3 =", "\"%SUM(value1)\": 0.2, \"%avg__B\": 0.4, }, { \"groupA\": \"C\", \"groupB\": \"y\",", "len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) def test_nest_procs_returns_hierarchy(self): raw = {} raw[DTTM_ALIAS] = [100, 200,", "4.0], } ) data = viz.BigNumberViz(datasource, {\"metrics\": [\"y\"]}).get_data(df) assert np.isnan(data[2][\"y\"])", "= test_viz.nest_values(levels) self.assertEqual(3, len(nest)) for i in range(0, 3): self.assertEqual(\"metric\"", "\"y\": 8}, {\"x\": 300, \"y\": 9}, ], \"group\": (\"c1\", \"c2\",", "{\"groupby\": [], \"metrics\": [\"\", None]} datasource = self.get_datasource_mock() # Test", "test_viz.get_df(query_obj) self.assertEqual(type(result), pd.DataFrame) self.assertTrue(result.empty) def test_get_df_handles_dttm_col(self): form_data = {\"dummy\": 123}", "# Test data raw = {} raw[DTTM_ALIAS] = [100, 200,", "(\"b1\", \"b2\", \"b3\"), }, { \"values\": [ {\"x\": 100, \"y\":", "[\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, 5.0, 7.0],", "form_data = {} datasource = None with self.assertRaises(Exception): viz.BaseViz(datasource, form_data)", "\"datasource\": \"2__table\", \"table_timestamp_format\": \"%Y-%m-%d %H:%M:%S\", \"markup_type\": \"markdown\", \"where\": \"\", \"compare_suffix\":", "Check method correctly transforms data self.assertEqual(set([\"a1\", \"a2\", \"a3\"]), set(data[\"columns\"])) time_format", "pivot = df_drop.pivot_table( index=DTTM_ALIAS, columns=groups[:i], values=metrics ) procs[i] = pivot", "{\"metrics\": [\"metric1\"], \"groupby\": [\"groupA\"]} test_viz = viz.RoseViz(Mock(), fd) test_viz.metrics =", "data raw = {} raw[DTTM_ALIAS] = [100, 200, 300, 100,", "# test TableViz metrics in correct order form_data = {", "\"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"geo\", \"isExtra\":", "\"groupby\": [\"groupA\", \"groupB\"], \"metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\",", "1}, ] self.assertEqual(expected_values, data[\"values\"]) def test_groupby_nans(self): form_data = { \"metrics\":", "\"columns\": [], } datasource = self.get_datasource_mock() df = pd.DataFrame({\"beds\": [0,", "200, 300] raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\", \"b1\", \"b1\",", "\"sum_value\": [15]}) datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) data", "test_viz.levels_for.mock_calls[2][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_diff\" test_viz.levels_for_diff = Mock(return_value=1) test_viz.get_data(df) self.assertEqual(\"point_diff\", test_viz.levels_for_diff.mock_calls[0][1][0])", "{ \"metrics\": [\"y\"], \"rolling_type\": \"mean\", \"rolling_periods\": 10, \"min_periods\": 0, },", "Licensed to the Apache Software Foundation (ASF) under one #", "\"groupC\"] time_op = \"agg_sum\" test_viz = viz.PartitionViz(Mock(), {}) levels =", "viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"NULL\") with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"fldkjsalkj,fdlaskjfjadlksj\") @patch(\"superset.utils.core.uuid.uuid4\") def", "{} datasource = None with self.assertRaises(Exception): viz.BaseViz(datasource, form_data) def test_process_metrics(self):", "= { \"metric1\": [ { \"values\": [ {\"x\": 100, \"y\":", "\"a2\", \"a2\", \"b2\", \"b2\", \"b2\", \"c2\", \"c2\", \"c2\"] raw[\"groupC\"] =", "{ DTTM_ALIAS: 200.0, \"metric1\": 5.0, \"metric2\": 50.0, \"metric3\": 500.0, }", "str(context.exception)) test_form_data = { \"latlong_key\": {\"type\": \"latlong\", \"lonCol\": \"lon\", \"latCol\":", "\"2019-01-07\"] ), data={\"y\": [1.0, 2.0, 3.0, 4.0]}, ) self.assertEqual( viz.BigNumberViz(", "{\"groupby\": [\"name\"], \"metrics\": [\"sum__payout\"]} raw = {} raw[\"name\"] = [", "\"SUM\", \"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, } ],", ".tolist(), [1.0, 1.5, 2.0, 2.5], ) class BigNumberVizTestCase(SupersetTestCase): def test_get_data(self):", "0)], name=DTTM_ALIAS) ) datasource.offset = 0 results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01\"]})", "data) class PairedTTestTestCase(SupersetTestCase): def test_get_data_transforms_dataframe(self): form_data = { \"groupby\": [\"groupA\",", "\"value2\", \"operator\": \">\", \"comparator\": \"100\", }, { \"expressionType\": \"SQL\", \"clause\":", "NULL_STRING, \"y\": 3}, ] self.assertEqual(expected_values, data[\"values\"]) def test_column_nulls(self): form_data =", "[\"lon\", \"lat\"], \"delimited_key\": [\"lonlat\"], \"geohash_key\": [\"geo\"], } for mock_key in", "} datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) query_obj =", "\"colC\"], \"order_by_cols\": ['[\"colA\", \"colB\"]', '[\"colC\"]'], } super_query_obj.return_value = { \"columns\":", "\"b1\": 1500, \"c1\": 2400}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names)", "2.0, 0.0, 0.0, 5.0, 0.0, 7.0], ) np.testing.assert_equal( viz.NVD3TimeSeriesViz( datasource,", "test_viz.form_data[\"time_series_option\"] = \"point_factor\" test_viz.get_data(df) self.assertEqual(\"point_factor\", test_viz.levels_for_diff.mock_calls[2][1][0]) test_viz.levels_for_time = Mock(return_value=1) test_viz.nest_procs", "\"c\": \"dummy3\"} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_js_columns(mock_d) assert", "def test_get_data_applies_percentage(self): form_data = { \"groupby\": [\"groupA\", \"groupB\"], \"metrics\": [", "test_viz = viz.TimeTableViz(datasource, form_data) data = test_viz.get_data(df) # Check method", "t1, \"value\": 4, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t1, \"value\":", "\"subject\": \"lat\", \"isExtra\": False, }, { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\",", "with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj() @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_merges_all_columns(self,", "[form_data.get(\"size\")] form_data = {} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result =", "groups, df) nest = test_viz.nest_values(levels) self.assertEqual(3, len(nest)) for i in", "\"c3\"), }, ], \"metric3\": [ { \"values\": [ {\"x\": 100,", "20, 25, 30, 35, 40] raw[\"groupby1\"] = [\"a1\", \"a2\", \"a3\",", "form_data) with self.assertRaises(Exception): test_viz.query_obj() form_data[\"metrics\"] = [\"x\", \"y\"] test_viz =", "# KIND, either express or implied. See the License for", "= pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t1, t1,", "viz.PartitionViz(Mock(), {\"groupby\": groups}) def return_args(df_drop, aggregate): return df_drop test_viz.process_data =", "\"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, 3.0, 4.0], } )", "[ { \"groupA\": \"A\", \"groupB\": \"x\", \"SUM(value1)\": 15, \"count\": 6,", "Mock(return_value=1) test_viz.form_data[\"groupby\"] = [\"groups\"] test_viz.form_data[\"time_series_option\"] = \"not_time\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[0][1][0])", "self.get_datasource_mock() expected_results = { \"latlong_key\": [ { \"clause\": \"WHERE\", \"expressionType\":", "200, \"y\": 5}, {\"x\": 300, \"y\": 6}, ], \"group\": (\"b1\",", "DTTM_ALIAS: {\"a1\": 600, \"b1\": 600, \"c1\": 600}, \"metric1\": {\"a1\": 6,", "[\"groupB\"] self.assertEqual(sorted(cols), sorted(levels[2].columns.tolist())) cols += [\"groupC\"] self.assertEqual(sorted(cols), sorted(levels[3].columns.tolist())) self.assertEqual(4, len(test_viz.process_data.mock_calls))", "pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS) ) mock_dttm_col.python_date_format", "== [] def test_scatterviz_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock()", "assert result == [] def test_get_js_columns(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource", "test_viz.df_metrics_to_num = Mock() test_viz.get_fillna_for_columns = Mock(return_value=0) results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01", "\"adhoc_filters\": [], \"groupby\": [\"beds\"], \"columns\": [], } datasource = self.get_datasource_mock()", "1}, {\"x\": 200, \"y\": 2}, {\"x\": 300, \"y\": 3}, ],", "= Mock(return_value=1) test_viz.nest_values = Mock(return_value=1) test_viz.form_data[\"groupby\"] = [\"groups\"] test_viz.form_data[\"time_series_option\"] =", "fd[\"metrics\"] res = test_viz.get_data(df) expected = { 946684800000000000: [ {\"time\":", "== [form_data.get(\"size\")] form_data = {} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result", "80}, {\"x\": 300, \"y\": 90}, ], \"group\": (\"c1\", \"c2\", \"c3\"),", "\"b3\"), }, { \"values\": [ {\"x\": 100, \"y\": 7}, {\"x\":", "\"y\": 1}, ] self.assertEqual(expected_values, data[\"values\"]) def test_groupby_nans(self): form_data = {", "+ str(i + 1), nest[i][\"name\"]) self.assertEqual(None, nest[i].get(\"val\")) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(3,", "\"sqlExpression\": \"value3 in ('North America')\", }, ], } datasource =", "[\"groups\"] test_viz.form_data[\"time_series_option\"] = \"not_time\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\"", "form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"count\", data[\"key\"]) expected_values = [ {\"x\":", "\"a3\": 40}, } self.assertEqual(expected, data[\"records\"]) @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_throws_metrics_and_groupby(self, super_query_obj): datasource", "\"columns\": [\"colD\", \"colC\"], \"groupby\": [\"colA\", \"colB\"], } test_viz = viz.TableViz(datasource,", "\"max__Y\"], query_obj[\"metrics\"] ) def test_query_obj_throws_columns_and_metrics(self): datasource = self.get_datasource_mock() form_data =", "t3, t1, t2, t3] raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\",", "} ) data = viz.BigNumberViz(datasource, {\"metrics\": [\"y\"]}).get_data(df) self.assertEqual(data[2], {DTTM_ALIAS: pd.Timestamp(\"2019-01-05\"),", "\"%SUM(value1)\": 0.15, \"%avg__B\": 0.2, }, { \"groupA\": \"B\", \"groupB\": \"x\",", "You may obtain a copy of the License at #", "\"WHERE\", \"sqlExpression\": \"value3 in ('North America')\", }, ], } datasource", "\"pepperoni\", \"cheese\", \"pepperoni\"], \"role\": [\"engineer\", \"engineer\", None, None], \"votes\": [3,", "test_viz.levels_for.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_mean\"", "\"resample_method\": \"sum\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0, 2.0, 0.0,", "3.0, 4.0], } ) data = viz.BigNumberViz(datasource, {\"metrics\": [\"y\"]}).get_data(df) self.assertEqual(data[2],", "pd.Timestamp(\"2004\") raw[DTTM_ALIAS] = [t1, t2, t3, t1, t2, t3, t1,", "], } datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) query_obj", "(\"c1\", \"c2\", \"c3\"), }, ], \"metric3\": [ { \"values\": [", "levels[0].to_dict()) expected = { \"metric1\": {\"a1\": 2, \"b1\": 2, \"c1\":", "= \"agg_mean\" levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected", "viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\": \"asfreq\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"]", "from datetime import datetime import logging from math import nan", "} ], \"geohash_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\":", "\"colB\"], } test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual(form_data[\"all_columns\"],", "\"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"avg__B\", ], }", "data and computes percents self.assertEqual( [ \"groupA\", \"groupB\", \"SUM(value1)\", \"count\",", "pd.Series([datetime(1960, 1, 1, 6, 0)], name=DTTM_ALIAS) ) datasource.offset = 0", "= [100, 200, 300] raw[\"\"] = [1, 2, 3] raw[None]", "[ u\"sum__SP_POP_TOTL\", u\"SUM(SE_PRM_NENR_MA)\", u\"SUM(SP_URB_TOTL)\", u\"count\", ] self.assertEqual(test_viz.metric_labels, expect_metric_labels) self.assertEqual(test_viz.all_metrics, expect_metric_labels)", "[\"\", None]} datasource = self.get_datasource_mock() # Test data raw =", "str(i + 1), nest[i][\"name\"]) self.assertEqual(None, nest[i].get(\"val\")) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(3, len(nest[0][\"children\"][0][\"children\"]))", "groups = [\"groupA\", \"groupB\", \"groupC\"] metrics = [\"metric1\", \"metric2\", \"metric3\"]", "}, { \"values\": [ {\"x\": 100, \"y\": 4}, {\"x\": 200,", "= [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"sum_value\", \"column\":", "OF ANY # KIND, either express or implied. See the", "\"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lonlat\", \"isExtra\": False, }", "test_nest_procs_returns_hierarchy(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300, 100,", "{u\"y\": 2, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 2, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\":", "}, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 5.0, 7.0], ) self.assertEqual(", "}, { \"values\": [ {\"x\": 100, \"y\": 400}, {\"x\": 200,", "viz.RoseViz(Mock(), fd) test_viz.metrics = fd[\"metrics\"] res = test_viz.get_data(df) expected =", "{\"type\": \"latlong\", \"lonCol\": \"lon\", \"latCol\": \"lat\"}, \"delimited_key\": {\"type\": \"delimited\", \"lonlatCol\":", "2, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 5.0,", "\"metric1\": 45, \"metric2\": 450, \"metric3\": 4500} self.assertEqual(expected, levels[0].to_dict()) expected =", "Apache Software Foundation (ASF) under one # or more contributor", "\"comparator\": \"100\", }, { \"expressionType\": \"SQL\", \"clause\": \"WHERE\", \"sqlExpression\": \"value3", "viz_instance = viz.BaseDeckGLViz(datasource, form_data) coord = viz_instance.parse_coordinates(\"1.23, 3.21\") self.assertEqual(coord, (1.23,", "\"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0, 2.0, np.nan, np.nan, 5.0, np.nan,", "form_data) def test_process_metrics(self): # test TableViz metrics in correct order", "2.0, 3.0, 4.0]}, ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"],", "[11, 22, 33, 44], \"count\": [6, 7, 8, 9], \"groupA\":", "600, 700, 800, 900] df = pd.DataFrame(raw) test_viz = viz.PartitionViz(Mock(),", "200, \"y\": 2}, {\"x\": 300, \"y\": 3}, ], \"group\": \"All\",", "3}) def test_get_data_with_none(self): datasource = self.get_datasource_mock() df = pd.DataFrame( data={", "= self.get_datasource_mock() viz_instance = viz.BaseDeckGLViz(datasource, form_data) coord = viz_instance.parse_coordinates(\"1.23, 3.21\")", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"sum\", \"rolling_periods\": 2,", "= test_viz_deckgl.query_obj() assert results[\"metrics\"] == [] assert results[\"groupby\"] == []", "logging logger.info(result) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS)", "under the License is distributed on an # \"AS IS\"", "len(test_viz.levels_for_time.mock_calls)) self.assertEqual(1, len(test_viz.nest_procs.mock_calls)) test_viz.form_data[\"time_series_option\"] = \"time_series\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[3][1][0]) self.assertEqual(7,", "[2, 2, 4, 4] df = pd.DataFrame(raw) test_viz = viz.NVD3TimeSeriesViz(datasource,", "self.assertEqual(expected, data[\"records\"]) def test_parse_adhoc_filters(self): form_data = { \"metrics\": [ {", "u\"key\": (u\"Real Madrid Basket\",), }, { u\"values\": [ {u\"y\": 2,", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "\"cca3\", \"percent_metrics\": [\"count\"], \"slice_id\": 74, \"time_grain_sqla\": None, \"order_by_cols\": [], \"groupby\":", "= test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 6, 0)], name=DTTM_ALIAS)", "200}, {\"x\": 300, \"y\": 300}, ], \"group\": (\"a1\", \"a2\", \"a3\"),", "coord = viz_instance.parse_coordinates(\"1.23, 3.21\") self.assertEqual(coord, (1.23, 3.21)) coord = viz_instance.parse_coordinates(\"1.23", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "nan, 2], \"count\": [30, 42, 3, 29]}) test_viz = viz.DistributionBarViz(datasource,", "\"group\": (\"c1\", \"c2\", \"c3\"), }, ], } self.assertEqual(data, expected) def", "viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"cumsum\", \"rolling_periods\": 0, \"min_periods\":", "1, 1, 5, 0)], name=DTTM_ALIAS) ) mock_dttm_col.python_date_format = None result", "(\"b1\",)}, {\"time\": t3, \"value\": 9, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ],", "= { \"groupby\": [\"groupA\", \"groupB\"], \"metrics\": [ { \"expressionType\": \"SIMPLE\",", "raw[DTTM_ALIAS] = [100, 200, 300, 100, 200, 300, 100, 200,", "{\"a1\": 6, \"b1\": 15, \"c1\": 24}, \"metric2\": {\"a1\": 60, \"b1\":", "\"metrics\": [\"votes\"], \"adhoc_filters\": [], \"groupby\": [\"toppings\"], \"columns\": [\"role\"], } datasource", "\"rolling_type\": \"sum\", \"rolling_periods\": 2, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(),", "test_viz.cache_timeout) datasource.cache_timeout = 156 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(156, test_viz.cache_timeout)", "\"SUM(value1)\": 25, \"count\": 8, \"avg__C\": 33, \"%SUM(value1)\": 0.25, \"%avg__B\": 0.1,", "7, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], 1009843200000000000: [ {\"time\": t2,", "pd.DataFrame(raw) groups = [\"groupA\", \"groupB\", \"groupC\"] test_viz = viz.PartitionViz(Mock(), {\"groupby\":", "{ \"__timestamp\": pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0,", "logger.info(result) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS) )", "= [\"metric1\", \"metric2\", \"metric3\"] procs = {} for i in", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "query_obj = test_viz.query_obj() self.assertEqual( [{\"col\": \"value2\", \"val\": \"100\", \"op\": \">\"}],", "\"WHERE\", \"sqlExpression\": \"value3 in ('North America')\", }, ], \"having\": \"SUM(value1)", "np.nan, 7.0], ) def test_apply_rolling(self): datasource = self.get_datasource_mock() df =", "\"sum_value\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, } ] form_data =", "test_cache_timeout(self): datasource = self.get_datasource_mock() datasource.cache_timeout = 0 test_viz = viz.BaseViz(datasource,", "def test_cache_timeout(self): datasource = self.get_datasource_mock() datasource.cache_timeout = 0 test_viz =", "= {\"dummy\": 123} query_obj = {\"granularity\": \"day\"} results = Mock()", "viz.TableViz(datasource, form_data) data = test_viz.get_data(df) # Check method correctly transforms", "\"metrics\": [\"count\"], \"adhoc_filters\": [], \"groupby\": [\"beds\"], \"columns\": [], } datasource", "form_data={}) self.assertEqual(0, test_viz.cache_timeout) datasource.cache_timeout = 156 test_viz = viz.BaseViz(datasource, form_data={})", "file # distributed with this work for additional information #", "{ \"groupby\": [\"groupA\", \"groupB\"], \"metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\":", "test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df) expected = [", "Mock(return_value=mock_dttm_col) test_viz = viz.BaseViz(datasource, form_data) test_viz.df_metrics_to_num = Mock() test_viz.get_fillna_for_columns =", "{ \"expressionType\": \"SIMPLE\", \"clause\": \"HAVING\", \"subject\": \"SUM(value1)\", \"operator\": \"<\", \"comparator\":", "raw = {} raw[DTTM_ALIAS] = [100, 200, 300, 100, 200,", "{\"a1\": 200, \"b1\": 500, \"c1\": 800}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\",", "\"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual([], query_obj[\"extras\"][\"having_druid\"]) self.assertEqual(\"(value3 in ('North America'))\",", "datasource.query = Mock(return_value=results) mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col) test_viz", "[\"groupby1\"]} datasource = self.get_datasource_mock() raw = {} t1 = pd.Timestamp(\"2000\")", "computes percents self.assertEqual( [ \"groupA\", \"groupB\", \"SUM(value1)\", \"count\", \"avg__C\", \"%SUM(value1)\",", "{\"x\": \"anchovies\", \"y\": 1}, ] self.assertEqual(expected_values, data[\"values\"]) def test_groupby_nans(self): form_data", "= test_viz.query_obj() self.assertFalse(query_obj[\"is_timeseries\"]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" query_obj = test_viz.query_obj() self.assertTrue(query_obj[\"is_timeseries\"])", "form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_key = \"spatial_key\" mock_gb", "pd import tests.test_app import superset.viz as viz from superset import", "from .utils import load_fixture logger = logging.getLogger(__name__) class BaseVizTestCase(SupersetTestCase): def", "\"values\": [ {\"x\": 100, \"y\": 4}, {\"x\": 200, \"y\": 5},", "self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"NULL\") with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"fldkjsalkj,fdlaskjfjadlksj\") @patch(\"superset.utils.core.uuid.uuid4\") def test_filter_nulls(self, mock_uuid4): mock_uuid4.return_value", "for i in range(0, 3): self.assertEqual(\"metric\" + str(i + 1),", "700, 800, 900] df = pd.DataFrame(raw) test_viz = viz.PartitionViz(Mock(), {})", "u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid Basket\",), }, { u\"values\": [", "\"b3\"), }, { \"values\": [ {\"x\": 100, \"y\": 700}, {\"x\":", "40, \"count\": 9, \"avg__C\": 44, \"%SUM(value1)\": 0.4, \"%avg__B\": 0.3, },", "result = test_viz.get_df(query_obj) import logging logger.info(result) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1,", "mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col) mock_dttm_col.python_date_format = \"epoch_ms\" result", "[10, 20, 30, 40, 50, 60, 70, 80, 90] raw[\"metric3\"]", "20, \"b1\": 50, \"c1\": 80}, \"metric3\": {\"a1\": 200, \"b1\": 500,", "\"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_time_calls_process_data_and_drops_cols(self): raw = {} raw[DTTM_ALIAS] =", "\"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lat\", \"isExtra\": False, },", "[\"role\"], } datasource = self.get_datasource_mock() df = pd.DataFrame( { \"toppings\":", "\"b3\"), }, { \"values\": [ {\"x\": 100, \"y\": 70}, {\"x\":", "test_get_data_transforms_dataframe(self): form_data = { \"groupby\": [\"groupA\", \"groupB\", \"groupC\"], \"metrics\": [\"metric1\",", "\"c1\": 200, \"b1\": 200}, \"metric1\": {\"a1\": 2, \"b1\": 5, \"c1\":", "= viz.BaseViz(datasource, form_data={}) self.assertEqual(0, test_viz.cache_timeout) datasource.cache_timeout = 156 test_viz =", "05:00:00\"]}) datasource.offset = 0 mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col)", "\"SUM(value1)\", \"count\", \"avg__C\", \"%SUM(value1)\", \"%avg__B\", ], list(data[\"columns\"]), ) expected =", "test_viz.form_data[\"time_series_option\"] = \"agg_sum\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_mean\" test_viz.get_data(df)", "{ \"values\": [ {\"x\": 100, \"y\": 400}, {\"x\": 200, \"y\":", "raw[DTTM_ALIAS] = [100, 200, 300] raw[\"\"] = [1, 2, 3]", "{\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"avg__B\", ], } datasource =", "100, \"y\": 400}, {\"x\": 200, \"y\": 500}, {\"x\": 300, \"y\":", "{\"time\": t2, \"value\": 5, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t2,", "\"columns\": [], } datasource = self.get_datasource_mock() df = pd.DataFrame( {", "{\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, } ], \"adhoc_filters\": [ { \"expressionType\":", "pd.DataFrame( data={ DTTM_ALIAS: pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\":", "load_fixture logger = logging.getLogger(__name__) class BaseVizTestCase(SupersetTestCase): def test_constructor_exception_no_datasource(self): form_data =", "datasource.get_column = Mock(return_value=mock_dttm_col) test_viz = viz.BaseViz(datasource, form_data) test_viz.df_metrics_to_num = Mock()", "\"value1\", \"type\": \"DOUBLE\"}, }, \"count\", \"avg__C\", ], \"percent_metrics\": [ {", "self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS: {\"a1\": 200, \"c1\": 200,", "\"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0, 2.0, 0.0, 0.0, 5.0,", "# Check method correctly transforms data self.assertEqual(set([\"count\", \"sum__A\"]), set(data[\"columns\"])) time_format", "America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"(SUM(value1) > 5)\", query_obj[\"extras\"][\"having\"]) def test_adhoc_filters_overwrite_legacy_filters(self): form_data =", "\"DOUBLE\"}, }, \"avg__B\", ], } datasource = self.get_datasource_mock() df =", "[\"sum__A\", \"count\", \"avg__C\"], \"percent_metrics\": [\"sum__A\", \"avg__B\", \"max__Y\"], } test_viz =", "{} raw[\"name\"] = [ \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid C.F.🇺🇸🇬🇧\",", ") self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"cumsum\", \"rolling_periods\":", "df = pd.DataFrame( data={ DTTM_ALIAS: pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"]", "self.get_datasource_mock() form_data = { \"metrics\": [\"sum__A\", \"count\", \"avg__C\"], \"percent_metrics\": [\"sum__A\",", "License, Version 2.0 (the # \"License\"); you may not use", "7.0], ) np.testing.assert_equal( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\": \"asfreq\", \"resample_rule\":", "pd.Series([datetime(1960, 1, 1, 0, 0)], name=DTTM_ALIAS) ) def test_cache_timeout(self): datasource", "form_data = {\"metrics\": [\"sum__A\"], \"groupby\": [\"groupby1\"]} datasource = self.get_datasource_mock() raw", "= [\"groupA\", \"groupB\", \"groupC\"] test_viz = viz.PartitionViz(Mock(), {}) time_op =", "self.assertEqual(\"\", query_obj[\"extras\"][\"having\"]) def test_query_obj_merges_percent_metrics(self): datasource = self.get_datasource_mock() form_data = {", "= [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data) test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) assert expected_results.get(mock_key)", "2.5], ) class BigNumberVizTestCase(SupersetTestCase): def test_get_data(self): datasource = self.get_datasource_mock() df", "def test_column_nulls(self): form_data = { \"metrics\": [\"votes\"], \"adhoc_filters\": [], \"groupby\":", "import tests.test_app import superset.viz as viz from superset import app", "datasource.cache_timeout = None datasource.database.cache_timeout = 0 self.assertEqual(0, test_viz.cache_timeout) datasource.database.cache_timeout =", "{} test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() form_data[\"metrics\"] =", "4, 5, 6, 7, 8, 9] raw[\"metric2\"] = [10, 20,", "expected = [ { \"groupA\": \"A\", \"groupB\": \"x\", \"SUM(value1)\": 15,", "[\"groupA\"] self.assertEqual(sorted(cols), sorted(levels[1].columns.tolist())) cols += [\"groupB\"] self.assertEqual(sorted(cols), sorted(levels[2].columns.tolist())) cols +=", "= \"adv_anal\" test_viz.get_data(df) self.assertEqual(1, len(test_viz.levels_for_time.mock_calls)) self.assertEqual(1, len(test_viz.nest_procs.mock_calls)) test_viz.form_data[\"time_series_option\"] = \"time_series\"", "raw = {} t1 = pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") t3", "\"value1\", \"type\": \"DOUBLE\"}, }, \"order_desc\": False, } df = pd.DataFrame({\"SUM(value1)\":", "cols += [\"groupA\"] self.assertEqual(sorted(cols), sorted(levels[1].columns.tolist())) cols += [\"groupB\"] self.assertEqual(sorted(cols), sorted(levels[2].columns.tolist()))", "result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)],", "{ \"columns\": [\"colD\", \"colC\"], \"groupby\": [\"colA\", \"colB\"], } test_viz =", "\"groupB\": \"z\", \"SUM(value1)\": 40, \"count\": 9, \"avg__C\": 44, \"%SUM(value1)\": 0.4,", "viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df) expected = [ { \"key\":", "DTTM_ALIAS from .base_tests import SupersetTestCase from .utils import load_fixture logger", "\"country_code\", \"secondary_metric\": \"sum__SP_POP_TOTL\", \"granularity_sqla\": \"year\", \"page_length\": 0, \"all_columns\": [], \"viz_type\":", "= 1 result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1,", "self.get_datasource_mock() df = pd.DataFrame( { \"toppings\": [\"cheese\", \"pepperoni\", \"anchovies\", None],", "\"b1\": 500, \"c1\": 800}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names)", "superset import app from superset.constants import NULL_STRING from superset.exceptions import", "form_data) result = test_viz.get_df(query_obj) self.assertEqual(type(result), pd.DataFrame) self.assertTrue(result.empty) def test_get_df_handles_dttm_col(self): form_data", "== [\"test_col\"] def test_parse_coordinates(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock()", "= [10, 20, 30] df = pd.DataFrame(raw) pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource,", "test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"]", "test_viz_deckgl.query_obj() assert results[\"metrics\"] == [] assert results[\"groupby\"] == [] assert", "form_data) test_viz_deckgl.point_radius_fixed = {} result = test_viz_deckgl.get_metrics() assert result ==", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "[ { \"values\": [ {\"x\": 100, \"y\": 10}, {\"x\": 200,", "\"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, } ], \"adhoc_filters\": [ {", "= \"agg_sum\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_mean\" test_viz.get_data(df) self.assertEqual(\"agg_mean\",", "\"anchovies\", \"y\": 1}, ] self.assertEqual(expected_values, data[\"values\"]) def test_groupby_nans(self): form_data =", "viz.NVD3TimeSeriesViz(datasource, form_data) viz_data = {} viz_data = test_viz.get_data(df) expected =", "1), nest[i][\"name\"]) self.assertEqual(None, nest[i].get(\"val\")) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(3, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"]))", "expected_results.get(mock_key) == adhoc_filters class TimeSeriesVizTestCase(SupersetTestCase): def test_timeseries_unicode_data(self): datasource = self.get_datasource_mock()", "1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"][0][\"children\"]) ) def test_get_data_calls_correct_method(self): test_viz = viz.PartitionViz(Mock(), {}) df", "raw = {} raw[DTTM_ALIAS] = [100, 200, 300] raw[\"\"] =", "20, \"count\": 7, \"avg__C\": 22, \"%SUM(value1)\": 0.2, \"%avg__B\": 0.4, },", "\"votes\": [3, 5, 1, 2], } ) test_viz = viz.DistributionBarViz(datasource,", "4, 5, 6, 7, 8, 9] df = pd.DataFrame(raw) fd", "25, 40], \"avg__B\": [10, 20, 5, 15], \"avg__C\": [11, 22,", "[ {\"x\": 100, \"y\": 400}, {\"x\": 200, \"y\": 500}, {\"x\":", "test_viz.query_obj() self.assertEqual([\"colA\", \"colB\", metric], query_obj[\"metrics\"]) self.assertEqual([(metric, True)], query_obj[\"orderby\"]) run_test(\"simple_metric\") run_test(", "{\"a1\": 200, \"c1\": 200, \"b1\": 200}, \"metric1\": {\"a1\": 2, \"b1\":", "def test_get_data_calls_correct_method(self): test_viz = viz.PartitionViz(Mock(), {}) df = Mock() with", "\"c1\": 2400}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\",", "}, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 1.5, 2.0, 2.5], ) class", "\"pepperoni\", \"anchovies\", None], \"votes\": [3, 5, 1, 2], } )", "df_drop.pivot_table( index=DTTM_ALIAS, columns=groups[:i], values=metrics ) procs[i] = pivot nest =", "import pandas as pd import tests.test_app import superset.viz as viz", "superset.utils.core import DTTM_ALIAS from .base_tests import SupersetTestCase from .utils import", "[\"sum__A\", \"count\", \"avg__C\", \"avg__B\", \"max__Y\"], query_obj[\"metrics\"] ) def test_query_obj_throws_columns_and_metrics(self): datasource", "{\"x\": 300, \"y\": 900}, ], \"group\": (\"c1\", \"c2\", \"c3\"), },", "\"y\": 7}, {\"x\": 200, \"y\": 8}, {\"x\": 300, \"y\": 9},", "\"%Y-%m-%d %H:%M:%S\" expected = { t1.strftime(time_format): {\"a1\": 15, \"a2\": 20,", "= test_viz.levels_for_time(groups, df) self.assertEqual(4, len(levels)) cols = [DTTM_ALIAS, \"metric1\", \"metric2\",", "\"y\": 9}, ], \"group\": (\"c1\", \"c2\", \"c3\"), }, ], \"metric2\":", "{ t1.strftime(time_format): {\"a1\": 15, \"a2\": 20, \"a3\": 25}, t2.strftime(time_format): {\"a1\":", "[] test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data) test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) assert expected_results.get(mock_key) ==", "form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() viz_instance = viz.BaseDeckGLViz(datasource, form_data)", "self.assertEqual(\"metric\" + str(i + 1), nest[i][\"name\"]) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"]))", "= viz.BaseDeckGLViz(datasource, form_data) coord = viz_instance.parse_coordinates(\"1.23, 3.21\") self.assertEqual(coord, (1.23, 3.21))", "2, \"c1\": 2}, \"metric2\": {\"a1\": 20, \"b1\": 20, \"c1\": 20},", "[], \"metrics\": [\"\", None]} datasource = self.get_datasource_mock() # Test data", "= pd.Timestamp(\"2002\") t3 = pd.Timestamp(\"2004\") raw[DTTM_ALIAS] = [t1, t2, t3,", "\"metrics\": [\"y\"], \"rolling_type\": \"cumsum\", \"rolling_periods\": 0, \"min_periods\": 0, }, )", "def test_get_data_transforms_dataframe(self): form_data = { \"groupby\": [\"groupA\", \"groupB\", \"groupC\"], \"metrics\":", "[\"a1\", \"a1\", \"a1\", \"b1\", \"b1\", \"b1\", \"c1\", \"c1\", \"c1\"] raw[\"groupB\"]", "{\"x\": \"pepperoni\", \"y\": 5}, {\"x\": \"cheese\", \"y\": 3}, {\"x\": NULL_STRING,", "\"values\": [ {\"x\": 100, \"y\": 7}, {\"x\": 200, \"y\": 8},", "{ \"expressionType\": \"SQL\", \"clause\": \"WHERE\", \"sqlExpression\": \"value3 in ('North America')\",", "sorted(levels[0].columns.tolist())) cols += [\"groupA\"] self.assertEqual(sorted(cols), sorted(levels[1].columns.tolist())) cols += [\"groupB\"] self.assertEqual(sorted(cols),", "\"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual( [{\"op\": \"<\", \"val\": \"10\", \"col\":", "240}, \"metric3\": {\"a1\": 600, \"b1\": 1500, \"c1\": 2400}, } self.assertEqual(expected,", "[]} datasource = self.get_datasource_mock() raw = {} t1 = pd.Timestamp(\"2000\")", "\"groupC\"] test_viz = viz.PartitionViz(Mock(), {}) time_op = \"point_diff\" levels =", "\"y\": 2}, {\"x\": 300, \"y\": 3}, ], \"group\": (\"a1\", \"a2\",", ".base_tests import SupersetTestCase from .utils import load_fixture logger = logging.getLogger(__name__)", "700, 800, 900] df = pd.DataFrame(raw) groups = [\"groupA\", \"groupB\",", "# under the License. # isort:skip_file import uuid from datetime", "= Mock(return_value=1) test_viz.get_data(df) self.assertEqual(\"point_diff\", test_viz.levels_for_diff.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_percent\" test_viz.get_data(df) self.assertEqual(\"point_percent\",", "2], } ) test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)", "def test_process_spatial_query_obj(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_key =", "{\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"order_desc\": False, } df =", "5.0, 7.0], ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\":", "order form_data = { \"url_params\": {}, \"row_limit\": 500, \"metric\": \"sum__SP_POP_TOTL\",", "200, \"b1\": 200, \"c1\": 200}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual(4, len(levels))", "[\"groupA\", \"groupB\"], \"metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\":", "\"SUM(value1)\": 20, \"count\": 7, \"avg__C\": 22, \"%SUM(value1)\": 0.2, \"%avg__B\": 0.4,", "\"operator\": \"<\", \"comparator\": \"10\", }, { \"expressionType\": \"SQL\", \"clause\": \"HAVING\",", "\"lon\", \"latCol\": \"lat\"}, \"delimited_key\": {\"type\": \"delimited\", \"lonlatCol\": \"lonlat\"}, \"geohash_key\": {\"type\":", "\"avg__B\", \"max__Y\"], query_obj[\"metrics\"] ) def test_query_obj_throws_columns_and_metrics(self): datasource = self.get_datasource_mock() form_data", "= viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"NULL\") with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"fldkjsalkj,fdlaskjfjadlksj\") @patch(\"superset.utils.core.uuid.uuid4\")", "test_should_be_timeseries_raises_when_no_granularity(self): datasource = self.get_datasource_mock() form_data = {\"include_time\": True} with self.assertRaises(Exception):", "test_viz.get_data(df) # Check method correctly transforms data and computes percents", "= {\"groupby\": [\"a\"]} super_query_obj.return_value = {} test_viz = viz.TimeTableViz(datasource, form_data)", "self.assertEqual(3, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) self.assertEqual( 1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"][0][\"children\"]) ) def test_get_data_calls_correct_method(self):", "\"y\": 500}, {\"x\": 300, \"y\": 600}, ], \"group\": (\"b1\", \"b2\",", "data raw = {} raw[DTTM_ALIAS] = [100, 200, 300] raw[\"\"]", "\"geo\", \"isExtra\": False, } ], } for mock_key in [\"latlong_key\",", "t2, t2] raw[\"sum__A\"] = [15, 20, 25, 30, 35, 40]", "with self.assertRaises(ValueError) as context: test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) self.assertTrue(\"Bad spatial key\" in", "= pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01\"]}) mock_dttm_col.python_date_format = \"%Y-%m-%d\" result = test_viz.get_df(query_obj) pd.testing.assert_series_equal(", "None) self.assertEqual(viz_instance.parse_coordinates(\"\"), None) def test_parse_coordinates_raises(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource =", "datetime import logging from math import nan from unittest.mock import", "test_query_obj_throws_metrics_and_groupby(self, super_query_obj): datasource = self.get_datasource_mock() form_data = {\"groupby\": [\"a\"]} super_query_obj.return_value", "\"%SUM(value1)\": 0.4, \"%avg__B\": 0.3, }, ] self.assertEqual(expected, data[\"records\"]) def test_parse_adhoc_filters(self):", "mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data.copy()) test_viz_deckgl.spatial_control_keys", "len(levels)) expected = { DTTM_ALIAS: 200.0, \"metric1\": 5.0, \"metric2\": 50.0,", "expected_values = [ {\"x\": \"1.0\", \"y\": 42}, {\"x\": \"0.0\", \"y\":", "} super_query_obj.return_value = { \"columns\": [\"colD\", \"colC\"], \"groupby\": [\"colA\", \"colB\"],", "[\"int\"] form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed =", "pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t1, t1, t2,", "3] raw[None] = [10, 20, 30] df = pd.DataFrame(raw) pairedTTestViz", "expected = { t1.strftime(time_format): {\"sum__A\": 15, \"count\": 6}, t2.strftime(time_format): {\"sum__A\":", "\"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, } ], \"adhoc_filters\": [", "{\"x\": 100, \"y\": 100}, {\"x\": 200, \"y\": 200}, {\"x\": 300,", "test_timeseries_unicode_data(self): datasource = self.get_datasource_mock() form_data = {\"groupby\": [\"name\"], \"metrics\": [\"sum__payout\"]}", "test_viz.query_obj() form_data[\"metrics\"] = [\"x\", \"y\"] test_viz = viz.TimeTableViz(datasource, form_data) with", "u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid C.F.\\U0001f1fa\\U0001f1f8\\U0001f1ec\\U0001f1e7\",), }, ] self.assertEqual(expected, viz_data)", "data = test_viz.get_data(df)[0] self.assertEqual(\"count\", data[\"key\"]) expected_values = [ {\"x\": \"1.0\",", "\"b1\": 2, \"c1\": 2}, \"metric2\": {\"a1\": 20, \"b1\": 20, \"c1\":", "\"metrics\": [\"x\", \"y\"]} with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj()", "viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {\"type\": \"metric\", \"value\": \"int\"} result =", "= {\"metrics\": [\"sum__A\", \"count\"], \"groupby\": []} datasource = self.get_datasource_mock() raw", ") class BigNumberVizTestCase(SupersetTestCase): def test_get_data(self): datasource = self.get_datasource_mock() df =", "datasource = self.get_datasource_mock() datasource.cache_timeout = 0 test_viz = viz.BaseViz(datasource, form_data={})", "test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"votes\", data[\"key\"]) expected_values", "7, 8, 9], \"groupA\": [\"A\", \"B\", \"C\", \"C\"], \"groupB\": [\"x\",", "900] df = pd.DataFrame(raw) pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource, form_data) data =", "5, 0)], name=DTTM_ALIAS) ) datasource.offset = 1 result = test_viz.get_df(query_obj)", "\"operator\": \"IS NOT NULL\", \"subject\": \"lon\", \"isExtra\": False, }, ],", "200, \"y\": 200}, {\"x\": 300, \"y\": 300}, ], \"group\": (\"a1\",", "= self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics() assert", "self.assertEqual(4, len(levels)) expected = { DTTM_ALIAS: 200.0, \"metric1\": 5.0, \"metric2\":", "= [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(ValueError) as context:", "= df_drop.pivot_table( index=DTTM_ALIAS, columns=groups[:i], values=metrics ) procs[i] = pivot nest", "form_data = {\"include_time\": True} with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data)", "load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource,", "Madrid C.F.\\U0001f1fa\\U0001f1f8\\U0001f1ec\\U0001f1e7\",), }, ] self.assertEqual(expected, viz_data) def test_process_data_resample(self): datasource =", "\"subject\": \"SUM(value1)\", \"operator\": \"<\", \"comparator\": \"10\", }, { \"expressionType\": \"SQL\",", "t2, t3, t1, t2, t3] raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\",", "= viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(NotImplementedError) as context: test_viz_deckgl.get_properties(mock_d) self.assertTrue(\"\" in", "\"10\", \"col\": \"SUM(value1)\"}], query_obj[\"extras\"][\"having_druid\"], ) self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"])", "self.assertEqual(data, expected) def test_get_data_empty_null_keys(self): form_data = {\"groupby\": [], \"metrics\": [\"\",", "self.get_datasource_mock() df = pd.DataFrame( { \"__timestamp\": pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\",", "\"val\": \"100\", \"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual([], query_obj[\"extras\"][\"having_druid\"]) self.assertEqual(\"(value3 in", "= \"spatial_key\" mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with", "35, \"a3\": 40}, } self.assertEqual(expected, data[\"records\"]) @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_throws_metrics_and_groupby(self, super_query_obj):", "{\"x\": \"cheese\", \"y\": 3}, {\"x\": NULL_STRING, \"y\": 2}, {\"x\": \"anchovies\",", "\"values\": [ {\"x\": 100, \"y\": 700}, {\"x\": 200, \"y\": 800},", "= self.get_datasource_mock() test_viz_deckgl = viz.DeckGeoJson(datasource, form_data) results = test_viz_deckgl.query_obj() assert", "7, 8, 9] df = pd.DataFrame(raw) fd = {\"metrics\": [\"metric1\"],", "\"%SUM(value1)\": 0.25, \"%avg__B\": 0.1, }, { \"groupA\": \"C\", \"groupB\": \"z\",", "from superset.constants import NULL_STRING from superset.exceptions import SpatialException from superset.utils.core", "groups}) def return_args(df_drop, aggregate): return df_drop test_viz.process_data = Mock(side_effect=return_args) levels", "\"SUM(value1)\"}], query_obj[\"extras\"][\"having_druid\"], ) self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"(SUM(value1) >", "\"groupA\": \"A\", \"groupB\": \"x\", \"SUM(value1)\": 15, \"count\": 6, \"avg__C\": 11,", "\"url_params\": {}, \"row_limit\": 500, \"metric\": \"sum__SP_POP_TOTL\", \"entity\": \"country_code\", \"secondary_metric\": \"sum__SP_POP_TOTL\",", "Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid Basket\", \"Real Madrid Basket\", ] raw[\"__timestamp\"]", "450, \"metric3\": 4500} self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS: {\"a1\":", "\"C\"] with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj() @patch(\"superset.viz.BaseViz.query_obj\") def", "\"metric2\": {\"a1\": 20, \"b1\": 20, \"c1\": 20}, \"metric3\": {\"a1\": 200,", "data = test_viz.get_data(df) # Check method correctly transforms data and", "\"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\":", "datasource = self.get_datasource_mock() expected_results = { \"latlong_key\": [ { \"clause\":", "pivot nest = test_viz.nest_procs(procs) self.assertEqual(3, len(nest)) for i in range(0,", "correctly transforms data expected = { \"metric1\": [ { \"values\":", "\"metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\", \"column\":", "self.get_datasource_mock() mock_d = {\"a\": \"dummy1\", \"b\": \"dummy2\", \"c\": \"dummy3\"} test_viz_deckgl", "df = pd.DataFrame(raw) fd = {\"metrics\": [\"metric1\"], \"groupby\": [\"groupA\"]} test_viz", "\"SIMPLE\", \"clause\": \"HAVING\", \"subject\": \"SUM(value1)\", \"operator\": \"<\", \"comparator\": \"10\", },", "\"b1\": 200, \"c1\": 200}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual(4, len(levels)) self.assertEqual([\"groupA\",", "= uuid.UUID(\"12345678123456781234567812345678\") test_form_data = { \"latlong_key\": {\"type\": \"latlong\", \"lonCol\": \"lon\",", "1, 0, 0)], name=DTTM_ALIAS) ) def test_cache_timeout(self): datasource = self.get_datasource_mock()", "t3, \"value\": 9, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], } self.assertEqual(expected,", "5, \"c1\": 8}, \"metric2\": {\"a1\": 20, \"b1\": 50, \"c1\": 80},", "= [\"groupA\", \"groupB\", \"groupC\"] levels = test_viz.levels_for(\"agg_sum\", groups, df) nest", "{ t1.strftime(time_format): {\"sum__A\": 15, \"count\": 6}, t2.strftime(time_format): {\"sum__A\": 20, \"count\":", "datasource.type = \"table\" test_viz = viz.BaseViz(datasource, form_data) expect_metric_labels = [", "\"groupC\"] metrics = [\"metric1\", \"metric2\", \"metric3\"] procs = {} for", "datasource = self.get_datasource_mock() mock_d = {\"a\": \"dummy1\", \"b\": \"dummy2\", \"c\":", "def test_get_js_columns(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_d =", "\"value\": 8, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], 1072915200000000000: [ {\"time\":", "class BaseDeckGLVizTestCase(SupersetTestCase): def test_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock()", "900}, ], \"group\": (\"c1\", \"c2\", \"c3\"), }, ], } self.assertEqual(data,", "assert result == [] def test_scatterviz_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource", "express or implied. See the License for the # specific", "len(nest[0][\"children\"])) self.assertEqual(3, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) self.assertEqual( 1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"][0][\"children\"]) ) def", "50}, {\"x\": 300, \"y\": 60}, ], \"group\": (\"b1\", \"b2\", \"b3\"),", "= { \"metrics\": [\"count\"], \"adhoc_filters\": [], \"groupby\": [\"beds\"], \"columns\": [],", "results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01\"]}) mock_dttm_col.python_date_format = \"%Y-%m-%d\" result = test_viz.get_df(query_obj)", "9, \"avg__C\": 44, \"%SUM(value1)\": 0.4, \"%avg__B\": 0.3, }, ] self.assertEqual(expected,", "\"groupC\"], \"metrics\": [\"metric1\", \"metric2\", \"metric3\"], } datasource = self.get_datasource_mock() #", "= {} raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\", \"b1\", \"b1\",", "5, 6, 7, 8, 9] raw[\"metric2\"] = [10, 20, 30,", "pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t2] raw[\"sum__A\"] =", "\"since\": \"2014-01-01\", \"until\": \"2014-01-02\", \"metrics\": [\"sum__SP_POP_TOTL\", \"SUM(SE_PRM_NENR_MA)\", \"SUM(SP_URB_TOTL)\"], \"country_fieldtype\": \"cca3\",", "import SpatialException from superset.utils.core import DTTM_ALIAS from .base_tests import SupersetTestCase", "viz.BaseDeckGLViz(datasource, form_data) coord = viz_instance.parse_coordinates(\"1.23, 3.21\") self.assertEqual(coord, (1.23, 3.21)) coord", "[ {\"x\": 100, \"y\": 10}, {\"x\": 200, \"y\": 20}, {\"x\":", "may obtain a copy of the License at # #", "viz from superset import app from superset.constants import NULL_STRING from", "test_viz.query_obj() del form_data[\"metrics\"] form_data[\"groupby\"] = [\"B\", \"C\"] with self.assertRaises(Exception): test_viz", "\"2014-01-02\", \"metrics\": [\"sum__SP_POP_TOTL\", \"SUM(SE_PRM_NENR_MA)\", \"SUM(SP_URB_TOTL)\"], \"country_fieldtype\": \"cca3\", \"percent_metrics\": [\"count\"], \"slice_id\":", "], } self.assertEqual(data, expected) class PartitionVizTestCase(SupersetTestCase): @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_time_series_option(self, super_query_obj):", "\"lat\"], \"delimited_key\": [\"lonlat\"], \"geohash_key\": [\"geo\"], } for mock_key in [\"latlong_key\",", "= { \"metrics\": metrics, \"timeseries_limit_metric\": { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\",", "[\"engineer\", \"engineer\", None, None], \"votes\": [3, 5, 1, 2], }", "nest = test_viz.nest_values(levels) self.assertEqual(3, len(nest)) for i in range(0, 3):", "range(0, 3): self.assertEqual(\"metric\" + str(i + 1), nest[i][\"name\"]) self.assertEqual(3, len(nest[0][\"children\"]))", "[t1, t2, t3, t1, t2, t3, t1, t2, t3] raw[\"groupA\"]", "form_data = { \"groupby\": [\"groupA\", \"groupB\", \"groupC\"], \"metrics\": [\"metric1\", \"metric2\",", "\"b1\": 150, \"c1\": 240}, \"metric3\": {\"a1\": 600, \"b1\": 1500, \"c1\":", "\"groupB\": \"x\", \"SUM(value1)\": 20, \"count\": 7, \"avg__C\": 22, \"%SUM(value1)\": 0.2,", "NULL\", \"subject\": \"lon\", \"isExtra\": False, }, ], \"delimited_key\": [ {", "form_data) expect_metric_labels = [ u\"sum__SP_POP_TOTL\", u\"SUM(SE_PRM_NENR_MA)\", u\"SUM(SP_URB_TOTL)\", u\"count\", ] self.assertEqual(test_viz.metric_labels,", "{} raw[DTTM_ALIAS] = [100, 200, 300, 100, 200, 300, 100,", "{\"a1\": 600, \"b1\": 1500, \"c1\": 2400}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\",", "7}, {\"x\": 200, \"y\": 8}, {\"x\": 300, \"y\": 9}, ],", "= [\"a2\", \"a2\", \"a2\", \"b2\", \"b2\", \"b2\", \"c2\", \"c2\", \"c2\"]", "test_viz.cache_timeout) datasource.database.cache_timeout = 1666 self.assertEqual(1666, test_viz.cache_timeout) datasource.database.cache_timeout = None test_viz", "test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"NULL\") with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"fldkjsalkj,fdlaskjfjadlksj\")", "= Mock() datasource.type = \"table\" datasource.query = Mock(return_value=results) mock_dttm_col =", "\"Real Madrid Basket\", ] raw[\"__timestamp\"] = [ \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", \"2018-02-20T00:00:00\",", "Foundation (ASF) under one # or more contributor license agreements.", "}, { u\"values\": [ {u\"y\": 2, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 2,", "{\"time\": t3, \"value\": 9, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], }", "= test_viz.get_data(df) # Check method correctly transforms data and computes", "t2.strftime(time_format): {\"sum__A\": 20, \"count\": 7}, } self.assertEqual(expected, data[\"records\"]) def test_get_data_group_by(self):", "= viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics() assert result == []", "{\"a1\": 20, \"b1\": 50, \"c1\": 80}, \"metric3\": {\"a1\": 200, \"b1\":", "\"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t1, \"value\": 4, \"key\": (\"b1\",),", "\"percent_metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\", \"column\":", "test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) self.assertTrue(\"Bad spatial key\" in str(context.exception)) test_form_data = {", "3.21\") self.assertEqual(coord, (1.23, 3.21)) self.assertEqual(viz_instance.parse_coordinates(None), None) self.assertEqual(viz_instance.parse_coordinates(\"\"), None) def test_parse_coordinates_raises(self):", "datasource.offset = 1 result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1,", "\"year\", \"page_length\": 0, \"all_columns\": [], \"viz_type\": \"table\", \"since\": \"2014-01-01\", \"until\":", "mock_gb) assert expected_results.get(mock_key) == mock_gb def test_geojson_query_obj(self): form_data = load_fixture(\"deck_geojson_form_data.json\")", "in compliance # with the License. You may obtain a", "# to you under the Apache License, Version 2.0 (the", "License for the # specific language governing permissions and limitations", "\"c1\": 600}, \"metric1\": {\"a1\": 6, \"b1\": 15, \"c1\": 24}, \"metric2\":", "6, \"b1\": 15, \"c1\": 24}, \"metric2\": {\"a1\": 60, \"b1\": 150,", "50, \"c1\": 80}, \"metric3\": {\"a1\": 200, \"b1\": 500, \"c1\": 800},", "nest[i][\"name\"]) self.assertEqual(None, nest[i].get(\"val\")) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(3, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) self.assertEqual(", "t2, t2, t2] raw[\"sum__A\"] = [15, 20, 25, 30, 35,", "t1, \"value\": 1, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t1, \"value\":", "self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(NotImplementedError) as context: test_viz_deckgl.get_properties(mock_d)", "expected = {DTTM_ALIAS: 1800, \"metric1\": 45, \"metric2\": 450, \"metric3\": 4500}", "[\"test_col\"] def test_parse_coordinates(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() viz_instance", "{\"sum__A\": 15, \"count\": 6}, t2.strftime(time_format): {\"sum__A\": 20, \"count\": 7}, }", "= None datasource.database.cache_timeout = 0 self.assertEqual(0, test_viz.cache_timeout) datasource.database.cache_timeout = 1666", "\"metric2\": 450, \"metric3\": 4500} self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS:", ") self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"(SUM(value1) > 5)\", query_obj[\"extras\"][\"having\"])", "\"c1\": 2}, \"metric2\": {\"a1\": 20, \"b1\": 20, \"c1\": 20}, \"metric3\":", "raw[\"groupB\"] = [\"a2\", \"a2\", \"a2\", \"b2\", \"b2\", \"b2\", \"c2\", \"c2\",", "query_obj = test_viz.query_obj() self.assertTrue(query_obj[\"is_timeseries\"]) def test_levels_for_computes_levels(self): raw = {} raw[DTTM_ALIAS]", "= viz.BigNumberViz(datasource, {\"metrics\": [\"y\"]}).get_data(df) self.assertEqual(data[2], {DTTM_ALIAS: pd.Timestamp(\"2019-01-05\"), \"y\": 3}) def", "form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {\"type\":", "[\"x\", \"x\", \"y\", \"z\"], } ) test_viz = viz.TableViz(datasource, form_data)", "\"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"order_desc\": False, } df", "t3 = pd.Timestamp(\"2004\") raw[DTTM_ALIAS] = [t1, t2, t3, t1, t2,", "[\"a2\", \"a2\", \"a2\", \"b2\", \"b2\", \"b2\", \"c2\", \"c2\", \"c2\"] raw[\"groupC\"]", "mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col) test_viz = viz.BaseViz(datasource, form_data)", "= self.get_datasource_mock() mock_key = \"spatial_key\" mock_gb = [] test_viz_deckgl =", "viz.BaseViz(datasource, form_data) def test_process_metrics(self): # test TableViz metrics in correct", "\"metric1\": 5.0, \"metric2\": 50.0, \"metric3\": 500.0, } self.assertEqual(expected, levels[0].to_dict()) expected", "= pd.DataFrame(raw) pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource, form_data) data = pairedTTestViz.get_data(df) #", "\"a2\", \"a3\"), }, { \"values\": [ {\"x\": 100, \"y\": 400},", "\"value2\", \"val\": \"100\", \"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual([], query_obj[\"extras\"][\"having_druid\"]) self.assertEqual(\"(value3", ".process_data(df)[\"y\"] .tolist(), [1.0, 2.0, 0.0, 0.0, 5.0, 0.0, 7.0], )", "test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj() del form_data[\"metrics\"] form_data[\"groupby\"] = [\"B\",", "\"o10Y\", } datasource = Mock() datasource.type = \"table\" test_viz =", "3, 4, 5, 6, 7, 8, 9] df = pd.DataFrame(raw)", "\"SUM(value1)\": 15, \"count\": 6, \"avg__C\": 11, \"%SUM(value1)\": 0.15, \"%avg__B\": 0.2,", "[] assert results[\"columns\"] == [\"test_col\"] def test_parse_coordinates(self): form_data = load_fixture(\"deck_path_form_data.json\")", "return_args(df_drop, aggregate): return df_drop test_viz.process_data = Mock(side_effect=return_args) levels = test_viz.levels_for_time(groups,", "3, 29]}) test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"count\",", "method correctly transforms data self.assertEqual(set([\"a1\", \"a2\", \"a3\"]), set(data[\"columns\"])) time_format =", "License is distributed on an # \"AS IS\" BASIS, WITHOUT", "test_viz.get_data(df) test_viz.levels_for = Mock(return_value=1) test_viz.nest_values = Mock(return_value=1) test_viz.form_data[\"groupby\"] = [\"groups\"]", "viz.PartitionViz(datasource, form_data) super_query_obj.return_value = {} query_obj = test_viz.query_obj() self.assertFalse(query_obj[\"is_timeseries\"]) test_viz.form_data[\"time_series_option\"]", "query_obj[\"columns\"]) self.assertEqual([], query_obj[\"groupby\"]) self.assertEqual([[\"colA\", \"colB\"], [\"colC\"]], query_obj[\"orderby\"]) def test_query_obj_uses_sortby(self): datasource", "viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {} result = test_viz_deckgl.get_metrics() assert result", "\"latlong_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\":", "datasource, {\"metrics\": [\"y\"], \"resample_method\": \"asfreq\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(),", "}, ] self.assertEqual(expected, viz_data) def test_process_data_resample(self): datasource = self.get_datasource_mock() df", "100, \"y\": 10}, {\"x\": 200, \"y\": 20}, {\"x\": 300, \"y\":", "\"a3\"), }, { \"values\": [ {\"x\": 100, \"y\": 400}, {\"x\":", "= viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"votes\", data[\"key\"]) expected_values =", "40}, {\"x\": 200, \"y\": 50}, {\"x\": 300, \"y\": 60}, ],", "viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_js_columns(mock_d) assert result == {\"color\": None}", "\"groupB\": \"x\", \"SUM(value1)\": 15, \"count\": 6, \"avg__C\": 11, \"%SUM(value1)\": 0.15,", "= [\"groups\"] test_viz.form_data[\"time_series_option\"] = \"not_time\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] =", "\"order_desc\": False, } def run_test(metric): form_data[\"timeseries_limit_metric\"] = metric test_viz =", "datasource = self.get_datasource_mock() form_data = {\"groupby\": [\"a\"]} super_query_obj.return_value = {}", "200}, \"metric1\": {\"a1\": 2, \"b1\": 5, \"c1\": 8}, \"metric2\": {\"a1\":", "\"y\": 20}, {\"x\": 300, \"y\": 30}, ], \"group\": \"All\", }", "\"val\": \"100\", \"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual( [{\"op\": \"<\", \"val\":", "600}, ], \"group\": (\"b1\", \"b2\", \"b3\"), }, { \"values\": [", "t2, \"value\": 2, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t2, \"value\":", "test_viz.get_data(df) self.assertEqual(\"point_diff\", test_viz.levels_for_diff.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_percent\" test_viz.get_data(df) self.assertEqual(\"point_percent\", test_viz.levels_for_diff.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"]", "{} raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\", \"b1\", \"b1\", \"c1\",", "} ) test_viz = viz.TableViz(datasource, form_data) data = test_viz.get_data(df) #", "datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"mean\", \"rolling_periods\": 10, \"min_periods\": 0,", "None, \"order_by_cols\": [], \"groupby\": [\"country_name\"], \"compare_lag\": \"10\", \"limit\": \"25\", \"datasource\":", "= load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result", "pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS) ) mock_dttm_col.python_date_format = None", "\"c2\", \"c3\"), }, ], } self.assertEqual(data, expected) def test_get_data_empty_null_keys(self): form_data", ") self.assertEqual([], query_obj[\"extras\"][\"having_druid\"]) self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"\", query_obj[\"extras\"][\"having\"])", "\"c1\": 800}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\",", "u\"2018-02-20T00:00:00\"}, {u\"y\": 4, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid Basket\",),", "raw[\"metric3\"] = [100, 200, 300, 400, 500, 600, 700, 800,", "3.21)) coord = viz_instance.parse_coordinates(\"1.23 3.21\") self.assertEqual(coord, (1.23, 3.21)) self.assertEqual(viz_instance.parse_coordinates(None), None)", "\"metric3\": 4500} self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS: {\"a1\": 600,", "def return_args(df_drop, aggregate): return df_drop test_viz.process_data = Mock(side_effect=return_args) levels =", "pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 0, 0)], name=DTTM_ALIAS) ) def", "= test_viz_deckgl.form_data[\"adhoc_filters\"] assert expected_results.get(mock_key) == adhoc_filters class TimeSeriesVizTestCase(SupersetTestCase): def test_timeseries_unicode_data(self):", "u\"key\": (u\"Real Madrid C.F.\\U0001f1fa\\U0001f1f8\\U0001f1ec\\U0001f1e7\",), }, ] self.assertEqual(expected, viz_data) def test_process_data_resample(self):", "{\"x\": 300, \"y\": 9}, ], \"group\": (\"c1\", \"c2\", \"c3\"), },", "Mock() with self.assertRaises(ValueError): test_viz.get_data(df) test_viz.levels_for = Mock(return_value=1) test_viz.nest_values = Mock(return_value=1)", "{\"dummy\": 123} query_obj = {\"granularity\": \"day\"} datasource = self.get_datasource_mock() test_viz", "= [mock_key] test_viz_deckgl.add_null_filters() adhoc_filters = test_viz_deckgl.form_data[\"adhoc_filters\"] assert expected_results.get(mock_key) == adhoc_filters", "\"avg__C\": 33, \"%SUM(value1)\": 0.25, \"%avg__B\": 0.1, }, { \"groupA\": \"C\",", "[] assert results[\"groupby\"] == [] assert results[\"columns\"] == [\"test_col\"] def", "[{\"op\": \"<\", \"val\": \"10\", \"col\": \"SUM(value1)\"}], query_obj[\"extras\"][\"having_druid\"], ) self.assertEqual(\"(value3 in", "= [1, 2, 3, 4, 5, 6, 7, 8, 9]", "\"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS NOT NULL\",", "6, 0)], name=DTTM_ALIAS) ) datasource.offset = 0 results.df = pd.DataFrame(data={DTTM_ALIAS:", "{ \"expressionType\": \"SQL\", \"clause\": \"HAVING\", \"sqlExpression\": \"SUM(value1) > 5\", },", "form_data) result = test_viz_deckgl.get_metrics() assert result == [form_data.get(\"size\")] form_data =", "= [\"groupA\", \"groupB\", \"groupC\"] time_op = \"agg_sum\" test_viz = viz.PartitionViz(Mock(),", "def test_get_data_group_by(self): form_data = {\"metrics\": [\"sum__A\"], \"groupby\": [\"groupby1\"]} datasource =", "\"metric3\"], } datasource = self.get_datasource_mock() # Test data raw =", "600} self.assertEqual(expected, levels[0].to_dict()) expected = { \"metric1\": {\"a1\": 2, \"b1\":", "\"y\": 100}, {\"x\": 200, \"y\": 200}, {\"x\": 300, \"y\": 300},", "the Apache Software Foundation (ASF) under one # or more", "self.assertEqual(7, len(test_viz.nest_values.mock_calls)) class RoseVisTestCase(SupersetTestCase): def test_rose_vis_get_data(self): raw = {} t1", "{\"metrics\": [\"y\"], \"resample_method\": \"asfreq\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0,", "datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"sum\", \"rolling_periods\": 2, \"min_periods\": 0,", "35, 40] raw[\"groupby1\"] = [\"a1\", \"a2\", \"a3\", \"a1\", \"a2\", \"a3\"]", "mock_uuid4): mock_uuid4.return_value = uuid.UUID(\"12345678123456781234567812345678\") test_form_data = { \"latlong_key\": {\"type\": \"latlong\",", "\"SUM(value1) > 5\", }, { \"expressionType\": \"SQL\", \"clause\": \"WHERE\", \"sqlExpression\":", "\"colB\"], \"order_desc\": False, } def run_test(metric): form_data[\"timeseries_limit_metric\"] = metric test_viz", "[\"groupA\", \"groupB\", \"groupC\"] metrics = [\"metric1\", \"metric2\", \"metric3\"] procs =", "\"geohash_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\":", "20}, \"metric3\": {\"a1\": 200, \"b1\": 200, \"c1\": 200}, } self.assertEqual(expected,", "\"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"avg__B\", ], } datasource", "\"10\", }, { \"expressionType\": \"SQL\", \"clause\": \"HAVING\", \"sqlExpression\": \"SUM(value1) >", "DTTM_ALIAS: 200.0, \"metric1\": 5.0, \"metric2\": 50.0, \"metric3\": 500.0, } self.assertEqual(expected,", "\"operator\": \"IS NOT NULL\", \"subject\": \"geo\", \"isExtra\": False, } ],", "df_drop test_viz.process_data = Mock(side_effect=return_args) levels = test_viz.levels_for_time(groups, df) self.assertEqual(4, len(levels))", "name=DTTM_ALIAS) ) def test_cache_timeout(self): datasource = self.get_datasource_mock() datasource.cache_timeout = 0", "{u\"y\": 4, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 4, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\":", "{ \"values\": [ {\"x\": 100, \"y\": 4}, {\"x\": 200, \"y\":", "test_viz = viz.TableViz(datasource, form_data) data = test_viz.get_data(df) # Check method", "} test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual( [\"sum__A\",", "20, 30] df = pd.DataFrame(raw) pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource, form_data) data", "Mock() datasource.type = \"table\" datasource.query = Mock(return_value=results) mock_dttm_col = Mock()", "except in compliance # with the License. You may obtain", "\"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"count\", \"avg__C\", ],", "\"metrics\": [\"\", None]} datasource = self.get_datasource_mock() # Test data raw", "\"b1\", \"c1\", \"c1\", \"c1\"] raw[\"groupB\"] = [\"a2\", \"a2\", \"a2\", \"b2\",", "Mock() test_viz.get_fillna_for_columns = Mock(return_value=0) results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01 05:00:00\"]}) datasource.offset", "test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(ValueError) as context: test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb)", "\"y\": 5}, {\"x\": 300, \"y\": 6}, ], \"group\": (\"b1\", \"b2\",", "= [ \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", ] raw[\"sum__payout\"] = [2,", "= viz.TimeTableViz(datasource, form_data) data = test_viz.get_data(df) # Check method correctly", "fd = {\"metrics\": [\"metric1\"], \"groupby\": [\"groupA\"]} test_viz = viz.RoseViz(Mock(), fd)", "= test_viz_deckgl.get_metrics() assert result == [form_data.get(\"size\")] form_data = {} test_viz_deckgl", "self.get_datasource_mock() form_data = { \"metrics\": [\"colA\", \"colB\"], \"order_desc\": False, }", "test_viz.form_data[\"time_series_option\"] = \"not_time\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" test_viz.get_data(df)", "{ \"values\": [ {\"x\": 100, \"y\": 40}, {\"x\": 200, \"y\":", "license agreements. See the NOTICE file # distributed with this", "\"label\": \"sum_value\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, } ] form_data", "data[\"key\"]) expected_values = [ {\"x\": \"pepperoni\", \"y\": 5}, {\"x\": \"cheese\",", "def test_levels_for_computes_levels(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300,", "required by applicable law or agreed to in writing, #", "NULL_STRING from superset.exceptions import SpatialException from superset.utils.core import DTTM_ALIAS from", "= test_viz.get_data(df)[0] self.assertEqual(\"votes\", data[\"key\"]) expected_values = [ {\"x\": \"pepperoni\", \"y\":", "PairedTTestTestCase(SupersetTestCase): def test_get_data_transforms_dataframe(self): form_data = { \"groupby\": [\"groupA\", \"groupB\", \"groupC\"],", "test_get_data_group_by(self): form_data = {\"metrics\": [\"sum__A\"], \"groupby\": [\"groupby1\"]} datasource = self.get_datasource_mock()", "df = pd.DataFrame( { \"toppings\": [\"cheese\", \"pepperoni\", \"cheese\", \"pepperoni\"], \"role\":", "{ \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\":", "[\"y\"], \"rolling_type\": \"sum\", \"rolling_periods\": 2, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"]", "1, 1, 0, 0)], name=DTTM_ALIAS) ) def test_cache_timeout(self): datasource =", "app from superset.constants import NULL_STRING from superset.exceptions import SpatialException from", "\"value3 in ('North America')\", }, ], } datasource = self.get_datasource_mock()", "2, 3, 4, 5, 6, 7, 8, 9] df =", "5\", }, { \"expressionType\": \"SQL\", \"clause\": \"WHERE\", \"sqlExpression\": \"value3 in", "t2.strftime(time_format): {\"a1\": 30, \"a2\": 35, \"a3\": 40}, } self.assertEqual(expected, data[\"records\"])", "\"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"geo\",", "\"subject\": \"geo\", \"isExtra\": False, } ], } for mock_key in", "\"b3\", \"b3\", \"b3\", \"c3\", \"c3\", \"c3\"] raw[\"metric1\"] = [1, 2,", "def test_parse_adhoc_filters(self): form_data = { \"metrics\": [ { \"expressionType\": \"SIMPLE\",", "index=pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), data={\"y\": [1.0, 2.0, 3.0,", "[ {\"time\": t2, \"value\": 2, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\":", "class PartitionVizTestCase(SupersetTestCase): @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_time_series_option(self, super_query_obj): datasource = self.get_datasource_mock() form_data", "test_viz.get_data(df) self.assertEqual(\"point_percent\", test_viz.levels_for_diff.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_factor\" test_viz.get_data(df) self.assertEqual(\"point_factor\", test_viz.levels_for_diff.mock_calls[2][1][0]) test_viz.levels_for_time", "300, 100, 200, 300, 100, 200, 300] raw[\"groupA\"] = [\"a1\",", "0, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 6.0,", "name=DTTM_ALIAS) ) datasource.offset = 0 results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01\"]}) mock_dttm_col.python_date_format", "self.assertEqual(\"count\", data[\"key\"]) expected_values = [ {\"x\": \"1.0\", \"y\": 42}, {\"x\":", "DistBarVizTestCase(SupersetTestCase): def test_groupby_nulls(self): form_data = { \"metrics\": [\"votes\"], \"adhoc_filters\": [],", "\"a3\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\" expected = { t1.strftime(time_format):", "form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_d = {\"a\": \"dummy1\",", "raw[DTTM_ALIAS] = [t1, t2] raw[\"sum__A\"] = [15, 20] raw[\"count\"] =", "viz_data = test_viz.get_data(df) expected = [ { u\"values\": [ {u\"y\":", "DTTM_ALIAS: {\"a1\": 200, \"c1\": 200, \"b1\": 200}, \"metric1\": {\"a1\": 2,", ") np.testing.assert_equal( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\": \"asfreq\", \"resample_rule\": \"1D\"},", "{ \"groupA\": \"A\", \"groupB\": \"x\", \"SUM(value1)\": 15, \"count\": 6, \"avg__C\":", "with self.assertRaises(Exception): test_viz.query_obj() form_data[\"metrics\"] = [\"x\", \"y\"] test_viz = viz.TimeTableViz(datasource,", "\"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0, 2.0, 0.0, 0.0, 5.0, 0.0,", "SpatialException from superset.utils.core import DTTM_ALIAS from .base_tests import SupersetTestCase from", "{ \"N/A\": [ { \"values\": [ {\"x\": 100, \"y\": 1},", "levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_diff_computes_difference(self): raw = {}", "+ 1), nest[i][\"name\"]) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) def", "= viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics() assert result == [form_data.get(\"size\")]", "# Check method correctly transforms data expected = { \"N/A\":", "= {\"dummy\": 123} query_obj = {\"granularity\": \"day\"} datasource = self.get_datasource_mock()", "('North America')\", }, ], } datasource = self.get_datasource_mock() test_viz =", "form_data) query_obj = test_viz.query_obj() self.assertEqual( [{\"col\": \"value2\", \"val\": \"100\", \"op\":", "True)], query_obj[\"orderby\"]) run_test(\"simple_metric\") run_test( { \"label\": \"adhoc_metric\", \"expressionType\": \"SIMPLE\", \"aggregate\":", "import DTTM_ALIAS from .base_tests import SupersetTestCase from .utils import load_fixture", "300, \"y\": 600}, ], \"group\": (\"b1\", \"b2\", \"b3\"), }, {", "\"name\": (\"a1\",)}, {\"time\": t3, \"value\": 6, \"key\": (\"b1\",), \"name\": (\"b1\",)},", "\"metrics\": [\"y\"], \"rolling_type\": \"mean\", \"rolling_periods\": 10, \"min_periods\": 0, }, )", "20, \"b1\": 20, \"c1\": 20}, \"metric3\": {\"a1\": 200, \"b1\": 200,", "(ASF) under one # or more contributor license agreements. See", "viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"sum\", \"rolling_periods\": 2, \"min_periods\":", "# or more contributor license agreements. See the NOTICE file", "test_viz.levels_for_diff.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_percent\" test_viz.get_data(df) self.assertEqual(\"point_percent\", test_viz.levels_for_diff.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_factor\"", "\"SUM(SE_PRM_NENR_MA)\", \"SUM(SP_URB_TOTL)\"], \"country_fieldtype\": \"cca3\", \"percent_metrics\": [\"count\"], \"slice_id\": 74, \"time_grain_sqla\": None,", "\"C\", \"groupB\": \"z\", \"SUM(value1)\": 40, \"count\": 9, \"avg__C\": 44, \"%SUM(value1)\":", "{\"a1\": 200, \"b1\": 200, \"c1\": 200}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual(4,", "= { \"latlong_key\": {\"type\": \"latlong\", \"lonCol\": \"lon\", \"latCol\": \"lat\"}, \"delimited_key\":", "= pd.DataFrame(raw) groups = [\"groupA\", \"groupB\", \"groupC\"] time_op = \"agg_sum\"", "} datasource = self.get_datasource_mock() df = pd.DataFrame( { \"toppings\": [\"cheese\",", "\"count\": 7}, } self.assertEqual(expected, data[\"records\"]) def test_get_data_group_by(self): form_data = {\"metrics\":", "def test_adhoc_metric_with_sortby(self): metrics = [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\",", "[\"B\", \"C\"] with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj() @patch(\"superset.viz.BaseViz.query_obj\")", "{\"x\": 100, \"y\": 40}, {\"x\": 200, \"y\": 50}, {\"x\": 300,", "[\"groupA\"]} test_viz = viz.RoseViz(Mock(), fd) test_viz.metrics = fd[\"metrics\"] res =", "}, { \"groupA\": \"C\", \"groupB\": \"y\", \"SUM(value1)\": 25, \"count\": 8,", "levels = test_viz.levels_for(\"agg_sum\", groups, df) nest = test_viz.nest_values(levels) self.assertEqual(3, len(nest))", "{\"metrics\": [\"sum__A\", \"count\"], \"groupby\": []} datasource = self.get_datasource_mock() raw =", "= viz.PartitionViz(Mock(), {}) levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels))", "\"order_by_cols\": [], \"groupby\": [\"country_name\"], \"compare_lag\": \"10\", \"limit\": \"25\", \"datasource\": \"2__table\",", "1), nest[i][\"name\"]) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) def test_nest_procs_returns_hierarchy(self):", "700, 800, 900] df = pd.DataFrame(raw) pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource, form_data)", "Madrid Basket\", \"Real Madrid Basket\", ] raw[\"__timestamp\"] = [ \"2018-02-20T00:00:00\",", "\"C\", \"groupB\": \"y\", \"SUM(value1)\": 25, \"count\": 8, \"avg__C\": 33, \"%SUM(value1)\":", "\"aggregate\": \"SUM\", \"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }", "df = pd.DataFrame( index=pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), data={\"y\":", "\"metrics\": [\"y\"], \"rolling_type\": \"sum\", \"rolling_periods\": 2, \"min_periods\": 0, }, )", "1072915200000000000: [ {\"time\": t3, \"value\": 3, \"key\": (\"a1\",), \"name\": (\"a1\",)},", "= [100, 200, 300, 100, 200, 300, 100, 200, 300]", "viz.PartitionViz(Mock(), {}) groups = [\"groupA\", \"groupB\", \"groupC\"] levels = test_viz.levels_for(\"agg_sum\",", "self.assertRaises(Exception): test_viz.query_obj() form_data[\"metrics\"] = [\"x\", \"y\"] test_viz = viz.TimeTableViz(datasource, form_data)", "\"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t2, \"value\": 5, \"key\": (\"b1\",),", "3.0, 4.0]}, ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\":", "\"N/A\": [ { \"values\": [ {\"x\": 100, \"y\": 1}, {\"x\":", "{\"x\": 200, \"y\": 500}, {\"x\": 300, \"y\": 600}, ], \"group\":", "4, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid Basket\",), }, {", "test_viz_deckgl.get_metrics() assert result == [] def test_scatterviz_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\")", "test_viz_deckgl.spatial_control_keys = [mock_key] test_viz_deckgl.add_null_filters() adhoc_filters = test_viz_deckgl.form_data[\"adhoc_filters\"] assert expected_results.get(mock_key) ==", "}, \"count\", \"avg__C\", ], \"percent_metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\":", "\"cheese\", \"pepperoni\"], \"role\": [\"engineer\", \"engineer\", None, None], \"votes\": [3, 5,", "{\"type\": \"delimited\", \"lonlatCol\": \"lonlat\"}, \"geohash_key\": {\"type\": \"geohash\", \"geohashCol\": \"geo\"}, }", "\"dummy3\"} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_js_columns(mock_d) assert result", "test_viz_deckgl.get_js_columns(mock_d) assert result == {\"color\": None} def test_get_properties(self): mock_d =", "\"latlong_key\": {\"type\": \"latlong\", \"lonCol\": \"lon\", \"latCol\": \"lat\"}, \"delimited_key\": {\"type\": \"delimited\",", "PartitionVizTestCase(SupersetTestCase): @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_time_series_option(self, super_query_obj): datasource = self.get_datasource_mock() form_data =", "= viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual(form_data[\"all_columns\"], query_obj[\"columns\"]) self.assertEqual([], query_obj[\"groupby\"])", "result == {\"color\": None} def test_get_properties(self): mock_d = {} form_data", "form_data) data = test_viz.get_data(df) # Check method correctly transforms data", "test_viz.form_data[\"time_series_option\"] = \"adv_anal\" test_viz.get_data(df) self.assertEqual(1, len(test_viz.levels_for_time.mock_calls)) self.assertEqual(1, len(test_viz.nest_procs.mock_calls)) test_viz.form_data[\"time_series_option\"] =", "= \"%Y-%m-%d %H:%M:%S\" expected = { t1.strftime(time_format): {\"sum__A\": 15, \"count\":", "\"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0, 2.0, np.nan, np.nan, 5.0,", "form_data={}) self.assertEqual(app.config[\"CACHE_DEFAULT_TIMEOUT\"], test_viz.cache_timeout) class TableVizTestCase(SupersetTestCase): def test_get_data_applies_percentage(self): form_data = {", "Basket\",), }, { u\"values\": [ {u\"y\": 2, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\":", "5.0, np.nan, 7.0], ) def test_apply_rolling(self): datasource = self.get_datasource_mock() df", "\"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", ] raw[\"sum__payout\"] = [2, 2, 4,", "test_viz.levels_for(\"agg_sum\", groups, df) nest = test_viz.nest_values(levels) self.assertEqual(3, len(nest)) for i", "\"b2\", \"c2\", \"c2\", \"c2\"] raw[\"groupC\"] = [\"a3\", \"a3\", \"a3\", \"b3\",", "form_data = { \"metrics\": metrics, \"timeseries_limit_metric\": { \"expressionType\": \"SIMPLE\", \"aggregate\":", "datasource = self.get_datasource_mock() form_data = { \"metrics\": [\"colA\", \"colB\"], \"order_desc\":", "3, 4, 5, 6, 7, 8, 9] raw[\"metric2\"] = [10,", "expected = { DTTM_ALIAS: 200.0, \"metric1\": 5.0, \"metric2\": 50.0, \"metric3\":", "datasource.offset = 0 mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col) mock_dttm_col.python_date_format", "self.assertEqual( [ \"groupA\", \"groupB\", \"SUM(value1)\", \"count\", \"avg__C\", \"%SUM(value1)\", \"%avg__B\", ],", "mock_key = \"spatial_key\" mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data)", "\"c2\", \"c3\"), }, ], \"metric3\": [ { \"values\": [ {\"x\":", "0.0, 0.0, 5.0, 0.0, 7.0], ) np.testing.assert_equal( viz.NVD3TimeSeriesViz( datasource, {\"metrics\":", "test_viz = viz.TableViz(datasource, form_data) data = test_viz.get_data(df) self.assertEqual([\"sum_value\"], data[\"columns\"]) class", "(\"a1\",), \"name\": (\"a1\",)}, {\"time\": t3, \"value\": 6, \"key\": (\"b1\",), \"name\":", "= {\"granularity\": \"day\"} datasource = self.get_datasource_mock() test_viz = viz.BaseViz(datasource, form_data)", "test_query_obj_time_series_option(self, super_query_obj): datasource = self.get_datasource_mock() form_data = {} test_viz =", "\"c1\": 8}, \"metric2\": {\"a1\": 20, \"b1\": 50, \"c1\": 80}, \"metric3\":", "df) expected = {\"metric1\": 6, \"metric2\": 60, \"metric3\": 600} self.assertEqual(expected,", "\"SUM\", \"label\": \"sum_value\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, } ]", "self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS: {\"a1\": 600, \"b1\": 600,", "\"B\"], \"metrics\": [\"x\", \"y\"]} with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data)", "def test_filter_nulls(self, mock_uuid4): mock_uuid4.return_value = uuid.UUID(\"12345678123456781234567812345678\") test_form_data = { \"latlong_key\":", "24}, \"metric2\": {\"a1\": 60, \"b1\": 150, \"c1\": 240}, \"metric3\": {\"a1\":", "\"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid Basket\", \"Real", "\"SIMPLE\", \"aggregate\": \"SUM\", \"column\": {\"column_name\": \"sort_column\",}, } ) def test_should_be_timeseries_raises_when_no_granularity(self):", "str(i + 1), nest[i][\"name\"]) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"]))", "{\"x\": 200, \"y\": 50}, {\"x\": 300, \"y\": 60}, ], \"group\":", "= [\"a1\", \"a1\", \"a1\", \"b1\", \"b1\", \"b1\", \"c1\", \"c1\", \"c1\"]", "{} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {} result =", "3}, ], \"group\": \"All\", } ], \"NULL\": [ { \"values\":", "= [ {\"x\": \"1.0\", \"y\": 42}, {\"x\": \"0.0\", \"y\": 30},", "\"y\": [1.0, 2.0, 3.0, 4.0], } ) data = viz.BigNumberViz(datasource,", "columns=groups[:i], values=metrics ) procs[i] = pivot nest = test_viz.nest_procs(procs) self.assertEqual(3,", "self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics() assert result", "[1.0, 2.0, np.nan, np.nan, 5.0, np.nan, 7.0], ) def test_apply_rolling(self):", "{ \"key\": \"engineer\", \"values\": [{\"x\": \"pepperoni\", \"y\": 5}, {\"x\": \"cheese\",", "self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"(SUM(value1) > 5)\", query_obj[\"extras\"][\"having\"]) def", "{\"x\": 300, \"y\": 300}, ], \"group\": (\"a1\", \"a2\", \"a3\"), },", "= None with self.assertRaises(Exception): viz.BaseViz(datasource, form_data) def test_process_metrics(self): # test", "viz.TableViz(datasource, form_data) test_viz.query_obj() del form_data[\"metrics\"] form_data[\"groupby\"] = [\"B\", \"C\"] with", "\"sort_column\",}, } ) def test_should_be_timeseries_raises_when_no_granularity(self): datasource = self.get_datasource_mock() form_data =", "\"group\": \"All\", } ], \"NULL\": [ { \"values\": [ {\"x\":", "42}, {\"x\": \"0.0\", \"y\": 30}, {\"x\": \"2.0\", \"y\": 29}, {\"x\":", "test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data.copy()) test_viz_deckgl.spatial_control_keys = [mock_key] test_viz_deckgl.add_null_filters() adhoc_filters =", "\"latlong_key\": [\"lon\", \"lat\"], \"delimited_key\": [\"lonlat\"], \"geohash_key\": [\"geo\"], } for mock_key", "= {\"metrics\": [\"sum__A\"], \"groupby\": [\"groupby1\"]} datasource = self.get_datasource_mock() raw =", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "\"groupB\", \"SUM(value1)\", \"count\", \"avg__C\", \"%SUM(value1)\", \"%avg__B\", ], list(data[\"columns\"]), ) expected", "method correctly transforms data expected = { \"metric1\": [ {", "\"count\": 7, \"avg__C\": 22, \"%SUM(value1)\": 0.2, \"%avg__B\": 0.4, }, {", "] raw[\"__timestamp\"] = [ \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", ] raw[\"sum__payout\"]", "datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"cumsum\", \"rolling_periods\": 0, \"min_periods\": 0,", "\"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_diff_computes_difference(self): raw =", "\">\"}], query_obj[\"filter\"] ) self.assertEqual( [{\"op\": \"<\", \"val\": \"10\", \"col\": \"SUM(value1)\"}],", "pd.DataFrame) self.assertTrue(result.empty) def test_get_df_handles_dttm_col(self): form_data = {\"dummy\": 123} query_obj =", "\"value1\", \"type\": \"DOUBLE\"}, } ] form_data = { \"metrics\": metrics,", "pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t1, t1, t2, t2, t2] raw[\"sum__A\"]", "self.get_datasource_mock() expected_results = { \"latlong_key\": [\"lon\", \"lat\"], \"delimited_key\": [\"lonlat\"], \"geohash_key\":", "[\"votes\"], \"adhoc_filters\": [], \"groupby\": [\"toppings\"], \"columns\": [\"role\"], } datasource =", "self.get_datasource_mock() mock_key = \"spatial_key\" mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource,", "2], } ) test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0]", "= { \"url_params\": {}, \"row_limit\": 500, \"metric\": \"sum__SP_POP_TOTL\", \"entity\": \"country_code\",", "= pd.DataFrame(raw) test_viz = viz.PartitionViz(Mock(), {}) groups = [\"groupA\", \"groupB\",", "\"point_factor\" test_viz.get_data(df) self.assertEqual(\"point_factor\", test_viz.levels_for_diff.mock_calls[2][1][0]) test_viz.levels_for_time = Mock(return_value=1) test_viz.nest_procs = Mock(return_value=1)", "{ \"latlong_key\": {\"type\": \"latlong\", \"lonCol\": \"lon\", \"latCol\": \"lat\"}, \"delimited_key\": {\"type\":", "\"2018-03-09T00:00:00\", ] raw[\"sum__payout\"] = [2, 2, 4, 4] df =", "result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 0, 0)], name=DTTM_ALIAS) ) def test_cache_timeout(self):", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "raw[None] = [10, 20, 30] df = pd.DataFrame(raw) pairedTTestViz =", "form_data[\"timeseries_limit_metric\"] = metric test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj()", "Basket\", \"Real Madrid Basket\", ] raw[\"__timestamp\"] = [ \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\",", "} def run_test(metric): form_data[\"timeseries_limit_metric\"] = metric test_viz = viz.TableViz(datasource, form_data)", "60, 70, 80, 90] raw[\"metric3\"] = [100, 200, 300, 400,", "\"b1\": 20, \"c1\": 20}, \"metric3\": {\"a1\": 200, \"b1\": 200, \"c1\":", "DTTM_ALIAS: pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0,", "the Apache License, Version 2.0 (the # \"License\"); you may", "pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 6, 0)], name=DTTM_ALIAS) ) datasource.offset", "correctly transforms data expected = { \"N/A\": [ { \"values\":", "= pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource, form_data) data = test_viz.get_data(df) #", "\"metric2\": 50.0, \"metric3\": 500.0, } self.assertEqual(expected, levels[0].to_dict()) expected = {", "300] raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\", \"b1\", \"b1\", \"c1\",", "load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() viz_instance = viz.BaseDeckGLViz(datasource, form_data) coord =", "query_obj[\"metrics\"]) self.assertEqual([(metric, True)], query_obj[\"orderby\"]) run_test(\"simple_metric\") run_test( { \"label\": \"adhoc_metric\", \"expressionType\":", "index=DTTM_ALIAS, columns=groups[:i], values=metrics ) procs[i] = pivot nest = test_viz.nest_procs(procs)", "you under the Apache License, Version 2.0 (the # \"License\");", "datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics()", "\"value2\", \"operator\": \">\", \"comparator\": \"100\", }, { \"expressionType\": \"SIMPLE\", \"clause\":", "\"%Y-%m-%d %H:%M:%S\" expected = { t1.strftime(time_format): {\"sum__A\": 15, \"count\": 6},", "\"SUM(value1) > 5\", } datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource,", "\"\", \"operator\": \"IS NOT NULL\", \"subject\": \"geo\", \"isExtra\": False, }", "\"DOUBLE\"}, } ], \"adhoc_filters\": [ { \"expressionType\": \"SIMPLE\", \"clause\": \"WHERE\",", "coord = viz_instance.parse_coordinates(\"1.23 3.21\") self.assertEqual(coord, (1.23, 3.21)) self.assertEqual(viz_instance.parse_coordinates(None), None) self.assertEqual(viz_instance.parse_coordinates(\"\"),", "(\"b1\",), \"name\": (\"b1\",)}, {\"time\": t3, \"value\": 9, \"key\": (\"c1\",), \"name\":", "spatial key\" in str(context.exception)) test_form_data = { \"latlong_key\": {\"type\": \"latlong\",", "5, 0)], name=DTTM_ALIAS) ) mock_dttm_col.python_date_format = None result = test_viz.get_df(query_obj)", "= viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(ValueError) as context: test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) self.assertTrue(\"Bad", "\"y\": 5}, {\"x\": \"cheese\", \"y\": 3}, {\"x\": NULL_STRING, \"y\": 2},", "= {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {} result", "{\"time\": t1, \"value\": 1, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t1,", "= { \"metric1\": {\"a1\": 2, \"b1\": 2, \"c1\": 2}, \"metric2\":", "test_query_obj_uses_sortby(self): datasource = self.get_datasource_mock() form_data = { \"metrics\": [\"colA\", \"colB\"],", "= [10, 20, 30, 40, 50, 60, 70, 80, 90]", "\"group\": (\"c1\", \"c2\", \"c3\"), }, ], \"metric3\": [ { \"values\":", "None, 4.0], } ) data = viz.BigNumberViz(datasource, {\"metrics\": [\"y\"]}).get_data(df) assert", "# Unless required by applicable law or agreed to in", "], list(data[\"columns\"]), ) expected = [ { \"groupA\": \"A\", \"groupB\":", "500, 600, 700, 800, 900] df = pd.DataFrame(raw) test_viz =", "\"y\": 1}], }, { \"key\": \"engineer\", \"values\": [{\"x\": \"pepperoni\", \"y\":", "\"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"column\": {\"column_name\": \"sort_column\",}, } ) def", "= test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS)", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "= [ \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid", "5.0, 7.0], } ) self.assertEqual( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\":", "def test_levels_for_diff_computes_difference(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300,", "\"geohash_key\"]: mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data) test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb)", "} ], } for mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: test_viz_deckgl", "datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) data = test_viz.get_data(df)", "(\"b1\",)}, {\"time\": t1, \"value\": 7, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ],", "300, \"y\": 6}, ], \"group\": (\"b1\", \"b2\", \"b3\"), }, {", "df = Mock() with self.assertRaises(ValueError): test_viz.get_data(df) test_viz.levels_for = Mock(return_value=1) test_viz.nest_values", "\"HAVING\", \"subject\": \"SUM(value1)\", \"operator\": \"<\", \"comparator\": \"10\", }, { \"expressionType\":", "700}, {\"x\": 200, \"y\": 800}, {\"x\": 300, \"y\": 900}, ],", "\"not_time\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[1][1][0])", "sorted(levels[2].columns.tolist())) cols += [\"groupC\"] self.assertEqual(sorted(cols), sorted(levels[3].columns.tolist())) self.assertEqual(4, len(test_viz.process_data.mock_calls)) def test_nest_values_returns_hierarchy(self):", "self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) time_op = \"agg_mean\"", "= viz.TableViz(datasource, form_data) test_viz.should_be_timeseries() def test_adhoc_metric_with_sortby(self): metrics = [ {", "= { \"metrics\": [\"colA\", \"colB\"], \"order_desc\": False, } def run_test(metric):", "\"b3\", \"c3\", \"c3\", \"c3\"] raw[\"metric1\"] = [1, 2, 3, 4,", "}, { \"expressionType\": \"SQL\", \"clause\": \"HAVING\", \"sqlExpression\": \"SUM(value1) > 5\",", "test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 6, 0)], name=DTTM_ALIAS) )", "{ \"metrics\": metrics, \"timeseries_limit_metric\": { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\":", "100, \"y\": 70}, {\"x\": 200, \"y\": 80}, {\"x\": 300, \"y\":", "= [t1, t2] raw[\"sum__A\"] = [15, 20] raw[\"count\"] = [6,", "= 0 results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01\"]}) mock_dttm_col.python_date_format = \"%Y-%m-%d\" result", "test_form_data) test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) assert expected_results.get(mock_key) == mock_gb def test_geojson_query_obj(self): form_data", "method correctly transforms data self.assertEqual(set([\"count\", \"sum__A\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d", "[15], \"sum_value\": [15]}) datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data)", "[6, 7, 8, 9], \"groupA\": [\"A\", \"B\", \"C\", \"C\"], \"groupB\":", "def test_parse_coordinates_raises(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl =", "df = pd.DataFrame( { \"SUM(value1)\": [15, 20, 25, 40], \"avg__B\":", "[\"groupA\", \"groupB\", \"groupC\"] time_op = \"agg_sum\" test_viz = viz.PartitionViz(Mock(), {})", "4}, {\"x\": 200, \"y\": 5}, {\"x\": 300, \"y\": 6}, ],", "result == [] def test_get_js_columns(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource =", "3): self.assertEqual(\"metric\" + str(i + 1), nest[i][\"name\"]) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(1,", "{\"time\": t1, \"value\": 4, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t1,", "more contributor license agreements. See the NOTICE file # distributed", "superset.viz as viz from superset import app from superset.constants import", "{\"x\": 300, \"y\": 3}, ], \"group\": \"All\", } ], \"NULL\":", "superset.exceptions import SpatialException from superset.utils.core import DTTM_ALIAS from .base_tests import", ") datasource.offset = 1 result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960,", "\"geo\"}, } datasource = self.get_datasource_mock() expected_results = { \"latlong_key\": [", "\"b2\", \"b3\"), }, { \"values\": [ {\"x\": 100, \"y\": 70},", "{u\"y\": 2, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid C.F.\\U0001f1fa\\U0001f1f8\\U0001f1ec\\U0001f1e7\",), },", "= [\"x\", \"y\"] test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj()", "datasource.get_column = Mock(return_value=mock_dttm_col) mock_dttm_col.python_date_format = \"epoch_ms\" result = test_viz.get_df(query_obj) import", "test_viz_deckgl.parse_coordinates(\"fldkjsalkj,fdlaskjfjadlksj\") @patch(\"superset.utils.core.uuid.uuid4\") def test_filter_nulls(self, mock_uuid4): mock_uuid4.return_value = uuid.UUID(\"12345678123456781234567812345678\") test_form_data =", "1500, \"c1\": 2400}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\",", "\"geohash_key\": {\"type\": \"geohash\", \"geohashCol\": \"geo\"}, } datasource = self.get_datasource_mock() expected_results", "\"compare_lag\": \"10\", \"limit\": \"25\", \"datasource\": \"2__table\", \"table_timestamp_format\": \"%Y-%m-%d %H:%M:%S\", \"markup_type\":", "200, 300, 400, 500, 600, 700, 800, 900] df =", "with self.assertRaises(NotImplementedError) as context: test_viz_deckgl.get_properties(mock_d) self.assertTrue(\"\" in str(context.exception)) def test_process_spatial_query_obj(self):", "data={ DTTM_ALIAS: pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0,", "test_filter_nulls(self, mock_uuid4): mock_uuid4.return_value = uuid.UUID(\"12345678123456781234567812345678\") test_form_data = { \"latlong_key\": {\"type\":", "\"\", \"compare_suffix\": \"o10Y\", } datasource = Mock() datasource.type = \"table\"", "specific language governing permissions and limitations # under the License.", "test_viz.levels_for_diff.mock_calls[2][1][0]) test_viz.levels_for_time = Mock(return_value=1) test_viz.nest_procs = Mock(return_value=1) test_viz.form_data[\"time_series_option\"] = \"adv_anal\"", "pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource, form_data) data = test_viz.get_data(df) # Check", "= viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() class BaseDeckGLVizTestCase(SupersetTestCase): def test_get_metrics(self):", "pd.DataFrame({\"SUM(value1)\": [15], \"sum_value\": [15]}) datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource,", "], \"group\": \"All\", } ], } self.assertEqual(data, expected) class PartitionVizTestCase(SupersetTestCase):", "assert expected_results.get(mock_key) == mock_gb def test_geojson_query_obj(self): form_data = load_fixture(\"deck_geojson_form_data.json\") datasource", "{}) levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected =", "Mock() results.query = Mock() results.status = Mock() results.error_message = Mock()", "\"groupby\": [\"beds\"], \"columns\": [], } datasource = self.get_datasource_mock() df =", "self.get_datasource_mock() datasource.cache_timeout = 0 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(0, test_viz.cache_timeout)", "test_viz.levels_for_time(groups, df) self.assertEqual(4, len(levels)) cols = [DTTM_ALIAS, \"metric1\", \"metric2\", \"metric3\"]", "mock_gb def test_geojson_query_obj(self): form_data = load_fixture(\"deck_geojson_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl", "[\"colA\", \"colB\"], \"order_desc\": False, } def run_test(metric): form_data[\"timeseries_limit_metric\"] = metric", "500, \"c1\": 800}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\",", "def test_query_obj_throws_columns_and_metrics(self): datasource = self.get_datasource_mock() form_data = {\"all_columns\": [\"A\", \"B\"],", "{ \"latlong_key\": [\"lon\", \"lat\"], \"delimited_key\": [\"lonlat\"], \"geohash_key\": [\"geo\"], } for", "distributed with this work for additional information # regarding copyright", "} datasource = self.get_datasource_mock() expected_results = { \"latlong_key\": [\"lon\", \"lat\"],", "def test_parse_coordinates(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() viz_instance =", "[ \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", ] raw[\"sum__payout\"] = [2, 2,", "Madrid Basket\",), }, { u\"values\": [ {u\"y\": 2, u\"x\": u\"2018-02-20T00:00:00\"},", "\"secondary_metric\": \"sum__SP_POP_TOTL\", \"granularity_sqla\": \"year\", \"page_length\": 0, \"all_columns\": [], \"viz_type\": \"table\",", "raw[\"name\"] = [ \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real", "{\"time\": t3, \"value\": 3, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t3,", "datasource = self.get_datasource_mock() mock_key = \"spatial_key\" mock_gb = [] test_viz_deckgl", "{\"metrics\": [\"y\"]}).get_data(df) self.assertEqual(data[2], {DTTM_ALIAS: pd.Timestamp(\"2019-01-05\"), \"y\": 3}) def test_get_data_with_none(self): datasource", "for the # specific language governing permissions and limitations #", "= self.get_datasource_mock() form_data = {} test_viz = viz.PartitionViz(datasource, form_data) super_query_obj.return_value", "= { DTTM_ALIAS: {\"a1\": 200, \"c1\": 200, \"b1\": 200}, \"metric1\":", "\"values\": [ {\"x\": 100, \"y\": 100}, {\"x\": 200, \"y\": 200},", "[\"sum__A\", \"avg__B\", \"max__Y\"], } test_viz = viz.TableViz(datasource, form_data) query_obj =", "self.assertEqual(\"votes\", data[\"key\"]) expected_values = [ {\"x\": \"pepperoni\", \"y\": 5}, {\"x\":", "\"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t1, \"value\": 7, \"key\": (\"c1\",),", "} for mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: mock_gb = []", "\"adhoc_filters\": [], \"groupby\": [\"toppings\"], \"columns\": [\"role\"], } datasource = self.get_datasource_mock()", "class BaseVizTestCase(SupersetTestCase): def test_constructor_exception_no_datasource(self): form_data = {} datasource = None", "\"name\": (\"a1\",)}, {\"time\": t2, \"value\": 5, \"key\": (\"b1\",), \"name\": (\"b1\",)},", "\"group\": (\"a1\", \"a2\", \"a3\"), }, { \"values\": [ {\"x\": 100,", "groups = [\"groupA\", \"groupB\", \"groupC\"] test_viz = viz.PartitionViz(Mock(), {\"groupby\": groups})", "{\"x\": 300, \"y\": 30}, ], \"group\": \"All\", } ], }", "test_parse_coordinates_raises(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource,", "= test_viz.get_data(df) expected = [ { u\"values\": [ {u\"y\": 4,", "pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource, form_data) data = pairedTTestViz.get_data(df) # Check method", "= self.get_datasource_mock() test_viz = viz.BaseViz(datasource, form_data) result = test_viz.get_df(query_obj) self.assertEqual(type(result),", "self.assertEqual(expected, levels[1].to_dict()) self.assertEqual(4, len(levels)) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_time_calls_process_data_and_drops_cols(self):", "self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) time_op = \"agg_mean\" levels = test_viz.levels_for(time_op,", "{ \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\",", "[{\"col\": \"value2\", \"val\": \"100\", \"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual( [{\"op\":", "\"key\": \"engineer\", \"values\": [{\"x\": \"pepperoni\", \"y\": 5}, {\"x\": \"cheese\", \"y\":", "{\"x\": 300, \"y\": 60}, ], \"group\": (\"b1\", \"b2\", \"b3\"), },", "pd.DataFrame(raw) groups = [\"groupA\", \"groupB\", \"groupC\"] test_viz = viz.PartitionViz(Mock(), {})", "0)], name=DTTM_ALIAS) ) def test_cache_timeout(self): datasource = self.get_datasource_mock() datasource.cache_timeout =", "self.assertEqual(expected, viz_data) def test_process_data_resample(self): datasource = self.get_datasource_mock() df = pd.DataFrame(", "\"type\": \"DOUBLE\"}, } ], \"adhoc_filters\": [ { \"expressionType\": \"SIMPLE\", \"clause\":", "form_data) query_obj = test_viz.query_obj() self.assertEqual(form_data[\"all_columns\"], query_obj[\"columns\"]) self.assertEqual([], query_obj[\"groupby\"]) self.assertEqual([[\"colA\", \"colB\"],", "under the License. # isort:skip_file import uuid from datetime import", "math import nan from unittest.mock import Mock, patch import numpy", "= load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_key = \"spatial_key\" mock_gb =", "== [] def test_get_js_columns(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock()", "Mock(return_value=1) test_viz.get_data(df) self.assertEqual(\"point_diff\", test_viz.levels_for_diff.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_percent\" test_viz.get_data(df) self.assertEqual(\"point_percent\", test_viz.levels_for_diff.mock_calls[1][1][0])", "result = test_viz_deckgl.get_metrics() assert result == [\"int\"] form_data = {}", "29]}) test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"count\", data[\"key\"])", "} ], \"NULL\": [ { \"values\": [ {\"x\": 100, \"y\":", "{} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics() assert result", "{\"type\": \"metric\", \"value\": \"int\"} result = test_viz_deckgl.get_metrics() assert result ==", "i in range(0, 3): self.assertEqual(\"metric\" + str(i + 1), nest[i][\"name\"])", "query_obj = test_viz.query_obj() self.assertFalse(query_obj[\"is_timeseries\"]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" query_obj = test_viz.query_obj()", "groups, df) self.assertEqual(4, len(levels)) expected = { DTTM_ALIAS: 200.0, \"metric1\":", "\"metric1\": [ { \"values\": [ {\"x\": 100, \"y\": 1}, {\"x\":", "= \"agg_sum\" test_viz = viz.PartitionViz(Mock(), {}) levels = test_viz.levels_for(time_op, groups,", "\"y\": 2}, {\"x\": \"anchovies\", \"y\": 1}, ] self.assertEqual(expected_values, data[\"values\"]) def", "), data={\"y\": [1.0, 2.0, 3.0, 4.0]}, ) self.assertEqual( viz.BigNumberViz( datasource,", "= [\"B\", \"C\"] with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj()", "\"a1\", \"a1\", \"b1\", \"b1\", \"b1\", \"c1\", \"c1\", \"c1\"] raw[\"groupB\"] =", "= test_viz.get_data(df) self.assertEqual([\"sum_value\"], data[\"columns\"]) class DistBarVizTestCase(SupersetTestCase): def test_groupby_nulls(self): form_data =", "assert result == [form_data.get(\"size\")] form_data = {} test_viz_deckgl = viz.BaseDeckGLViz(datasource,", "\"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lon\", \"isExtra\": False, },", "to you under the Apache License, Version 2.0 (the #", "test_query_obj_merges_percent_metrics(self): datasource = self.get_datasource_mock() form_data = { \"metrics\": [\"sum__A\", \"count\",", "data[\"records\"]) def test_get_data_group_by(self): form_data = {\"metrics\": [\"sum__A\"], \"groupby\": [\"groupby1\"]} datasource", "query_obj[\"groupby\"]) self.assertEqual([[\"colA\", \"colB\"], [\"colC\"]], query_obj[\"orderby\"]) def test_query_obj_uses_sortby(self): datasource = self.get_datasource_mock()", "}, { \"expressionType\": \"SQL\", \"clause\": \"WHERE\", \"sqlExpression\": \"value3 in ('North", "\"count\": 9, \"avg__C\": 44, \"%SUM(value1)\": 0.4, \"%avg__B\": 0.3, }, ]", "\"geohash\", \"geohashCol\": \"geo\"}, } datasource = self.get_datasource_mock() expected_results = {", "may not use this file except in compliance # with", "t2, \"value\": 5, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t2, \"value\":", "= {\"groupby\": [], \"metrics\": [\"\", None]} datasource = self.get_datasource_mock() #", "{ \"groupby\": [\"groupA\", \"groupB\", \"groupC\"], \"metrics\": [\"metric1\", \"metric2\", \"metric3\"], }", "20, 30, 40, 50, 60, 70, 80, 90] raw[\"metric3\"] =", "test_rose_vis_get_data(self): raw = {} t1 = pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\")", "{\"x\": 300, \"y\": 600}, ], \"group\": (\"b1\", \"b2\", \"b3\"), },", "logging.getLogger(__name__) class BaseVizTestCase(SupersetTestCase): def test_constructor_exception_no_datasource(self): form_data = {} datasource =", "\"metrics\": [\"colA\", \"colB\"], \"order_desc\": False, } def run_test(metric): form_data[\"timeseries_limit_metric\"] =", "\"y\": 29}, {\"x\": NULL_STRING, \"y\": 3}, ] self.assertEqual(expected_values, data[\"values\"]) def", "{}) df = Mock() with self.assertRaises(ValueError): test_viz.get_data(df) test_viz.levels_for = Mock(return_value=1)", "5, 1, 2], } ) test_viz = viz.DistributionBarViz(datasource, form_data) data", "\"resample_method\": \"asfreq\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0, 2.0, np.nan,", ") self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"mean\", \"rolling_periods\":", "np.nan, 5.0, np.nan, 7.0], ) def test_apply_rolling(self): datasource = self.get_datasource_mock()", "\"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lon\", \"isExtra\": False,", "\"c1\": 200}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual(4, len(levels)) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"],", "self.get_datasource_mock() df = pd.DataFrame( { \"toppings\": [\"cheese\", \"pepperoni\", \"cheese\", \"pepperoni\"],", "\"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"count\", \"avg__C\", ], \"percent_metrics\":", "expected_results = { \"latlong_key\": [\"lon\", \"lat\"], \"delimited_key\": [\"lonlat\"], \"geohash_key\": [\"geo\"],", "[mock_key] test_viz_deckgl.add_null_filters() adhoc_filters = test_viz_deckgl.form_data[\"adhoc_filters\"] assert expected_results.get(mock_key) == adhoc_filters class", "test_viz.metrics = fd[\"metrics\"] res = test_viz.get_data(df) expected = { 946684800000000000:", "\"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"sum_value\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"},", "20, \"a3\": 25}, t2.strftime(time_format): {\"a1\": 30, \"a2\": 35, \"a3\": 40},", "\"clause\": \"HAVING\", \"subject\": \"SUM(value1)\", \"operator\": \"<\", \"comparator\": \"10\", }, {", "\"pepperoni\", \"y\": 2}, {\"x\": \"cheese\", \"y\": 1}], }, { \"key\":", "Basket\", ] raw[\"__timestamp\"] = [ \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", ]", "additional information # regarding copyright ownership. The ASF licenses this", "datasource = None with self.assertRaises(Exception): viz.BaseViz(datasource, form_data) def test_process_metrics(self): #", "\"geohash_key\": [\"geo\"], } for mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: mock_gb", "\"groupby\": [\"groupA\"]} test_viz = viz.RoseViz(Mock(), fd) test_viz.metrics = fd[\"metrics\"] res", "0.4, }, { \"groupA\": \"C\", \"groupB\": \"y\", \"SUM(value1)\": 25, \"count\":", ") procs[i] = pivot nest = test_viz.nest_procs(procs) self.assertEqual(3, len(nest)) for", "\"y\": 70}, {\"x\": 200, \"y\": 80}, {\"x\": 300, \"y\": 90},", "= {} raw[\"name\"] = [ \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid", "{\"a1\": 2, \"b1\": 2, \"c1\": 2}, \"metric2\": {\"a1\": 20, \"b1\":", "form_data) test_viz.should_be_timeseries() def test_adhoc_metric_with_sortby(self): metrics = [ { \"expressionType\": \"SIMPLE\",", "29}, {\"x\": NULL_STRING, \"y\": 3}, ] self.assertEqual(expected_values, data[\"values\"]) def test_column_nulls(self):", "\"b2\", \"b2\", \"c2\", \"c2\", \"c2\"] raw[\"groupC\"] = [\"a3\", \"a3\", \"a3\",", "t1, t2, t3, t1, t2, t3] raw[\"groupA\"] = [\"a1\", \"a1\",", "{ \"metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\",", "600, \"c1\": 600}, \"metric1\": {\"a1\": 6, \"b1\": 15, \"c1\": 24},", "t1, t2, t3] raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\", \"b1\",", "50.0, \"metric3\": 500.0, } self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS:", "= Mock(return_value=1) test_viz.form_data[\"time_series_option\"] = \"adv_anal\" test_viz.get_data(df) self.assertEqual(1, len(test_viz.levels_for_time.mock_calls)) self.assertEqual(1, len(test_viz.nest_procs.mock_calls))", "viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(ValueError) as context: test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) self.assertTrue(\"Bad spatial", "\"y\": 6}, ], \"group\": (\"b1\", \"b2\", \"b3\"), }, { \"values\":", "mock_d = {\"a\": \"dummy1\", \"b\": \"dummy2\", \"c\": \"dummy3\"} test_viz_deckgl =", "20, 25, 40], \"avg__B\": [10, 20, 5, 15], \"avg__C\": [11,", "\"adhoc_filters\": [], \"groupby\": [\"toppings\"], \"columns\": [], } datasource = self.get_datasource_mock()", "[\"A\", \"B\"], \"metrics\": [\"x\", \"y\"]} with self.assertRaises(Exception): test_viz = viz.TableViz(datasource,", "Mock() results.status = Mock() results.error_message = Mock() datasource = Mock()", "\"cheese\", \"y\": 3}], }, ] self.assertEqual(expected, data) class PairedTTestTestCase(SupersetTestCase): def", "\"values\": [ {\"x\": 100, \"y\": 1}, {\"x\": 200, \"y\": 2},", "\"groupB\", \"groupC\"] test_viz = viz.PartitionViz(Mock(), {\"groupby\": groups}) def return_args(df_drop, aggregate):", "form_data) test_viz_deckgl.point_radius_fixed = {\"type\": \"metric\", \"value\": \"int\"} result = test_viz_deckgl.get_metrics()", "# specific language governing permissions and limitations # under the", "result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 6, 0)], name=DTTM_ALIAS) ) datasource.offset =", "\"SUM(value1)\", \"operator\": \"<\", \"comparator\": \"10\", }, { \"expressionType\": \"SQL\", \"clause\":", "as np import pandas as pd import tests.test_app import superset.viz", "datasource = self.get_datasource_mock() df = pd.DataFrame( data={ DTTM_ALIAS: pd.to_datetime( [\"2019-01-01\",", "[15]}) datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) data =", "\"groupC\"] levels = test_viz.levels_for(\"agg_sum\", groups, df) nest = test_viz.nest_values(levels) self.assertEqual(3,", "datasource = self.get_datasource_mock() form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data)", "self.assertRaises(Exception): viz.BaseViz(datasource, form_data) def test_process_metrics(self): # test TableViz metrics in", "you may not use this file except in compliance #", "u\"SUM(SE_PRM_NENR_MA)\", u\"SUM(SP_URB_TOTL)\", u\"count\", ] self.assertEqual(test_viz.metric_labels, expect_metric_labels) self.assertEqual(test_viz.all_metrics, expect_metric_labels) def test_get_df_returns_empty_df(self):", "RoseVisTestCase(SupersetTestCase): def test_rose_vis_get_data(self): raw = {} t1 = pd.Timestamp(\"2000\") t2", "\"comparator\": \"10\", }, { \"expressionType\": \"SQL\", \"clause\": \"HAVING\", \"sqlExpression\": \"SUM(value1)", "metric test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual([\"colA\", \"colB\",", "= {} datasource = None with self.assertRaises(Exception): viz.BaseViz(datasource, form_data) def", "t3, t1, t2, t3, t1, t2, t3] raw[\"groupA\"] = [\"a1\",", "} ) test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df) expected", "self.get_datasource_mock() # Test data raw = {} raw[DTTM_ALIAS] = [100,", "\"avg__C\", ], \"percent_metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\":", "\"metric3\": 600} self.assertEqual(expected, levels[0].to_dict()) expected = { \"metric1\": {\"a1\": 2,", "\"having\": \"SUM(value1) > 5\", } datasource = self.get_datasource_mock() test_viz =", "self.assertEqual(test_viz.all_metrics, expect_metric_labels) def test_get_df_returns_empty_df(self): form_data = {\"dummy\": 123} query_obj =", "= {\"all_columns\": [\"A\", \"B\"], \"metrics\": [\"x\", \"y\"]} with self.assertRaises(Exception): test_viz", "form_data = {} test_viz = viz.PartitionViz(datasource, form_data) super_query_obj.return_value = {}", "\"agg_sum\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_mean\" test_viz.get_data(df) self.assertEqual(\"agg_mean\", test_viz.levels_for.mock_calls[2][1][0])", "self.assertEqual([\"colA\", \"colB\", metric], query_obj[\"metrics\"]) self.assertEqual([(metric, True)], query_obj[\"orderby\"]) run_test(\"simple_metric\") run_test( {", "with self.assertRaises(Exception): test_viz.query_obj() class BaseDeckGLVizTestCase(SupersetTestCase): def test_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\")", "viz_data = {} viz_data = test_viz.get_data(df) expected = [ {", "df = pd.DataFrame( { \"__timestamp\": pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"]", "100, 200, 300, 100, 200, 300] raw[\"groupA\"] = [\"a1\", \"a1\",", "\"groupby\": [\"groupA\", \"groupB\", \"groupC\"], \"metrics\": [\"metric1\", \"metric2\", \"metric3\"], } datasource", ".tolist(), [1.0, 2.0, 0.0, 0.0, 5.0, 0.0, 7.0], ) np.testing.assert_equal(", "= {} viz_data = test_viz.get_data(df) expected = [ { u\"values\":", "{\"a\": \"dummy1\", \"b\": \"dummy2\", \"c\": \"dummy3\"} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data)", "\"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\":", "{\"time\": t2, \"value\": 2, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t2,", "test_viz = viz.BaseViz(datasource, form_data) result = test_viz.get_df(query_obj) self.assertEqual(type(result), pd.DataFrame) self.assertTrue(result.empty)", "result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 0, 0)],", "form_data) query_obj = test_viz.query_obj() self.assertEqual([\"colA\", \"colB\", metric], query_obj[\"metrics\"]) self.assertEqual([(metric, True)],", "\"country_fieldtype\": \"cca3\", \"percent_metrics\": [\"count\"], \"slice_id\": 74, \"time_grain_sqla\": None, \"order_by_cols\": [],", "\"subject\": \"value2\", \"operator\": \">\", \"comparator\": \"100\", }, { \"expressionType\": \"SQL\",", "[ {\"x\": 100, \"y\": 40}, {\"x\": 200, \"y\": 50}, {\"x\":", "= {} for i in range(0, 4): df_drop = df.drop(groups[i:],", "from unittest.mock import Mock, patch import numpy as np import", "with this work for additional information # regarding copyright ownership.", "form_data) test_viz.df_metrics_to_num = Mock() test_viz.get_fillna_for_columns = Mock(return_value=0) results.df = pd.DataFrame(data={DTTM_ALIAS:", "{\"x\": NULL_STRING, \"y\": 2}, {\"x\": \"anchovies\", \"y\": 1}, ] self.assertEqual(expected_values,", "], \"percent_metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\",", "\"page_length\": 0, \"all_columns\": [], \"viz_type\": \"table\", \"since\": \"2014-01-01\", \"until\": \"2014-01-02\",", "600, 700, 800, 900] df = pd.DataFrame(raw) groups = [\"groupA\",", "15], \"avg__C\": [11, 22, 33, 44], \"count\": [6, 7, 8,", "test_viz.levels_for_diff(time_op, groups, df) expected = {\"metric1\": 6, \"metric2\": 60, \"metric3\":", "datasource = self.get_datasource_mock() test_viz_deckgl = viz.DeckGeoJson(datasource, form_data) results = test_viz_deckgl.query_obj()", "= self.get_datasource_mock() expected_results = { \"latlong_key\": [\"lon\", \"lat\"], \"delimited_key\": [\"lonlat\"],", "{ 946684800000000000: [ {\"time\": t1, \"value\": 1, \"key\": (\"a1\",), \"name\":", "(u\"Real Madrid C.F.\\U0001f1fa\\U0001f1f8\\U0001f1ec\\U0001f1e7\",), }, ] self.assertEqual(expected, viz_data) def test_process_data_resample(self): datasource", "8, \"avg__C\": 33, \"%SUM(value1)\": 0.25, \"%avg__B\": 0.1, }, { \"groupA\":", "[1.0, 2.0, None, 4.0], } ) data = viz.BigNumberViz(datasource, {\"metrics\":", "[ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\", \"column\": {\"column_name\":", "33, 44], \"count\": [6, 7, 8, 9], \"groupA\": [\"A\", \"B\",", "groups, df) self.assertEqual(4, len(levels)) expected = {DTTM_ALIAS: 1800, \"metric1\": 45,", "self.assertEqual(sorted(cols), sorted(levels[2].columns.tolist())) cols += [\"groupC\"] self.assertEqual(sorted(cols), sorted(levels[3].columns.tolist())) self.assertEqual(4, len(test_viz.process_data.mock_calls)) def", "query_obj = {\"granularity\": \"day\"} datasource = self.get_datasource_mock() test_viz = viz.BaseViz(datasource,", "\"point_diff\" test_viz.levels_for_diff = Mock(return_value=1) test_viz.get_data(df) self.assertEqual(\"point_diff\", test_viz.levels_for_diff.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_percent\"", "datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"NULL\")", "4): df_drop = df.drop(groups[i:], 1) pivot = df_drop.pivot_table( index=DTTM_ALIAS, columns=groups[:i],", "len(nest[0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) def test_nest_procs_returns_hierarchy(self): raw = {}", "= [ { \"key\": NULL_STRING, \"values\": [{\"x\": \"pepperoni\", \"y\": 2},", "}, { \"values\": [ {\"x\": 100, \"y\": 7}, {\"x\": 200,", "[{\"col\": \"value2\", \"val\": \"100\", \"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual([], query_obj[\"extras\"][\"having_druid\"])", "\"groupB\", \"groupC\"] levels = test_viz.levels_for(\"agg_sum\", groups, df) nest = test_viz.nest_values(levels)", "datasource = self.get_datasource_mock() form_data = {} test_viz = viz.PartitionViz(datasource, form_data)", "\"spatial_key\" mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(ValueError)", "BigNumberVizTestCase(SupersetTestCase): def test_get_data(self): datasource = self.get_datasource_mock() df = pd.DataFrame( data={", "[1.0, 3.0, 6.0, 10.0], ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\":", "form_data = { \"url_params\": {}, \"row_limit\": 500, \"metric\": \"sum__SP_POP_TOTL\", \"entity\":", "[\"lonlat\"], \"geohash_key\": [\"geo\"], } for mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]:", "500, 600, 700, 800, 900] df = pd.DataFrame(raw) groups =", "form_data = { \"groupby\": [\"groupA\", \"groupB\"], \"metrics\": [ { \"expressionType\":", "expected = [ { u\"values\": [ {u\"y\": 4, u\"x\": u\"2018-02-20T00:00:00\"},", "test_viz.get_fillna_for_columns = Mock(return_value=0) results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01 05:00:00\"]}) datasource.offset =", "\"metrics\": [\"sum__A\", \"count\", \"avg__C\"], \"percent_metrics\": [\"sum__A\", \"avg__B\", \"max__Y\"], } test_viz", "regarding copyright ownership. The ASF licenses this file # to", "\"y\": 800}, {\"x\": 300, \"y\": 900}, ], \"group\": (\"c1\", \"c2\",", "25}, t2.strftime(time_format): {\"a1\": 30, \"a2\": 35, \"a3\": 40}, } self.assertEqual(expected,", "or agreed to in writing, # software distributed under the", "TimeSeriesVizTestCase(SupersetTestCase): def test_timeseries_unicode_data(self): datasource = self.get_datasource_mock() form_data = {\"groupby\": [\"name\"],", "400, 500, 600, 700, 800, 900] df = pd.DataFrame(raw) test_viz", "[ { u\"values\": [ {u\"y\": 4, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 4,", "800}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"],", "\"groupB\": \"y\", \"SUM(value1)\": 25, \"count\": 8, \"avg__C\": 33, \"%SUM(value1)\": 0.25,", "test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual( [\"sum__A\", \"count\",", "} ], } self.assertEqual(data, expected) class PartitionVizTestCase(SupersetTestCase): @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_time_series_option(self,", "in ('North America')\", }, ], } datasource = self.get_datasource_mock() test_viz", "cols = [DTTM_ALIAS, \"metric1\", \"metric2\", \"metric3\"] self.assertEqual(sorted(cols), sorted(levels[0].columns.tolist())) cols +=", "viz.BaseViz(datasource, form_data={}) self.assertEqual(156, test_viz.cache_timeout) datasource.cache_timeout = None datasource.database.cache_timeout = 0", "self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_diff_computes_difference(self): raw", "self.assertEqual([], query_obj[\"groupby\"]) self.assertEqual([[\"colA\", \"colB\"], [\"colC\"]], query_obj[\"orderby\"]) def test_query_obj_uses_sortby(self): datasource =", "metric], query_obj[\"metrics\"]) self.assertEqual([(metric, True)], query_obj[\"orderby\"]) run_test(\"simple_metric\") run_test( { \"label\": \"adhoc_metric\",", "= \"point_factor\" test_viz.get_data(df) self.assertEqual(\"point_factor\", test_viz.levels_for_diff.mock_calls[2][1][0]) test_viz.levels_for_time = Mock(return_value=1) test_viz.nest_procs =", "context: test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) self.assertTrue(\"Bad spatial key\" in str(context.exception)) test_form_data =", "\"name\": (\"b1\",)}, {\"time\": t2, \"value\": 8, \"key\": (\"c1\",), \"name\": (\"c1\",)},", "\"value\": 1, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t1, \"value\": 4,", "test_apply_rolling(self): datasource = self.get_datasource_mock() df = pd.DataFrame( index=pd.to_datetime( [\"2019-01-01\", \"2019-01-02\",", "from math import nan from unittest.mock import Mock, patch import", "], \"NULL\": [ { \"values\": [ {\"x\": 100, \"y\": 10},", "with self.assertRaises(ValueError): test_viz.get_data(df) test_viz.levels_for = Mock(return_value=1) test_viz.nest_values = Mock(return_value=1) test_viz.form_data[\"groupby\"]", "2, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 2, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real", "\"a2\": 20, \"a3\": 25}, t2.strftime(time_format): {\"a1\": 30, \"a2\": 35, \"a3\":", "datasource.database.cache_timeout = 0 self.assertEqual(0, test_viz.cache_timeout) datasource.database.cache_timeout = 1666 self.assertEqual(1666, test_viz.cache_timeout)", "superset.constants import NULL_STRING from superset.exceptions import SpatialException from superset.utils.core import", "{\"metric1\": 6, \"metric2\": 60, \"metric3\": 600} self.assertEqual(expected, levels[0].to_dict()) expected =", "viz.BaseViz(datasource, form_data) expect_metric_labels = [ u\"sum__SP_POP_TOTL\", u\"SUM(SE_PRM_NENR_MA)\", u\"SUM(SP_URB_TOTL)\", u\"count\", ]", "metrics = [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"sum_value\",", "assert results[\"groupby\"] == [] assert results[\"columns\"] == [\"test_col\"] def test_parse_coordinates(self):", "\"clause\": \"WHERE\", \"sqlExpression\": \"value3 in ('North America')\", }, ], \"having\":", "datasource = self.get_datasource_mock() df = pd.DataFrame( { \"toppings\": [\"cheese\", \"pepperoni\",", "\"count\", \"avg__C\", ], \"percent_metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\",", "\"y\": 3}, ] self.assertEqual(expected_values, data[\"values\"]) def test_column_nulls(self): form_data = {", "= Mock() with self.assertRaises(ValueError): test_viz.get_data(df) test_viz.levels_for = Mock(return_value=1) test_viz.nest_values =", "(\"b1\",), \"name\": (\"b1\",)}, {\"time\": t1, \"value\": 7, \"key\": (\"c1\",), \"name\":", "\"delimited_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\":", "\"b3\", \"b3\", \"c3\", \"c3\", \"c3\"] raw[\"metric1\"] = [1, 2, 3,", "300, 100, 200, 300] raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\",", "} df = pd.DataFrame({\"SUM(value1)\": [15], \"sum_value\": [15]}) datasource = self.get_datasource_mock()", "[\"y\"], \"resample_method\": \"sum\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0, 2.0,", "200, 300] raw[\"\"] = [1, 2, 3] raw[None] = [10,", "pd.Timestamp(\"2019-01-05\"), \"y\": 3}) def test_get_data_with_none(self): datasource = self.get_datasource_mock() df =", "\"col\": \"SUM(value1)\"}], query_obj[\"extras\"][\"having_druid\"], ) self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"(SUM(value1)", "} ) def test_should_be_timeseries_raises_when_no_granularity(self): datasource = self.get_datasource_mock() form_data = {\"include_time\":", "{ \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"sum_value\", \"column\": {\"column_name\": \"value1\",", "\"expressionType\": \"SQL\", \"clause\": \"WHERE\", \"sqlExpression\": \"value3 in ('North America')\", },", "import logging from math import nan from unittest.mock import Mock,", "{} test_viz = viz.PartitionViz(datasource, form_data) super_query_obj.return_value = {} query_obj =", "import numpy as np import pandas as pd import tests.test_app", "levels = test_viz.levels_for_diff(time_op, groups, df) expected = {\"metric1\": 6, \"metric2\":", "test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() class BaseDeckGLVizTestCase(SupersetTestCase): def", "in ('North America')\", }, ], \"having\": \"SUM(value1) > 5\", }", "datasource = self.get_datasource_mock() df = pd.DataFrame( { \"__timestamp\": pd.to_datetime( [\"2019-01-01\",", "\"y\", \"z\"], } ) test_viz = viz.TableViz(datasource, form_data) data =", "2}, {\"x\": \"anchovies\", \"y\": 1}, ] self.assertEqual(expected_values, data[\"values\"]) def test_groupby_nans(self):", "\"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS NOT", "cols += [\"groupC\"] self.assertEqual(sorted(cols), sorted(levels[3].columns.tolist())) self.assertEqual(4, len(test_viz.process_data.mock_calls)) def test_nest_values_returns_hierarchy(self): raw", "test_groupby_nulls(self): form_data = { \"metrics\": [\"votes\"], \"adhoc_filters\": [], \"groupby\": [\"toppings\"],", "\"a2\": 35, \"a3\": 40}, } self.assertEqual(expected, data[\"records\"]) @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_throws_metrics_and_groupby(self,", "100, \"y\": 100}, {\"x\": 200, \"y\": 200}, {\"x\": 300, \"y\":", "\"metric2\": {\"a1\": 20, \"b1\": 50, \"c1\": 80}, \"metric3\": {\"a1\": 200,", "\"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"order_desc\": False, }", "\"where\": \"\", \"compare_suffix\": \"o10Y\", } datasource = Mock() datasource.type =", "(\"c1\",), \"name\": (\"c1\",)}, ], 1072915200000000000: [ {\"time\": t3, \"value\": 3,", "], \"group\": (\"b1\", \"b2\", \"b3\"), }, { \"values\": [ {\"x\":", "self.assertTrue(\"Bad spatial key\" in str(context.exception)) test_form_data = { \"latlong_key\": {\"type\":", "= {} raw[DTTM_ALIAS] = [100, 200, 300, 100, 200, 300,", "\"%avg__B\", ], list(data[\"columns\"]), ) expected = [ { \"groupA\": \"A\",", "\"1.0\", \"y\": 42}, {\"x\": \"0.0\", \"y\": 30}, {\"x\": \"2.0\", \"y\":", "= test_viz_deckgl.get_metrics() assert result == [\"int\"] form_data = {} test_viz_deckgl", "in range(0, 3): self.assertEqual(\"metric\" + str(i + 1), nest[i][\"name\"]) self.assertEqual(3,", "200, \"c1\": 200}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual(4, len(levels)) self.assertEqual([\"groupA\", \"groupB\",", "= { \"groupby\": [\"groupA\", \"groupB\", \"groupC\"], \"metrics\": [\"metric1\", \"metric2\", \"metric3\"],", "t1 = pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t1,", "\"order_by_cols\": ['[\"colA\", \"colB\"]', '[\"colC\"]'], } super_query_obj.return_value = { \"columns\": [\"colD\",", "= viz.TableViz(datasource, form_data) data = test_viz.get_data(df) self.assertEqual([\"sum_value\"], data[\"columns\"]) class DistBarVizTestCase(SupersetTestCase):", "KIND, either express or implied. See the License for the", "self.get_datasource_mock() form_data = {\"groupby\": [\"a\"]} super_query_obj.return_value = {} test_viz =", "{}, \"row_limit\": 500, \"metric\": \"sum__SP_POP_TOTL\", \"entity\": \"country_code\", \"secondary_metric\": \"sum__SP_POP_TOTL\", \"granularity_sqla\":", "len(test_viz.process_data.mock_calls)) def test_nest_values_returns_hierarchy(self): raw = {} raw[\"groupA\"] = [\"a1\", \"a1\",", "BaseVizTestCase(SupersetTestCase): def test_constructor_exception_no_datasource(self): form_data = {} datasource = None with", "{ \"toppings\": [\"cheese\", \"pepperoni\", \"anchovies\", None], \"votes\": [3, 5, 1,", "\"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lonlat\", \"isExtra\": False,", "viz_instance.parse_coordinates(\"1.23, 3.21\") self.assertEqual(coord, (1.23, 3.21)) coord = viz_instance.parse_coordinates(\"1.23 3.21\") self.assertEqual(coord,", "raw = {} raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\", \"b1\",", "def test_process_data_resample(self): datasource = self.get_datasource_mock() df = pd.DataFrame( { \"__timestamp\":", "1009843200000000000: [ {\"time\": t2, \"value\": 2, \"key\": (\"a1\",), \"name\": (\"a1\",)},", "result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS) ) mock_dttm_col.python_date_format =", "\"columns\": [\"role\"], } datasource = self.get_datasource_mock() df = pd.DataFrame( {", "1, 2], } ) test_viz = viz.DistributionBarViz(datasource, form_data) data =", "\"y\": 30}, ], \"group\": \"All\", } ], } self.assertEqual(data, expected)", "False, } ], } for mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]:", "(\"c1\", \"c2\", \"c3\"), }, ], \"metric2\": [ { \"values\": [", "\"values\": [{\"x\": \"pepperoni\", \"y\": 5}, {\"x\": \"cheese\", \"y\": 3}], },", "= test_viz.get_df(query_obj) import logging logger.info(result) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1,", "\"expressionType\": \"SIMPLE\", \"clause\": \"WHERE\", \"subject\": \"value2\", \"operator\": \">\", \"comparator\": \"100\",", "} datasource = self.get_datasource_mock() df = pd.DataFrame({\"beds\": [0, 1, nan,", "15, \"count\": 6}, t2.strftime(time_format): {\"sum__A\": 20, \"count\": 7}, } self.assertEqual(expected,", ".utils import load_fixture logger = logging.getLogger(__name__) class BaseVizTestCase(SupersetTestCase): def test_constructor_exception_no_datasource(self):", "{\"column_name\": \"sort_column\",}, } ) def test_should_be_timeseries_raises_when_no_granularity(self): datasource = self.get_datasource_mock() form_data", "{} result = test_viz_deckgl.get_metrics() assert result == [] def test_get_js_columns(self):", "as context: test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) self.assertTrue(\"Bad spatial key\" in str(context.exception)) test_form_data", ") mock_dttm_col.python_date_format = None result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960,", "datasource = self.get_datasource_mock() df = pd.DataFrame( index=pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\",", "\"isExtra\": False, }, ], \"delimited_key\": [ { \"clause\": \"WHERE\", \"expressionType\":", "self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj() del form_data[\"metrics\"] form_data[\"groupby\"] =", "\"NULL\": [ { \"values\": [ {\"x\": 100, \"y\": 10}, {\"x\":", "200, \"y\": 20}, {\"x\": 300, \"y\": 30}, ], \"group\": \"All\",", "22, 33, 44], \"count\": [6, 7, 8, 9], \"groupA\": [\"A\",", "\"value\": 6, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t3, \"value\": 9,", "} datasource = self.get_datasource_mock() expected_results = { \"latlong_key\": [ {", "400}, {\"x\": 200, \"y\": 500}, {\"x\": 300, \"y\": 600}, ],", "assert result == {\"color\": None} def test_get_properties(self): mock_d = {}", "query_obj = test_viz.query_obj() self.assertEqual([\"colA\", \"colB\", metric], query_obj[\"metrics\"]) self.assertEqual([(metric, True)], query_obj[\"orderby\"])", "data[\"values\"]) def test_column_nulls(self): form_data = { \"metrics\": [\"votes\"], \"adhoc_filters\": [],", "= [15, 20] raw[\"count\"] = [6, 7] df = pd.DataFrame(raw)", "= load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() form_data = {} test_viz_deckgl =", "1800, \"metric1\": 45, \"metric2\": 450, \"metric3\": 4500} self.assertEqual(expected, levels[0].to_dict()) expected", "= [1, 2, 3] raw[None] = [10, 20, 30] df", "self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_mean\" test_viz.get_data(df) self.assertEqual(\"agg_mean\", test_viz.levels_for.mock_calls[2][1][0]) test_viz.form_data[\"time_series_option\"] =", "\"a3\": 25}, t2.strftime(time_format): {\"a1\": 30, \"a2\": 35, \"a3\": 40}, }", "results[\"metrics\"] == [] assert results[\"groupby\"] == [] assert results[\"columns\"] ==", "\"isExtra\": False, } ], \"geohash_key\": [ { \"clause\": \"WHERE\", \"expressionType\":", "= { \"all_columns\": [\"colA\", \"colB\", \"colC\"], \"order_by_cols\": ['[\"colA\", \"colB\"]', '[\"colC\"]'],", "list(data[\"columns\"]), ) expected = [ { \"groupA\": \"A\", \"groupB\": \"x\",", "200, 300, 100, 200, 300, 100, 200, 300] raw[\"groupA\"] =", "20}, {\"x\": 300, \"y\": 30}, ], \"group\": (\"a1\", \"a2\", \"a3\"),", "self.assertEqual(3, len(nest)) for i in range(0, 3): self.assertEqual(\"metric\" + str(i", "\"groupby\": [\"groupby1\"]} datasource = self.get_datasource_mock() raw = {} t1 =", "[t1, t1, t1, t2, t2, t2] raw[\"sum__A\"] = [15, 20,", "test_viz_deckgl.get_metrics() assert result == [] def test_get_js_columns(self): form_data = load_fixture(\"deck_path_form_data.json\")", "# Licensed to the Apache Software Foundation (ASF) under one", "Mock, patch import numpy as np import pandas as pd", "test_get_data_empty_null_keys(self): form_data = {\"groupby\": [], \"metrics\": [\"\", None]} datasource =", "and limitations # under the License. # isort:skip_file import uuid", "form_data = { \"metrics\": [\"votes\"], \"adhoc_filters\": [], \"groupby\": [\"toppings\"], \"columns\":", "], } for mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: test_viz_deckgl =", "self.assertEqual(data, expected) class PartitionVizTestCase(SupersetTestCase): @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_time_series_option(self, super_query_obj): datasource =", "test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_js_columns(mock_d) assert result ==", "300, \"y\": 3}, ], \"group\": \"All\", } ], \"NULL\": [", "\"rolling_periods\": 10, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 1.5,", "\"2019-01-07\"] ), \"y\": [1.0, 2.0, None, 4.0], } ) data", "test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {\"type\": \"metric\", \"value\": \"int\"}", "self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj() @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_merges_all_columns(self, super_query_obj):", "\"b1\", \"b1\", \"c1\", \"c1\", \"c1\"] raw[\"groupB\"] = [\"a2\", \"a2\", \"a2\",", "viz.PartitionViz(Mock(), {}) levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected", "9] raw[\"metric2\"] = [10, 20, 30, 40, 50, 60, 70,", "self.assertEqual(data[2], {DTTM_ALIAS: pd.Timestamp(\"2019-01-05\"), \"y\": 3}) def test_get_data_with_none(self): datasource = self.get_datasource_mock()", "(\"b1\",)}, {\"time\": t2, \"value\": 8, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ],", "self.get_datasource_mock() form_data = { \"all_columns\": [\"colA\", \"colB\", \"colC\"], \"order_by_cols\": ['[\"colA\",", "\"groupby\": [\"toppings\"], \"columns\": [\"role\"], } datasource = self.get_datasource_mock() df =", "\"operator\": \"IS NOT NULL\", \"subject\": \"lat\", \"isExtra\": False, }, {", "Mock(return_value=1) test_viz.nest_values = Mock(return_value=1) test_viz.form_data[\"groupby\"] = [\"groups\"] test_viz.form_data[\"time_series_option\"] = \"not_time\"", "\"column\": {\"column_name\": \"sort_column\",}, } ) def test_should_be_timeseries_raises_when_no_granularity(self): datasource = self.get_datasource_mock()", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "\"epoch_ms\" result = test_viz.get_df(query_obj) import logging logger.info(result) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960,", "\"All\", } ], \"NULL\": [ { \"values\": [ {\"x\": 100,", "400, 500, 600, 700, 800, 900] df = pd.DataFrame(raw) pairedTTestViz", "test_viz = viz.PartitionViz(Mock(), {}) levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4,", "self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) def test_nest_procs_returns_hierarchy(self): raw =", "test_viz.form_data[\"groupby\"] = [\"groups\"] test_viz.form_data[\"time_series_option\"] = \"not_time\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"]", "isort:skip_file import uuid from datetime import datetime import logging from", "= viz.BaseDeckGLViz(datasource, test_form_data.copy()) test_viz_deckgl.spatial_control_keys = [mock_key] test_viz_deckgl.add_null_filters() adhoc_filters = test_viz_deckgl.form_data[\"adhoc_filters\"]", "Software Foundation (ASF) under one # or more contributor license", "self.assertEqual(156, test_viz.cache_timeout) datasource.cache_timeout = None datasource.database.cache_timeout = 0 self.assertEqual(0, test_viz.cache_timeout)", "# regarding copyright ownership. The ASF licenses this file #", "{\"granularity\": \"day\"} results = Mock() results.query = Mock() results.status =", "\"c3\"] raw[\"metric1\"] = [1, 2, 3, 4, 5, 6, 7,", "60, \"b1\": 150, \"c1\": 240}, \"metric3\": {\"a1\": 600, \"b1\": 1500,", "time_op = \"agg_mean\" levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels))", "0 self.assertEqual(0, test_viz.cache_timeout) datasource.database.cache_timeout = 1666 self.assertEqual(1666, test_viz.cache_timeout) datasource.database.cache_timeout =", "test_levels_for_diff_computes_difference(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300, 100,", "{ \"metrics\": [\"y\"], \"rolling_type\": \"cumsum\", \"rolling_periods\": 0, \"min_periods\": 0, },", "= {\"granularity\": \"day\"} results = Mock() results.query = Mock() results.status", "\"Real Madrid Basket\", \"Real Madrid Basket\", ] raw[\"__timestamp\"] = [", "= viz.PartitionViz(Mock(), {}) groups = [\"groupA\", \"groupB\", \"groupC\"] metrics =", "expected = [ { \"key\": NULL_STRING, \"values\": [{\"x\": \"pepperoni\", \"y\":", "self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) def test_nest_procs_returns_hierarchy(self): raw = {} raw[DTTM_ALIAS]", "load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(NotImplementedError)", "pd.DataFrame( { \"toppings\": [\"cheese\", \"pepperoni\", \"cheese\", \"pepperoni\"], \"role\": [\"engineer\", \"engineer\",", "method correctly transforms data expected = { \"N/A\": [ {", "\"SUM\", \"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"avg__B\",", "self.assertEqual(test_viz.metric_labels, expect_metric_labels) self.assertEqual(test_viz.all_metrics, expect_metric_labels) def test_get_df_returns_empty_df(self): form_data = {\"dummy\": 123}", "[100, 200, 300, 100, 200, 300, 100, 200, 300] raw[\"groupA\"]", "this file # to you under the Apache License, Version", "[\"1960-01-01\"]}) mock_dttm_col.python_date_format = \"%Y-%m-%d\" result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960,", "Test data raw = {} raw[DTTM_ALIAS] = [100, 200, 300]", "test_viz.form_data[\"time_series_option\"] = \"agg_sum\" query_obj = test_viz.query_obj() self.assertTrue(query_obj[\"is_timeseries\"]) def test_levels_for_computes_levels(self): raw", "\"c2\", \"c2\", \"c2\"] raw[\"groupC\"] = [\"a3\", \"a3\", \"a3\", \"b3\", \"b3\",", "name=DTTM_ALIAS) ) datasource.offset = 1 result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS],", "self.assertEqual( [\"sum__A\", \"count\", \"avg__C\", \"avg__B\", \"max__Y\"], query_obj[\"metrics\"] ) def test_query_obj_throws_columns_and_metrics(self):", "results = test_viz_deckgl.query_obj() assert results[\"metrics\"] == [] assert results[\"groupby\"] ==", "[\"name\"], \"metrics\": [\"sum__payout\"]} raw = {} raw[\"name\"] = [ \"Real", "# Check method correctly transforms data expected = { \"metric1\":", "form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {}", "\"operator\": \">\", \"comparator\": \"100\", }, { \"expressionType\": \"SQL\", \"clause\": \"WHERE\",", "[3, 5, 1, 2], } ) test_viz = viz.DistributionBarViz(datasource, form_data)", "\"y\": [1.0, 2.0, None, 4.0], } ) data = viz.BigNumberViz(datasource,", "self.assertEqual(4, len(levels)) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_time_calls_process_data_and_drops_cols(self): raw =", "] form_data = { \"metrics\": metrics, \"timeseries_limit_metric\": { \"expressionType\": \"SIMPLE\",", "300, \"y\": 30}, ], \"group\": (\"a1\", \"a2\", \"a3\"), }, {", "self.assertEqual(4, len(levels)) expected = {DTTM_ALIAS: 1800, \"metric1\": 45, \"metric2\": 450,", "as viz from superset import app from superset.constants import NULL_STRING", "test_adhoc_metric_with_sortby(self): metrics = [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\":", "\"HAVING\", \"sqlExpression\": \"SUM(value1) > 5\", }, { \"expressionType\": \"SQL\", \"clause\":", "u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid Basket\",), }, { u\"values\":", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "2, \"b1\": 2, \"c1\": 2}, \"metric2\": {\"a1\": 20, \"b1\": 20,", "pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, 5.0,", "[1, 2, 3, 4, 5, 6, 7, 8, 9] raw[\"metric2\"]", "{\"x\": \"cheese\", \"y\": 3}], }, ] self.assertEqual(expected, data) class PairedTTestTestCase(SupersetTestCase):", "= viz.DeckGeoJson(datasource, form_data) results = test_viz_deckgl.query_obj() assert results[\"metrics\"] == []", "= Mock(return_value=1) test_viz.form_data[\"groupby\"] = [\"groups\"] test_viz.form_data[\"time_series_option\"] = \"not_time\" test_viz.get_data(df) self.assertEqual(\"agg_sum\",", "\"label\": \"adhoc_metric\", \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"column\": {\"column_name\": \"sort_column\",}, }", "2.0, np.nan, np.nan, 5.0, np.nan, 7.0], ) def test_apply_rolling(self): datasource", "self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) def test_nest_procs_returns_hierarchy(self): raw = {} raw[DTTM_ALIAS] = [100,", "t2, t3, t1, t2, t3, t1, t2, t3] raw[\"groupA\"] =", "import nan from unittest.mock import Mock, patch import numpy as", "def test_process_metrics(self): # test TableViz metrics in correct order form_data", "in correct order form_data = { \"url_params\": {}, \"row_limit\": 500,", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "\"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 5.0, 7.0],", "pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01 05:00:00\"]}) datasource.offset = 0 mock_dttm_col = Mock() datasource.get_column", "to the Apache Software Foundation (ASF) under one # or", "test_viz.nest_procs(procs) self.assertEqual(3, len(nest)) for i in range(0, 3): self.assertEqual(\"metric\" +", "\"License\"); you may not use this file except in compliance", "datasource.database.cache_timeout = None test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(app.config[\"CACHE_DEFAULT_TIMEOUT\"], test_viz.cache_timeout) class", "5}, {\"x\": \"cheese\", \"y\": 3}, {\"x\": NULL_STRING, \"y\": 2}, {\"x\":", "900] df = pd.DataFrame(raw) groups = [\"groupA\", \"groupB\", \"groupC\"] test_viz", "500, \"metric\": \"sum__SP_POP_TOTL\", \"entity\": \"country_code\", \"secondary_metric\": \"sum__SP_POP_TOTL\", \"granularity_sqla\": \"year\", \"page_length\":", "self.assertEqual(type(result), pd.DataFrame) self.assertTrue(result.empty) def test_get_df_handles_dttm_col(self): form_data = {\"dummy\": 123} query_obj", "= Mock(return_value=1) test_viz.nest_procs = Mock(return_value=1) test_viz.form_data[\"time_series_option\"] = \"adv_anal\" test_viz.get_data(df) self.assertEqual(1,", "\"groupby\": []} datasource = self.get_datasource_mock() raw = {} t1 =", "8, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], 1072915200000000000: [ {\"time\": t3,", "[15, 20, 25, 30, 35, 40] raw[\"groupby1\"] = [\"a1\", \"a2\",", "= load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_d = {\"a\": \"dummy1\", \"b\":", "[], \"viz_type\": \"table\", \"since\": \"2014-01-01\", \"until\": \"2014-01-02\", \"metrics\": [\"sum__SP_POP_TOTL\", \"SUM(SE_PRM_NENR_MA)\",", "\"groupB\", \"groupC\"] time_op = \"agg_sum\" test_viz = viz.PartitionViz(Mock(), {}) levels", "{ \"expressionType\": \"SIMPLE\", \"clause\": \"WHERE\", \"subject\": \"value2\", \"operator\": \">\", \"comparator\":", "mock_gb = [] test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(ValueError) as", "query_obj = {\"granularity\": \"day\"} results = Mock() results.query = Mock()", "300}, ], \"group\": (\"a1\", \"a2\", \"a3\"), }, { \"values\": [", "\"groupB\", \"groupC\"], levels[3].index.names) time_op = \"agg_mean\" levels = test_viz.levels_for(time_op, groups,", "# distributed with this work for additional information # regarding", "Mock(return_value=results) mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col) test_viz = viz.BaseViz(datasource,", "5}, {\"x\": \"cheese\", \"y\": 3}], }, ] self.assertEqual(expected, data) class", ") datasource.offset = 0 results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01\"]}) mock_dttm_col.python_date_format =", "\"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS", "= test_viz.nest_procs(procs) self.assertEqual(3, len(nest)) for i in range(0, 3): self.assertEqual(\"metric\"", "%H:%M:%S\" expected = { t1.strftime(time_format): {\"sum__A\": 15, \"count\": 6}, t2.strftime(time_format):", "test_viz.levels_for = Mock(return_value=1) test_viz.nest_values = Mock(return_value=1) test_viz.form_data[\"groupby\"] = [\"groups\"] test_viz.form_data[\"time_series_option\"]", ") self.assertEqual( [{\"op\": \"<\", \"val\": \"10\", \"col\": \"SUM(value1)\"}], query_obj[\"extras\"][\"having_druid\"], )", "NULL_STRING, \"y\": 2}, {\"x\": \"anchovies\", \"y\": 1}, ] self.assertEqual(expected_values, data[\"values\"])", "test_viz.get_data(df)[0] self.assertEqual(\"count\", data[\"key\"]) expected_values = [ {\"x\": \"1.0\", \"y\": 42},", "None) def test_parse_coordinates_raises(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl", "= viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual( [{\"col\": \"value2\", \"val\":", "Madrid Basket\", ] raw[\"__timestamp\"] = [ \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\",", "9}, ], \"group\": (\"c1\", \"c2\", \"c3\"), }, ], \"metric2\": [", "\"%avg__B\": 0.3, }, ] self.assertEqual(expected, data[\"records\"]) def test_parse_adhoc_filters(self): form_data =", "permissions and limitations # under the License. # isort:skip_file import", "# Check method correctly transforms data and computes percents self.assertEqual(", "query_obj[\"orderby\"]) def test_query_obj_uses_sortby(self): datasource = self.get_datasource_mock() form_data = { \"metrics\":", "del form_data[\"metrics\"] form_data[\"groupby\"] = [\"B\", \"C\"] with self.assertRaises(Exception): test_viz =", "self.get_datasource_mock() viz_instance = viz.BaseDeckGLViz(datasource, form_data) coord = viz_instance.parse_coordinates(\"1.23, 3.21\") self.assertEqual(coord,", "\"agg_mean\" test_viz.get_data(df) self.assertEqual(\"agg_mean\", test_viz.levels_for.mock_calls[2][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_diff\" test_viz.levels_for_diff = Mock(return_value=1)", "for additional information # regarding copyright ownership. The ASF licenses", "results.status = Mock() results.error_message = Mock() datasource = Mock() datasource.type", "viz_data) def test_process_data_resample(self): datasource = self.get_datasource_mock() df = pd.DataFrame( {", "3}, {\"x\": NULL_STRING, \"y\": 2}, {\"x\": \"anchovies\", \"y\": 1}, ]", "{ \"metrics\": [\"count\"], \"adhoc_filters\": [], \"groupby\": [\"beds\"], \"columns\": [], }", "df = pd.DataFrame(raw) groups = [\"groupA\", \"groupB\", \"groupC\"] test_viz =", "NOT NULL\", \"subject\": \"geo\", \"isExtra\": False, } ], } for", "datasource = Mock() datasource.type = \"table\" test_viz = viz.BaseViz(datasource, form_data)", "\"DOUBLE\"}, }, \"count\", \"avg__C\", ], \"percent_metrics\": [ { \"expressionType\": \"SIMPLE\",", "\"metric\": \"sum__SP_POP_TOTL\", \"entity\": \"country_code\", \"secondary_metric\": \"sum__SP_POP_TOTL\", \"granularity_sqla\": \"year\", \"page_length\": 0,", "with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"fldkjsalkj,fdlaskjfjadlksj\") @patch(\"superset.utils.core.uuid.uuid4\") def test_filter_nulls(self, mock_uuid4): mock_uuid4.return_value = uuid.UUID(\"12345678123456781234567812345678\")", "[\"a3\", \"a3\", \"a3\", \"b3\", \"b3\", \"b3\", \"c3\", \"c3\", \"c3\"] raw[\"metric1\"]", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "3.21)) self.assertEqual(viz_instance.parse_coordinates(None), None) self.assertEqual(viz_instance.parse_coordinates(\"\"), None) def test_parse_coordinates_raises(self): form_data = load_fixture(\"deck_path_form_data.json\")", "), \"y\": [1.0, 2.0, 5.0, 7.0], } ) self.assertEqual( viz.NVD3TimeSeriesViz(", "= viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"count\", data[\"key\"]) expected_values =", ") test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"votes\", data[\"key\"])", "} test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual(form_data[\"all_columns\"], query_obj[\"columns\"])", "\"value2\", \"val\": \"100\", \"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual( [{\"op\": \"<\",", "np import pandas as pd import tests.test_app import superset.viz as", "run_test(\"simple_metric\") run_test( { \"label\": \"adhoc_metric\", \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"column\":", "nest[i][\"name\"]) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) def test_nest_procs_returns_hierarchy(self): raw", "}, \"avg__B\", ], } datasource = self.get_datasource_mock() df = pd.DataFrame(", "[\"colC\"]], query_obj[\"orderby\"]) def test_query_obj_uses_sortby(self): datasource = self.get_datasource_mock() form_data = {", "[\"y\"]}).get_data(df) self.assertEqual(data[2], {DTTM_ALIAS: pd.Timestamp(\"2019-01-05\"), \"y\": 3}) def test_get_data_with_none(self): datasource =", "\"C\"], \"groupB\": [\"x\", \"x\", \"y\", \"z\"], } ) test_viz =", "form_data) data = test_viz.get_data(df) self.assertEqual([\"sum_value\"], data[\"columns\"]) class DistBarVizTestCase(SupersetTestCase): def test_groupby_nulls(self):", "{ \"groupA\": \"C\", \"groupB\": \"z\", \"SUM(value1)\": 40, \"count\": 9, \"avg__C\":", "] self.assertEqual(expected_values, data[\"values\"]) def test_groupby_nans(self): form_data = { \"metrics\": [\"count\"],", "}, ], } datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data)", "2, 3, 4, 5, 6, 7, 8, 9] raw[\"metric2\"] =", "test_viz = viz.PartitionViz(datasource, form_data) super_query_obj.return_value = {} query_obj = test_viz.query_obj()", "\"metrics\": [\"sum__payout\"]} raw = {} raw[\"name\"] = [ \"Real Madrid", "test_form_data = { \"latlong_key\": {\"type\": \"latlong\", \"lonCol\": \"lon\", \"latCol\": \"lat\"},", "\"metrics\": [\"votes\"], \"adhoc_filters\": [], \"groupby\": [\"toppings\"], \"columns\": [], } datasource", "raw = {} t1 = pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") raw[DTTM_ALIAS]", "\"SUM\", \"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"count\",", "self.assertEqual(viz_instance.parse_coordinates(None), None) self.assertEqual(viz_instance.parse_coordinates(\"\"), None) def test_parse_coordinates_raises(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource", "= {\"include_time\": True} with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.should_be_timeseries()", "200, \"b1\": 200}, \"metric1\": {\"a1\": 2, \"b1\": 5, \"c1\": 8},", "form_data = {\"groupby\": [\"a\"]} super_query_obj.return_value = {} test_viz = viz.TimeTableViz(datasource,", ") def test_should_be_timeseries_raises_when_no_granularity(self): datasource = self.get_datasource_mock() form_data = {\"include_time\": True}", "[\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), data={\"y\": [1.0, 2.0, 3.0, 4.0]},", "} ] form_data = { \"metrics\": metrics, \"timeseries_limit_metric\": { \"expressionType\":", ") self.assertEqual( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\": \"sum\", \"resample_rule\": \"1D\"},", "+ str(i + 1), nest[i][\"name\"]) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1,", "= pd.DataFrame( index=pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), data={\"y\": [1.0,", "= test_viz.query_obj() self.assertEqual( [{\"col\": \"value2\", \"val\": \"100\", \"op\": \">\"}], query_obj[\"filter\"]", "\"%SUM(value1)\", \"%avg__B\", ], list(data[\"columns\"]), ) expected = [ { \"groupA\":", "{\"x\": \"cheese\", \"y\": 1}], }, { \"key\": \"engineer\", \"values\": [{\"x\":", "form_data) data = test_viz.get_data(df) expected = [ { \"key\": NULL_STRING,", "20, \"c1\": 20}, \"metric3\": {\"a1\": 200, \"b1\": 200, \"c1\": 200},", "\"percent_metrics\": [\"sum__A\", \"avg__B\", \"max__Y\"], } test_viz = viz.TableViz(datasource, form_data) query_obj", "\"<\", \"val\": \"10\", \"col\": \"SUM(value1)\"}], query_obj[\"extras\"][\"having_druid\"], ) self.assertEqual(\"(value3 in ('North", "import Mock, patch import numpy as np import pandas as", "30, 40, 50, 60, 70, 80, 90] raw[\"metric3\"] = [100,", "}, ] self.assertEqual(expected, data) class PairedTTestTestCase(SupersetTestCase): def test_get_data_transforms_dataframe(self): form_data =", "= self.get_datasource_mock() form_data = {\"groupby\": [\"name\"], \"metrics\": [\"sum__payout\"]} raw =", "= viz.TableViz(datasource, form_data) test_viz.query_obj() @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_merges_all_columns(self, super_query_obj): datasource =", "groups = [\"groupA\", \"groupB\", \"groupC\"] levels = test_viz.levels_for(\"agg_sum\", groups, df)", "TableVizTestCase(SupersetTestCase): def test_get_data_applies_percentage(self): form_data = { \"groupby\": [\"groupA\", \"groupB\"], \"metrics\":", "\"IS NOT NULL\", \"subject\": \"lon\", \"isExtra\": False, }, ], \"delimited_key\":", "\"SUM\", \"column\": {\"column_name\": \"sort_column\",}, } ) def test_should_be_timeseries_raises_when_no_granularity(self): datasource =", "}, ], \"having\": \"SUM(value1) > 5\", } datasource = self.get_datasource_mock()", "test_viz_deckgl = viz.DeckGeoJson(datasource, form_data) results = test_viz_deckgl.query_obj() assert results[\"metrics\"] ==", "9], \"groupA\": [\"A\", \"B\", \"C\", \"C\"], \"groupB\": [\"x\", \"x\", \"y\",", "import datetime import logging from math import nan from unittest.mock", "], \"group\": (\"c1\", \"c2\", \"c3\"), }, ], \"metric2\": [ {", "the License for the # specific language governing permissions and", "test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() form_data[\"metrics\"] = [\"x\",", "@patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_throws_metrics_and_groupby(self, super_query_obj): datasource = self.get_datasource_mock() form_data = {\"groupby\":", "America')\", }, ], \"having\": \"SUM(value1) > 5\", } datasource =", "> 5\", } datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data)", "ANY # KIND, either express or implied. See the License", "\"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t3, \"value\": 9, \"key\": (\"c1\",),", "raw[\"groupby1\"] = [\"a1\", \"a2\", \"a3\", \"a1\", \"a2\", \"a3\"] df =", "self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"mean\", \"rolling_periods\": 10,", "\"aggregate\": \"SUM\", \"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, },", "2], \"count\": [30, 42, 3, 29]}) test_viz = viz.DistributionBarViz(datasource, form_data)", "test_viz.get_data(df) self.assertEqual(1, len(test_viz.levels_for_time.mock_calls)) self.assertEqual(1, len(test_viz.nest_procs.mock_calls)) test_viz.form_data[\"time_series_option\"] = \"time_series\" test_viz.get_data(df) self.assertEqual(\"agg_sum\",", "= [DTTM_ALIAS, \"metric1\", \"metric2\", \"metric3\"] self.assertEqual(sorted(cols), sorted(levels[0].columns.tolist())) cols += [\"groupA\"]", "{ \"latlong_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\",", "200, \"y\": 500}, {\"x\": 300, \"y\": 600}, ], \"group\": (\"b1\",", "5}, {\"x\": 300, \"y\": 6}, ], \"group\": (\"b1\", \"b2\", \"b3\"),", "20}, {\"x\": 300, \"y\": 30}, ], \"group\": \"All\", } ],", "expected = { \"metric1\": {\"a1\": 2, \"b1\": 2, \"c1\": 2},", "test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df)[0] self.assertEqual(\"count\", data[\"key\"]) expected_values", "\"agg_sum\" test_viz = viz.PartitionViz(Mock(), {}) levels = test_viz.levels_for(time_op, groups, df)", "\"groupC\"], levels[3].index.names) def test_levels_for_diff_computes_difference(self): raw = {} raw[DTTM_ALIAS] = [100,", "\"toppings\": [\"cheese\", \"pepperoni\", \"cheese\", \"pepperoni\"], \"role\": [\"engineer\", \"engineer\", None, None],", "{ \"metrics\": [\"colA\", \"colB\"], \"order_desc\": False, } def run_test(metric): form_data[\"timeseries_limit_metric\"]", "] raw[\"sum__payout\"] = [2, 2, 4, 4] df = pd.DataFrame(raw)", "result = test_viz.get_df(query_obj) self.assertEqual(type(result), pd.DataFrame) self.assertTrue(result.empty) def test_get_df_handles_dttm_col(self): form_data =", "len(nest[0][\"children\"][0][\"children\"][0][\"children\"][0][\"children\"]) ) def test_get_data_calls_correct_method(self): test_viz = viz.PartitionViz(Mock(), {}) df =", "len(test_viz.nest_values.mock_calls)) class RoseVisTestCase(SupersetTestCase): def test_rose_vis_get_data(self): raw = {} t1 =", "[\"colA\", \"colB\"], } test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj()", "400, 500, 600, 700, 800, 900] df = pd.DataFrame(raw) groups", "\"a3\", \"b3\", \"b3\", \"b3\", \"c3\", \"c3\", \"c3\"] raw[\"metric1\"] = [1,", "\"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"sum_value\", \"column\": {\"column_name\": \"value1\", \"type\":", "], \"group\": (\"c1\", \"c2\", \"c3\"), }, ], } self.assertEqual(data, expected)", "res = test_viz.get_data(df) expected = { 946684800000000000: [ {\"time\": t1,", "== [\"int\"] form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed", "method correctly transforms data and computes percents self.assertEqual( [ \"groupA\",", "0.3, }, ] self.assertEqual(expected, data[\"records\"]) def test_parse_adhoc_filters(self): form_data = {", "test_get_data(self): datasource = self.get_datasource_mock() df = pd.DataFrame( data={ DTTM_ALIAS: pd.to_datetime(", "self.assertEqual([\"sum_value\"], data[\"columns\"]) class DistBarVizTestCase(SupersetTestCase): def test_groupby_nulls(self): form_data = { \"metrics\":", "\"groupB\", \"groupC\"] test_viz = viz.PartitionViz(Mock(), {}) time_op = \"point_diff\" levels", "[\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, 3.0, 4.0],", "datasource.offset = 0 results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01\"]}) mock_dttm_col.python_date_format = \"%Y-%m-%d\"", "test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(156, test_viz.cache_timeout) datasource.cache_timeout = None datasource.database.cache_timeout", "), \"y\": [1.0, 2.0, 3.0, 4.0], } ) data =", "{} t1 = pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") t3 = pd.Timestamp(\"2004\")", "= test_viz.query_obj() self.assertEqual(form_data[\"all_columns\"], query_obj[\"columns\"]) self.assertEqual([], query_obj[\"groupby\"]) self.assertEqual([[\"colA\", \"colB\"], [\"colC\"]], query_obj[\"orderby\"])", "time_format = \"%Y-%m-%d %H:%M:%S\" expected = { t1.strftime(time_format): {\"sum__A\": 15,", ".process_data(df)[\"y\"] .tolist(), [1.0, 2.0, np.nan, np.nan, 5.0, np.nan, 7.0], )", "pandas as pd import tests.test_app import superset.viz as viz from", "[ {u\"y\": 4, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 4, u\"x\": u\"2018-03-09T00:00:00\"}, ],", "{\"time\": t3, \"value\": 6, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t3,", "time_op = \"agg_sum\" test_viz = viz.PartitionViz(Mock(), {}) levels = test_viz.levels_for(time_op,", "agreed to in writing, # software distributed under the License", "\"agg_sum\" query_obj = test_viz.query_obj() self.assertTrue(query_obj[\"is_timeseries\"]) def test_levels_for_computes_levels(self): raw = {}", ") .process_data(df)[\"y\"] .tolist(), [1.0, 2.0, np.nan, np.nan, 5.0, np.nan, 7.0],", "NULL_STRING, \"values\": [{\"x\": \"pepperoni\", \"y\": 2}, {\"x\": \"cheese\", \"y\": 1}],", "7.0], ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"mean\",", "= None result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1,", "\"type\": \"DOUBLE\"}, }, \"order_desc\": False, } df = pd.DataFrame({\"SUM(value1)\": [15],", "2}, \"metric2\": {\"a1\": 20, \"b1\": 20, \"c1\": 20}, \"metric3\": {\"a1\":", "self.assertTrue(query_obj[\"is_timeseries\"]) def test_levels_for_computes_levels(self): raw = {} raw[DTTM_ALIAS] = [100, 200,", "0 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(0, test_viz.cache_timeout) datasource.cache_timeout = 156", "\"SUM(SP_URB_TOTL)\"], \"country_fieldtype\": \"cca3\", \"percent_metrics\": [\"count\"], \"slice_id\": 74, \"time_grain_sqla\": None, \"order_by_cols\":", "= Mock() datasource.get_column = Mock(return_value=mock_dttm_col) mock_dttm_col.python_date_format = \"epoch_ms\" result =", "assert result == [\"int\"] form_data = {} test_viz_deckgl = viz.DeckScatterViz(datasource,", "== [] assert results[\"groupby\"] == [] assert results[\"columns\"] == [\"test_col\"]", "Mock(return_value=0) results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01 05:00:00\"]}) datasource.offset = 0 mock_dttm_col", "\"values\": [ {\"x\": 100, \"y\": 400}, {\"x\": 200, \"y\": 500},", "viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\": \"sum\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"]", "in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"\", query_obj[\"extras\"][\"having\"]) def test_query_obj_merges_percent_metrics(self): datasource =", "data self.assertEqual(set([\"a1\", \"a2\", \"a3\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\" expected", "= viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {} result = test_viz_deckgl.get_metrics() assert", "= viz.BaseViz(datasource, form_data) expect_metric_labels = [ u\"sum__SP_POP_TOTL\", u\"SUM(SE_PRM_NENR_MA)\", u\"SUM(SP_URB_TOTL)\", u\"count\",", "[\"groupA\", \"groupB\", \"groupC\"] test_viz = viz.PartitionViz(Mock(), {\"groupby\": groups}) def return_args(df_drop,", "NOT NULL\", \"subject\": \"lat\", \"isExtra\": False, }, { \"clause\": \"WHERE\",", "300] raw[\"\"] = [1, 2, 3] raw[None] = [10, 20,", "{\"x\": 200, \"y\": 8}, {\"x\": 300, \"y\": 9}, ], \"group\":", ") def test_apply_rolling(self): datasource = self.get_datasource_mock() df = pd.DataFrame( index=pd.to_datetime(", "self.assertEqual(expected, data) class PairedTTestTestCase(SupersetTestCase): def test_get_data_transforms_dataframe(self): form_data = { \"groupby\":", "[{\"x\": \"pepperoni\", \"y\": 5}, {\"x\": \"cheese\", \"y\": 3}], }, ]", "form_data = { \"metrics\": [\"sum__A\", \"count\", \"avg__C\"], \"percent_metrics\": [\"sum__A\", \"avg__B\",", "ASF licenses this file # to you under the Apache", "results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01 05:00:00\"]}) datasource.offset = 0 mock_dttm_col =", "super_query_obj): datasource = self.get_datasource_mock() form_data = {} test_viz = viz.PartitionViz(datasource,", "len(test_viz.nest_procs.mock_calls)) test_viz.form_data[\"time_series_option\"] = \"time_series\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[3][1][0]) self.assertEqual(7, len(test_viz.nest_values.mock_calls)) class", "2, 4, 4] df = pd.DataFrame(raw) test_viz = viz.NVD3TimeSeriesViz(datasource, form_data)", "raw[\"\"] = [1, 2, 3] raw[None] = [10, 20, 30]", "[\"sum__A\", \"count\"], \"groupby\": []} datasource = self.get_datasource_mock() raw = {}", "= 156 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(156, test_viz.cache_timeout) datasource.cache_timeout =", "\"y\": 10}, {\"x\": 200, \"y\": 20}, {\"x\": 300, \"y\": 30},", "2, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid C.F.\\U0001f1fa\\U0001f1f8\\U0001f1ec\\U0001f1e7\",), }, ]", "= [t1, t2, t3, t1, t2, t3, t1, t2, t3]", "\"isExtra\": False, } ], } for mock_key in [\"latlong_key\", \"delimited_key\",", "[ {\"x\": 100, \"y\": 7}, {\"x\": 200, \"y\": 8}, {\"x\":", "\"SQL\", \"clause\": \"HAVING\", \"sqlExpression\": \"SUM(value1) > 5\", }, { \"expressionType\":", "ownership. The ASF licenses this file # to you under", "{\"metrics\": [\"y\"], \"resample_method\": \"sum\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0,", "('North America')\", }, ], \"having\": \"SUM(value1) > 5\", } datasource", "} self.assertEqual(expected, data[\"records\"]) def test_get_data_group_by(self): form_data = {\"metrics\": [\"sum__A\"], \"groupby\":", "\"count\": 8, \"avg__C\": 33, \"%SUM(value1)\": 0.25, \"%avg__B\": 0.1, }, {", "levels[3].index.names) def test_levels_for_time_calls_process_data_and_drops_cols(self): raw = {} raw[DTTM_ALIAS] = [100, 200,", "America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"\", query_obj[\"extras\"][\"having\"]) def test_query_obj_merges_percent_metrics(self): datasource = self.get_datasource_mock() form_data", "\"groupC\"], levels[3].index.names) def test_levels_for_time_calls_process_data_and_drops_cols(self): raw = {} raw[DTTM_ALIAS] = [100,", "self.assertEqual(expected, data[\"records\"]) def test_get_data_group_by(self): form_data = {\"metrics\": [\"sum__A\"], \"groupby\": [\"groupby1\"]}", "\"lonlat\", \"isExtra\": False, } ], \"geohash_key\": [ { \"clause\": \"WHERE\",", "\"b1\", \"b1\", \"b1\", \"c1\", \"c1\", \"c1\"] raw[\"groupB\"] = [\"a2\", \"a2\",", "\"groupby\": [\"toppings\"], \"columns\": [], } datasource = self.get_datasource_mock() df =", "metrics = [\"metric1\", \"metric2\", \"metric3\"] procs = {} for i", ") self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"sum\", \"rolling_periods\":", "\"max__Y\"], } test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual(", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "= metric test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual([\"colA\",", "pd.Timestamp(\"2002\") t3 = pd.Timestamp(\"2004\") raw[DTTM_ALIAS] = [t1, t2, t3, t1,", "None]} datasource = self.get_datasource_mock() # Test data raw = {}", "= viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {\"type\": \"metric\", \"value\": \"int\"} result", "70, 80, 90] raw[\"metric3\"] = [100, 200, 300, 400, 500,", "200, \"c1\": 200, \"b1\": 200}, \"metric1\": {\"a1\": 2, \"b1\": 5,", "self.get_datasource_mock() df = pd.DataFrame( index=pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ),", "\"isExtra\": False, }, { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\",", "\"2__table\", \"table_timestamp_format\": \"%Y-%m-%d %H:%M:%S\", \"markup_type\": \"markdown\", \"where\": \"\", \"compare_suffix\": \"o10Y\",", "def test_query_obj_uses_sortby(self): datasource = self.get_datasource_mock() form_data = { \"metrics\": [\"colA\",", "len(nest)) for i in range(0, 3): self.assertEqual(\"metric\" + str(i +", "\"IS NOT NULL\", \"subject\": \"lat\", \"isExtra\": False, }, { \"clause\":", "t3, \"value\": 3, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t3, \"value\":", "pd.DataFrame( index=pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), data={\"y\": [1.0, 2.0,", "self.get_datasource_mock() test_viz_deckgl = viz.DeckGeoJson(datasource, form_data) results = test_viz_deckgl.query_obj() assert results[\"metrics\"]", "500.0, } self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS: {\"a1\": 200,", "}, { \"expressionType\": \"SIMPLE\", \"clause\": \"HAVING\", \"subject\": \"SUM(value1)\", \"operator\": \"<\",", "\"subject\": \"value2\", \"operator\": \">\", \"comparator\": \"100\", }, { \"expressionType\": \"SIMPLE\",", "viz_instance.parse_coordinates(\"1.23 3.21\") self.assertEqual(coord, (1.23, 3.21)) self.assertEqual(viz_instance.parse_coordinates(None), None) self.assertEqual(viz_instance.parse_coordinates(\"\"), None) def", "= pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") t3 = pd.Timestamp(\"2004\") raw[DTTM_ALIAS] =", "[1.0, 3.0, 5.0, 7.0], ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\":", "self.assertEqual(1, len(test_viz.nest_procs.mock_calls)) test_viz.form_data[\"time_series_option\"] = \"time_series\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[3][1][0]) self.assertEqual(7, len(test_viz.nest_values.mock_calls))", "\"100\", \"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual( [{\"op\": \"<\", \"val\": \"10\",", "self.assertEqual(\"(SUM(value1) > 5)\", query_obj[\"extras\"][\"having\"]) def test_adhoc_filters_overwrite_legacy_filters(self): form_data = { \"metrics\":", "[\"count\"], \"slice_id\": 74, \"time_grain_sqla\": None, \"order_by_cols\": [], \"groupby\": [\"country_name\"], \"compare_lag\":", "= viz.BaseViz(datasource, form_data) result = test_viz.get_df(query_obj) self.assertEqual(type(result), pd.DataFrame) self.assertTrue(result.empty) def", "with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"NULL\") with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"fldkjsalkj,fdlaskjfjadlksj\") @patch(\"superset.utils.core.uuid.uuid4\") def test_filter_nulls(self, mock_uuid4):", "test_viz.cache_timeout) class TableVizTestCase(SupersetTestCase): def test_get_data_applies_percentage(self): form_data = { \"groupby\": [\"groupA\",", "language governing permissions and limitations # under the License. #", "\"count\", \"avg__C\", \"%SUM(value1)\", \"%avg__B\", ], list(data[\"columns\"]), ) expected = [", "\"groupby\": [\"colA\", \"colB\"], } test_viz = viz.TableViz(datasource, form_data) query_obj =", "} self.assertEqual(data, expected) def test_get_data_empty_null_keys(self): form_data = {\"groupby\": [], \"metrics\":", ") .apply_rolling(df)[\"y\"] .tolist(), [1.0, 1.5, 2.0, 2.5], ) class BigNumberVizTestCase(SupersetTestCase):", "software distributed under the License is distributed on an #", "Mock() datasource.type = \"table\" test_viz = viz.BaseViz(datasource, form_data) expect_metric_labels =", "test_viz = viz.BaseViz(datasource, form_data) test_viz.df_metrics_to_num = Mock() test_viz.get_fillna_for_columns = Mock(return_value=0)", "test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)], name=DTTM_ALIAS) )", "super_query_obj.return_value = {} test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj()", "u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid C.F.\\U0001f1fa\\U0001f1f8\\U0001f1ec\\U0001f1e7\",), }, ] self.assertEqual(expected,", "self.get_datasource_mock() df = pd.DataFrame( data={ DTTM_ALIAS: pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\",", "\"day\"} datasource = self.get_datasource_mock() test_viz = viz.BaseViz(datasource, form_data) result =", "\"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lon\", \"isExtra\":", "0.15, \"%avg__B\": 0.2, }, { \"groupA\": \"B\", \"groupB\": \"x\", \"SUM(value1)\":", "logging from math import nan from unittest.mock import Mock, patch", "1, nan, 2], \"count\": [30, 42, 3, 29]}) test_viz =", "\"y\", \"SUM(value1)\": 25, \"count\": 8, \"avg__C\": 33, \"%SUM(value1)\": 0.25, \"%avg__B\":", "False, } df = pd.DataFrame({\"SUM(value1)\": [15], \"sum_value\": [15]}) datasource =", "groups, df) expected = {\"metric1\": 6, \"metric2\": 60, \"metric3\": 600}", "information # regarding copyright ownership. The ASF licenses this file", "6, 7, 8, 9] df = pd.DataFrame(raw) fd = {\"metrics\":", "self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_time_calls_process_data_and_drops_cols(self): raw = {} raw[DTTM_ALIAS]", "t2 = pd.Timestamp(\"2002\") t3 = pd.Timestamp(\"2004\") raw[DTTM_ALIAS] = [t1, t2,", "\"values\": [ {\"x\": 100, \"y\": 70}, {\"x\": 200, \"y\": 80},", "America')\", }, ], } datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource,", "= test_viz.query_obj() self.assertTrue(query_obj[\"is_timeseries\"]) def test_levels_for_computes_levels(self): raw = {} raw[DTTM_ALIAS] =", "10}, {\"x\": 200, \"y\": 20}, {\"x\": 300, \"y\": 30}, ],", "form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data)", "self.get_datasource_mock() df = pd.DataFrame({\"beds\": [0, 1, nan, 2], \"count\": [30,", "{\"sum__A\": 20, \"count\": 7}, } self.assertEqual(expected, data[\"records\"]) def test_get_data_group_by(self): form_data", ") .process_data(df)[\"y\"] .tolist(), [1.0, 2.0, 0.0, 0.0, 5.0, 0.0, 7.0],", "= viz.BaseViz(datasource, form_data={}) self.assertEqual(app.config[\"CACHE_DEFAULT_TIMEOUT\"], test_viz.cache_timeout) class TableVizTestCase(SupersetTestCase): def test_get_data_applies_percentage(self): form_data", "] self.assertEqual(expected_values, data[\"values\"]) def test_column_nulls(self): form_data = { \"metrics\": [\"votes\"],", "1) pivot = df_drop.pivot_table( index=DTTM_ALIAS, columns=groups[:i], values=metrics ) procs[i] =", "test TableViz metrics in correct order form_data = { \"url_params\":", "\"y\": 600}, ], \"group\": (\"b1\", \"b2\", \"b3\"), }, { \"values\":", "\"SUM\", \"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"order_desc\":", "\"c1\": 20}, \"metric3\": {\"a1\": 200, \"b1\": 200, \"c1\": 200}, }", "{\"all_columns\": [\"A\", \"B\"], \"metrics\": [\"x\", \"y\"]} with self.assertRaises(Exception): test_viz =", "\"day\"} results = Mock() results.query = Mock() results.status = Mock()", "licenses this file # to you under the Apache License,", "\"point_percent\" test_viz.get_data(df) self.assertEqual(\"point_percent\", test_viz.levels_for_diff.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_factor\" test_viz.get_data(df) self.assertEqual(\"point_factor\", test_viz.levels_for_diff.mock_calls[2][1][0])", "\"2.0\", \"y\": 29}, {\"x\": NULL_STRING, \"y\": 3}, ] self.assertEqual(expected_values, data[\"values\"])", "by applicable law or agreed to in writing, # software", "unittest.mock import Mock, patch import numpy as np import pandas", "2}, {\"x\": 300, \"y\": 3}, ], \"group\": (\"a1\", \"a2\", \"a3\"),", "8}, {\"x\": 300, \"y\": 9}, ], \"group\": (\"c1\", \"c2\", \"c3\"),", "} self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS: {\"a1\": 200, \"c1\":", "in str(context.exception)) def test_process_spatial_query_obj(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock()", "} ], \"adhoc_filters\": [ { \"expressionType\": \"SIMPLE\", \"clause\": \"WHERE\", \"subject\":", "assert results[\"metrics\"] == [] assert results[\"groupby\"] == [] assert results[\"columns\"]", "limitations # under the License. # isort:skip_file import uuid from", "= self.get_datasource_mock() form_data = {\"all_columns\": [\"A\", \"B\"], \"metrics\": [\"x\", \"y\"]}", "\"IS NOT NULL\", \"subject\": \"geo\", \"isExtra\": False, } ], }", "test_viz.query_obj() self.assertEqual( [{\"col\": \"value2\", \"val\": \"100\", \"op\": \">\"}], query_obj[\"filter\"] )", "\"sum__A\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\" expected = { t1.strftime(time_format):", "\"c2\", \"c3\"), }, ], \"metric2\": [ { \"values\": [ {\"x\":", "500}, {\"x\": 300, \"y\": 600}, ], \"group\": (\"b1\", \"b2\", \"b3\"),", ".apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 5.0, 7.0], ) self.assertEqual( viz.BigNumberViz( datasource,", "\"metric3\": {\"a1\": 200, \"b1\": 500, \"c1\": 800}, } self.assertEqual(expected, levels[1].to_dict())", "\"name\": (\"c1\",)}, ], 1009843200000000000: [ {\"time\": t2, \"value\": 2, \"key\":", "levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected = {DTTM_ALIAS:", "[1.0, 1.5, 2.0, 2.5], ) class BigNumberVizTestCase(SupersetTestCase): def test_get_data(self): datasource", "expect_metric_labels) def test_get_df_returns_empty_df(self): form_data = {\"dummy\": 123} query_obj = {\"granularity\":", "\"timeseries_limit_metric\": { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\", \"column\": {\"column_name\":", "self.assertEqual( [{\"op\": \"<\", \"val\": \"10\", \"col\": \"SUM(value1)\"}], query_obj[\"extras\"][\"having_druid\"], ) self.assertEqual(\"(value3", "\"a2\", \"a3\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\" expected = {", "compliance # with the License. You may obtain a copy", "\"all_columns\": [\"colA\", \"colB\", \"colC\"], \"order_by_cols\": ['[\"colA\", \"colB\"]', '[\"colC\"]'], } super_query_obj.return_value", "\"value\": 5, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t2, \"value\": 8,", "form_data = { \"metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\",", "\"metric2\": 60, \"metric3\": 600} self.assertEqual(expected, levels[0].to_dict()) expected = { \"metric1\":", "= viz.TableViz(datasource, form_data) data = test_viz.get_data(df) # Check method correctly", "pairedTTestViz.get_data(df) # Check method correctly transforms data expected = {", "def test_rose_vis_get_data(self): raw = {} t1 = pd.Timestamp(\"2000\") t2 =", "datasource = self.get_datasource_mock() raw = {} t1 = pd.Timestamp(\"2000\") t2", "= self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"NULL\") with", "} datasource = self.get_datasource_mock() df = pd.DataFrame( { \"SUM(value1)\": [15,", "300, \"y\": 90}, ], \"group\": (\"c1\", \"c2\", \"c3\"), }, ],", "= { \"N/A\": [ { \"values\": [ {\"x\": 100, \"y\":", "sorted(levels[3].columns.tolist())) self.assertEqual(4, len(test_viz.process_data.mock_calls)) def test_nest_values_returns_hierarchy(self): raw = {} raw[\"groupA\"] =", "def test_get_df_returns_empty_df(self): form_data = {\"dummy\": 123} query_obj = {\"granularity\": \"day\"}", "0.0, 7.0], ) np.testing.assert_equal( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\": \"asfreq\",", "levels[0].to_dict()) expected = { DTTM_ALIAS: {\"a1\": 200, \"c1\": 200, \"b1\":", "self.assertEqual(\"metric\" + str(i + 1), nest[i][\"name\"]) self.assertEqual(None, nest[i].get(\"val\")) self.assertEqual(3, len(nest[0][\"children\"]))", "test_viz.levels_for_diff.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_factor\" test_viz.get_data(df) self.assertEqual(\"point_factor\", test_viz.levels_for_diff.mock_calls[2][1][0]) test_viz.levels_for_time = Mock(return_value=1)", "[] def test_scatterviz_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() form_data", "\"c1\", \"c1\", \"c1\"] raw[\"groupB\"] = [\"a2\", \"a2\", \"a2\", \"b2\", \"b2\",", "None datasource.database.cache_timeout = 0 self.assertEqual(0, test_viz.cache_timeout) datasource.database.cache_timeout = 1666 self.assertEqual(1666,", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "test_viz.get_data(df) self.assertEqual([\"sum_value\"], data[\"columns\"]) class DistBarVizTestCase(SupersetTestCase): def test_groupby_nulls(self): form_data = {", "= \"epoch_ms\" result = test_viz.get_df(query_obj) import logging logger.info(result) pd.testing.assert_series_equal( result[DTTM_ALIAS],", "\"value\": 2, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t2, \"value\": 5,", "22, \"%SUM(value1)\": 0.2, \"%avg__B\": 0.4, }, { \"groupA\": \"C\", \"groupB\":", "\"aggregate\": \"SUM\", \"column\": {\"column_name\": \"sort_column\",}, } ) def test_should_be_timeseries_raises_when_no_granularity(self): datasource", "test_viz = viz.PartitionViz(Mock(), {}) df = Mock() with self.assertRaises(ValueError): test_viz.get_data(df)", "test_viz.levels_for_time = Mock(return_value=1) test_viz.nest_procs = Mock(return_value=1) test_viz.form_data[\"time_series_option\"] = \"adv_anal\" test_viz.get_data(df)", "self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[3][1][0]) self.assertEqual(7, len(test_viz.nest_values.mock_calls)) class RoseVisTestCase(SupersetTestCase): def test_rose_vis_get_data(self): raw =", "\"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"count\", \"avg__C\",", "4, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 4, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real", "], u\"key\": (u\"Real Madrid Basket\",), }, { u\"values\": [ {u\"y\":", "{\"a1\": 600, \"b1\": 600, \"c1\": 600}, \"metric1\": {\"a1\": 6, \"b1\":", "as pd import tests.test_app import superset.viz as viz from superset", "7, 8, 9] raw[\"metric2\"] = [10, 20, 30, 40, 50,", "test_viz = viz.PartitionViz(Mock(), {}) time_op = \"point_diff\" levels = test_viz.levels_for_diff(time_op,", "test_viz.get_data(df) self.assertEqual(\"point_factor\", test_viz.levels_for_diff.mock_calls[2][1][0]) test_viz.levels_for_time = Mock(return_value=1) test_viz.nest_procs = Mock(return_value=1) test_viz.form_data[\"time_series_option\"]", "[\"beds\"], \"columns\": [], } datasource = self.get_datasource_mock() df = pd.DataFrame({\"beds\":", "\"avg__C\": 22, \"%SUM(value1)\": 0.2, \"%avg__B\": 0.4, }, { \"groupA\": \"C\",", "\"count\": 6}, t2.strftime(time_format): {\"sum__A\": 20, \"count\": 7}, } self.assertEqual(expected, data[\"records\"])", "\"avg__C\"], \"percent_metrics\": [\"sum__A\", \"avg__B\", \"max__Y\"], } test_viz = viz.TableViz(datasource, form_data)", "Check method correctly transforms data self.assertEqual(set([\"count\", \"sum__A\"]), set(data[\"columns\"])) time_format =", "{ \"toppings\": [\"cheese\", \"pepperoni\", \"cheese\", \"pepperoni\"], \"role\": [\"engineer\", \"engineer\", None,", "\"groupB\", \"groupC\"], \"metrics\": [\"metric1\", \"metric2\", \"metric3\"], } datasource = self.get_datasource_mock()", "results[\"groupby\"] == [] assert results[\"columns\"] == [\"test_col\"] def test_parse_coordinates(self): form_data", "test_nest_values_returns_hierarchy(self): raw = {} raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\",", "[\"1960-01-01 05:00:00\"]}) datasource.offset = 0 mock_dttm_col = Mock() datasource.get_column =", "raw[\"count\"] = [6, 7] df = pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource,", "\"avg__C\": [11, 22, 33, 44], \"count\": [6, 7, 8, 9],", "form_data[\"metrics\"] form_data[\"groupby\"] = [\"B\", \"C\"] with self.assertRaises(Exception): test_viz = viz.TableViz(datasource,", "nest[i].get(\"val\")) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(3, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) self.assertEqual( 1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"][0][\"children\"])", "{ \"key\": NULL_STRING, \"values\": [{\"x\": \"pepperoni\", \"y\": 2}, {\"x\": \"cheese\",", "\"x\", \"SUM(value1)\": 20, \"count\": 7, \"avg__C\": 22, \"%SUM(value1)\": 0.2, \"%avg__B\":", "len(levels)) cols = [DTTM_ALIAS, \"metric1\", \"metric2\", \"metric3\"] self.assertEqual(sorted(cols), sorted(levels[0].columns.tolist())) cols", "\"a2\", \"a3\", \"a1\", \"a2\", \"a3\"] df = pd.DataFrame(raw) test_viz =", "test_groupby_nans(self): form_data = { \"metrics\": [\"count\"], \"adhoc_filters\": [], \"groupby\": [\"beds\"],", "result = test_viz_deckgl.get_js_columns(mock_d) assert result == {\"color\": None} def test_get_properties(self):", "300, \"y\": 60}, ], \"group\": (\"b1\", \"b2\", \"b3\"), }, {", "pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, 3.0,", "self.assertRaises(ValueError): test_viz.get_data(df) test_viz.levels_for = Mock(return_value=1) test_viz.nest_values = Mock(return_value=1) test_viz.form_data[\"groupby\"] =", "to in writing, # software distributed under the License is", "{\"groupby\": [\"a\"]} super_query_obj.return_value = {} test_viz = viz.TimeTableViz(datasource, form_data) with", "= pairedTTestViz.get_data(df) # Check method correctly transforms data expected =", "pd.DataFrame( { \"toppings\": [\"cheese\", \"pepperoni\", \"anchovies\", None], \"votes\": [3, 5,", "t2] raw[\"sum__A\"] = [15, 20] raw[\"count\"] = [6, 7] df", "{\"time\": t1, \"value\": 7, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], 1009843200000000000:", "= self.get_datasource_mock() expected_results = { \"latlong_key\": [ { \"clause\": \"WHERE\",", "} datasource = self.get_datasource_mock() # Test data raw = {}", "20, \"count\": 7}, } self.assertEqual(expected, data[\"records\"]) def test_get_data_group_by(self): form_data =", "\"y\": 2}, {\"x\": 300, \"y\": 3}, ], \"group\": \"All\", }", "super_query_obj): datasource = self.get_datasource_mock() form_data = {\"groupby\": [\"a\"]} super_query_obj.return_value =", "{ \"values\": [ {\"x\": 100, \"y\": 10}, {\"x\": 200, \"y\":", "form_data) test_viz.query_obj() @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_merges_all_columns(self, super_query_obj): datasource = self.get_datasource_mock() form_data", "test_viz.nest_procs = Mock(return_value=1) test_viz.form_data[\"time_series_option\"] = \"adv_anal\" test_viz.get_data(df) self.assertEqual(1, len(test_viz.levels_for_time.mock_calls)) self.assertEqual(1,", "in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"(SUM(value1) > 5)\", query_obj[\"extras\"][\"having\"]) def test_adhoc_filters_overwrite_legacy_filters(self):", "= [t1, t1, t1, t2, t2, t2] raw[\"sum__A\"] = [15,", "= test_viz.levels_for(\"agg_sum\", groups, df) nest = test_viz.nest_values(levels) self.assertEqual(3, len(nest)) for", "], \"delimited_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\",", "nan from unittest.mock import Mock, patch import numpy as np", "500, 600, 700, 800, 900] df = pd.DataFrame(raw) pairedTTestViz =", "set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\" expected = { t1.strftime(time_format): {\"sum__A\":", "form_data) with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"NULL\") with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"fldkjsalkj,fdlaskjfjadlksj\") @patch(\"superset.utils.core.uuid.uuid4\") def test_filter_nulls(self,", "self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def", "0)], name=DTTM_ALIAS) ) datasource.offset = 1 result = test_viz.get_df(query_obj) pd.testing.assert_series_equal(", "res) class TimeSeriesTableVizTestCase(SupersetTestCase): def test_get_data_metrics(self): form_data = {\"metrics\": [\"sum__A\", \"count\"],", ") data = viz.BigNumberViz(datasource, {\"metrics\": [\"y\"]}).get_data(df) self.assertEqual(data[2], {DTTM_ALIAS: pd.Timestamp(\"2019-01-05\"), \"y\":", ") expected = [ { \"groupA\": \"A\", \"groupB\": \"x\", \"SUM(value1)\":", "\"lat\", \"isExtra\": False, }, { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\":", "\"colB\"]', '[\"colC\"]'], } super_query_obj.return_value = { \"columns\": [\"colD\", \"colC\"], \"groupby\":", "Test data raw = {} raw[DTTM_ALIAS] = [100, 200, 300,", "with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.should_be_timeseries() def test_adhoc_metric_with_sortby(self): metrics", "[], } datasource = self.get_datasource_mock() df = pd.DataFrame({\"beds\": [0, 1,", "= { \"latlong_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\":", "> 5\", }, { \"expressionType\": \"SQL\", \"clause\": \"WHERE\", \"sqlExpression\": \"value3", "expected_results.get(mock_key) == mock_gb def test_geojson_query_obj(self): form_data = load_fixture(\"deck_geojson_form_data.json\") datasource =", "{\"x\": 200, \"y\": 200}, {\"x\": 300, \"y\": 300}, ], \"group\":", "\"avg__C\": 11, \"%SUM(value1)\": 0.15, \"%avg__B\": 0.2, }, { \"groupA\": \"B\",", "implied. See the License for the # specific language governing", "{ \"groupA\": \"C\", \"groupB\": \"y\", \"SUM(value1)\": 25, \"count\": 8, \"avg__C\":", "6}, ], \"group\": (\"b1\", \"b2\", \"b3\"), }, { \"values\": [", "\"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"geo\", \"isExtra\": False,", "result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 6, 0)],", "{\"x\": 300, \"y\": 6}, ], \"group\": (\"b1\", \"b2\", \"b3\"), },", "self.assertEqual(sorted(cols), sorted(levels[0].columns.tolist())) cols += [\"groupA\"] self.assertEqual(sorted(cols), sorted(levels[1].columns.tolist())) cols += [\"groupB\"]", "{ \"values\": [ {\"x\": 100, \"y\": 100}, {\"x\": 200, \"y\":", "\"b1\": 600, \"c1\": 600}, \"metric1\": {\"a1\": 6, \"b1\": 15, \"c1\":", "= {} result = test_viz_deckgl.get_metrics() assert result == [] def", "\"compare_suffix\": \"o10Y\", } datasource = Mock() datasource.type = \"table\" test_viz", "[100, 200, 300] raw[\"\"] = [1, 2, 3] raw[None] =", "(\"a1\",), \"name\": (\"a1\",)}, {\"time\": t1, \"value\": 4, \"key\": (\"b1\",), \"name\":", "\"operator\": \">\", \"comparator\": \"100\", }, { \"expressionType\": \"SIMPLE\", \"clause\": \"HAVING\",", "}, ], \"metric3\": [ { \"values\": [ {\"x\": 100, \"y\":", "[10, 20, 5, 15], \"avg__C\": [11, 22, 33, 44], \"count\":", "\"count\", \"avg__C\"], \"percent_metrics\": [\"sum__A\", \"avg__B\", \"max__Y\"], } test_viz = viz.TableViz(datasource,", "\"lon\", \"isExtra\": False, }, ], \"delimited_key\": [ { \"clause\": \"WHERE\",", "NOT NULL\", \"subject\": \"lon\", \"isExtra\": False, }, ], \"delimited_key\": [", "t1 = pd.Timestamp(\"2000\") t2 = pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t2]", "[\"geo\"], } for mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: mock_gb =", "\"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) time_op = \"agg_mean\" levels", "60, \"metric3\": 600} self.assertEqual(expected, levels[0].to_dict()) expected = { \"metric1\": {\"a1\":", "\"y\": 20}, {\"x\": 300, \"y\": 30}, ], \"group\": (\"a1\", \"a2\",", "\"a1\", \"b1\", \"b1\", \"b1\", \"c1\", \"c1\", \"c1\"] raw[\"groupB\"] = [\"a2\",", "\"time_series\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[3][1][0]) self.assertEqual(7, len(test_viz.nest_values.mock_calls)) class RoseVisTestCase(SupersetTestCase): def test_rose_vis_get_data(self):", "query_obj[\"extras\"][\"having_druid\"]) self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"\", query_obj[\"extras\"][\"having\"]) def test_query_obj_merges_percent_metrics(self):", "either express or implied. See the License for the #", "pd.DataFrame(raw) pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource, form_data) data = pairedTTestViz.get_data(df) # Check", "= pd.DataFrame( data={ DTTM_ALIAS: pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ),", "6, \"avg__C\": 11, \"%SUM(value1)\": 0.15, \"%avg__B\": 0.2, }, { \"groupA\":", "= pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t2] raw[\"sum__A\"] = [15, 20]", ") .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 6.0, 10.0], ) self.assertEqual( viz.BigNumberViz(", "\"cheese\", \"y\": 3}, {\"x\": NULL_STRING, \"y\": 2}, {\"x\": \"anchovies\", \"y\":", "test_viz.query_obj() self.assertEqual(form_data[\"all_columns\"], query_obj[\"columns\"]) self.assertEqual([], query_obj[\"groupby\"]) self.assertEqual([[\"colA\", \"colB\"], [\"colC\"]], query_obj[\"orderby\"]) def", "+= [\"groupA\"] self.assertEqual(sorted(cols), sorted(levels[1].columns.tolist())) cols += [\"groupB\"] self.assertEqual(sorted(cols), sorted(levels[2].columns.tolist())) cols", "4] df = pd.DataFrame(raw) test_viz = viz.NVD3TimeSeriesViz(datasource, form_data) viz_data =", "test_column_nulls(self): form_data = { \"metrics\": [\"votes\"], \"adhoc_filters\": [], \"groupby\": [\"toppings\"],", "\"group\": (\"b1\", \"b2\", \"b3\"), }, { \"values\": [ {\"x\": 100,", "levels = test_viz.levels_for_time(groups, df) self.assertEqual(4, len(levels)) cols = [DTTM_ALIAS, \"metric1\",", "def test_apply_rolling(self): datasource = self.get_datasource_mock() df = pd.DataFrame( index=pd.to_datetime( [\"2019-01-01\",", "{ DTTM_ALIAS: {\"a1\": 600, \"b1\": 600, \"c1\": 600}, \"metric1\": {\"a1\":", "3.21\") self.assertEqual(coord, (1.23, 3.21)) coord = viz_instance.parse_coordinates(\"1.23 3.21\") self.assertEqual(coord, (1.23,", "result == [form_data.get(\"size\")] form_data = {} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data)", "\"count\"], \"groupby\": []} datasource = self.get_datasource_mock() raw = {} t1", "= viz_instance.parse_coordinates(\"1.23 3.21\") self.assertEqual(coord, (1.23, 3.21)) self.assertEqual(viz_instance.parse_coordinates(None), None) self.assertEqual(viz_instance.parse_coordinates(\"\"), None)", "viz.TableViz(datasource, form_data) test_viz.query_obj() @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_merges_all_columns(self, super_query_obj): datasource = self.get_datasource_mock()", "= \"point_diff\" levels = test_viz.levels_for_diff(time_op, groups, df) expected = {\"metric1\":", "\"group\": (\"c1\", \"c2\", \"c3\"), }, ], \"metric2\": [ { \"values\":", "self.assertEqual(expected, data[\"records\"]) @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_throws_metrics_and_groupby(self, super_query_obj): datasource = self.get_datasource_mock() form_data", "mock_dttm_col.python_date_format = None result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1,", "test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics() assert result ==", "u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 4, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid", "def test_levels_for_time_calls_process_data_and_drops_cols(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300,", "{ \"metrics\": [\"votes\"], \"adhoc_filters\": [], \"groupby\": [\"toppings\"], \"columns\": [], }", "set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\" expected = { t1.strftime(time_format): {\"a1\":", "{\"type\": \"geohash\", \"geohashCol\": \"geo\"}, } datasource = self.get_datasource_mock() expected_results =", "\"operator\": \"IS NOT NULL\", \"subject\": \"lonlat\", \"isExtra\": False, } ],", "test_viz.should_be_timeseries() def test_adhoc_metric_with_sortby(self): metrics = [ { \"expressionType\": \"SIMPLE\", \"aggregate\":", "metrics in correct order form_data = { \"url_params\": {}, \"row_limit\":", "\"colC\"], \"groupby\": [\"colA\", \"colB\"], } test_viz = viz.TableViz(datasource, form_data) query_obj", "\"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 1.5, 2.0, 2.5],", "\"groupA\": \"C\", \"groupB\": \"y\", \"SUM(value1)\": 25, \"count\": 8, \"avg__C\": 33,", "form_data = {\"groupby\": [], \"metrics\": [\"\", None]} datasource = self.get_datasource_mock()", "['[\"colA\", \"colB\"]', '[\"colC\"]'], } super_query_obj.return_value = { \"columns\": [\"colD\", \"colC\"],", "file except in compliance # with the License. You may", "\"adhoc_metric\", \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"column\": {\"column_name\": \"sort_column\",}, } )", "test_form_data.copy()) test_viz_deckgl.spatial_control_keys = [mock_key] test_viz_deckgl.add_null_filters() adhoc_filters = test_viz_deckgl.form_data[\"adhoc_filters\"] assert expected_results.get(mock_key)", "= test_viz.get_data(df) expected = [ { \"key\": NULL_STRING, \"values\": [{\"x\":", "{ \"metric1\": {\"a1\": 2, \"b1\": 2, \"c1\": 2}, \"metric2\": {\"a1\":", "\"rolling_type\": \"cumsum\", \"rolling_periods\": 0, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(),", "2.0, 3.0, 4.0], } ) data = viz.BigNumberViz(datasource, {\"metrics\": [\"y\"]}).get_data(df)", "\"a3\", \"a1\", \"a2\", \"a3\"] df = pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource,", "form_data = {\"metrics\": [\"sum__A\", \"count\"], \"groupby\": []} datasource = self.get_datasource_mock()", "1 result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 6,", "levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) time_op = \"agg_mean\" levels =", "15, \"c1\": 24}, \"metric2\": {\"a1\": 60, \"b1\": 150, \"c1\": 240},", "df = pd.DataFrame( { \"toppings\": [\"cheese\", \"pepperoni\", \"anchovies\", None], \"votes\":", "\"y\": 3}, {\"x\": NULL_STRING, \"y\": 2}, {\"x\": \"anchovies\", \"y\": 1},", "2, \"b1\": 5, \"c1\": 8}, \"metric2\": {\"a1\": 20, \"b1\": 50,", "\"b1\": 50, \"c1\": 80}, \"metric3\": {\"a1\": 200, \"b1\": 500, \"c1\":", "from superset.exceptions import SpatialException from superset.utils.core import DTTM_ALIAS from .base_tests", "= pd.DataFrame( { \"__timestamp\": pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ),", "\"table\", \"since\": \"2014-01-01\", \"until\": \"2014-01-02\", \"metrics\": [\"sum__SP_POP_TOTL\", \"SUM(SE_PRM_NENR_MA)\", \"SUM(SP_URB_TOTL)\"], \"country_fieldtype\":", "\"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, None, 4.0], } )", "viz.BaseDeckGLViz(datasource, test_form_data) test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) assert expected_results.get(mock_key) == mock_gb def test_geojson_query_obj(self):", "\"groupA\": [\"A\", \"B\", \"C\", \"C\"], \"groupB\": [\"x\", \"x\", \"y\", \"z\"],", "C.F.🇺🇸🇬🇧\", \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid Basket\", \"Real Madrid Basket\",", "test_get_df_returns_empty_df(self): form_data = {\"dummy\": 123} query_obj = {\"granularity\": \"day\"} datasource", "{\"x\": 200, \"y\": 80}, {\"x\": 300, \"y\": 90}, ], \"group\":", "[ {\"x\": 100, \"y\": 100}, {\"x\": 200, \"y\": 200}, {\"x\":", "self.assertEqual(\"point_diff\", test_viz.levels_for_diff.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_percent\" test_viz.get_data(df) self.assertEqual(\"point_percent\", test_viz.levels_for_diff.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] =", "80}, \"metric3\": {\"a1\": 200, \"b1\": 500, \"c1\": 800}, } self.assertEqual(expected,", "contributor license agreements. See the NOTICE file # distributed with", "{\"include_time\": True} with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.should_be_timeseries() def", "self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"NULL\") with self.assertRaises(SpatialException):", "\"viz_type\": \"table\", \"since\": \"2014-01-01\", \"until\": \"2014-01-02\", \"metrics\": [\"sum__SP_POP_TOTL\", \"SUM(SE_PRM_NENR_MA)\", \"SUM(SP_URB_TOTL)\"],", "30}, ], \"group\": (\"a1\", \"a2\", \"a3\"), }, { \"values\": [", "}, { \"values\": [ {\"x\": 100, \"y\": 700}, {\"x\": 200,", "[], \"groupby\": [\"beds\"], \"columns\": [], } datasource = self.get_datasource_mock() df", "mock_uuid4.return_value = uuid.UUID(\"12345678123456781234567812345678\") test_form_data = { \"latlong_key\": {\"type\": \"latlong\", \"lonCol\":", "\"z\"], } ) test_viz = viz.TableViz(datasource, form_data) data = test_viz.get_data(df)", "data[\"key\"]) expected_values = [ {\"x\": \"1.0\", \"y\": 42}, {\"x\": \"0.0\",", "{\"x\": 100, \"y\": 4}, {\"x\": 200, \"y\": 5}, {\"x\": 300,", "levels[3].index.names) time_op = \"agg_mean\" levels = test_viz.levels_for(time_op, groups, df) self.assertEqual(4,", "\"100\", }, { \"expressionType\": \"SQL\", \"clause\": \"WHERE\", \"sqlExpression\": \"value3 in", "test_process_spatial_query_obj(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_key = \"spatial_key\"", "\"group\": \"All\", } ], } self.assertEqual(data, expected) class PartitionVizTestCase(SupersetTestCase): @patch(\"superset.viz.BaseViz.query_obj\")", "test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_mean\" test_viz.get_data(df) self.assertEqual(\"agg_mean\", test_viz.levels_for.mock_calls[2][1][0]) test_viz.form_data[\"time_series_option\"]", "i in range(0, 4): df_drop = df.drop(groups[i:], 1) pivot =", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "4, 4] df = pd.DataFrame(raw) test_viz = viz.NVD3TimeSeriesViz(datasource, form_data) viz_data", "datasource.cache_timeout = 156 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(156, test_viz.cache_timeout) datasource.cache_timeout", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "(\"c1\", \"c2\", \"c3\"), }, ], } self.assertEqual(data, expected) def test_get_data_empty_null_keys(self):", "\"a3\"] df = pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource, form_data) data =", "form_data = {\"dummy\": 123} query_obj = {\"granularity\": \"day\"} datasource =", "test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[3][1][0]) self.assertEqual(7, len(test_viz.nest_values.mock_calls)) class RoseVisTestCase(SupersetTestCase): def test_rose_vis_get_data(self): raw", "\"100\", }, { \"expressionType\": \"SIMPLE\", \"clause\": \"HAVING\", \"subject\": \"SUM(value1)\", \"operator\":", "in str(context.exception)) test_form_data = { \"latlong_key\": {\"type\": \"latlong\", \"lonCol\": \"lon\",", "def test_get_data(self): datasource = self.get_datasource_mock() df = pd.DataFrame( data={ DTTM_ALIAS:", "raw[\"sum__A\"] = [15, 20, 25, 30, 35, 40] raw[\"groupby1\"] =", "\"groupB\", \"groupC\"] metrics = [\"metric1\", \"metric2\", \"metric3\"] procs = {}", "form_data) coord = viz_instance.parse_coordinates(\"1.23, 3.21\") self.assertEqual(coord, (1.23, 3.21)) coord =", ") test_viz = viz.TableViz(datasource, form_data) data = test_viz.get_data(df) # Check", "distributed under the License is distributed on an # \"AS", "\"z\", \"SUM(value1)\": 40, \"count\": 9, \"avg__C\": 44, \"%SUM(value1)\": 0.4, \"%avg__B\":", "df = pd.DataFrame(raw) pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource, form_data) data = pairedTTestViz.get_data(df)", "9] df = pd.DataFrame(raw) fd = {\"metrics\": [\"metric1\"], \"groupby\": [\"groupA\"]}", "6, \"metric2\": 60, \"metric3\": 600} self.assertEqual(expected, levels[0].to_dict()) expected = {", "= { \"metrics\": [\"sum__A\", \"count\", \"avg__C\"], \"percent_metrics\": [\"sum__A\", \"avg__B\", \"max__Y\"],", "1, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t1, \"value\": 4, \"key\":", "expect_metric_labels) self.assertEqual(test_viz.all_metrics, expect_metric_labels) def test_get_df_returns_empty_df(self): form_data = {\"dummy\": 123} query_obj", "1, 5, 0)], name=DTTM_ALIAS) ) mock_dttm_col.python_date_format = None result =", "\"y\": [1.0, 2.0, 5.0, 7.0], } ) self.assertEqual( viz.NVD3TimeSeriesViz( datasource,", "{\"x\": 300, \"y\": 90}, ], \"group\": (\"c1\", \"c2\", \"c3\"), },", "under the Apache License, Version 2.0 (the # \"License\"); you", "Mock() datasource.get_column = Mock(return_value=mock_dttm_col) test_viz = viz.BaseViz(datasource, form_data) test_viz.df_metrics_to_num =", "2, 3] raw[None] = [10, 20, 30] df = pd.DataFrame(raw)", "[1.0, 2.0, 5.0, 7.0], } ) self.assertEqual( viz.NVD3TimeSeriesViz( datasource, {\"metrics\":", "raw[\"__timestamp\"] = [ \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", ] raw[\"sum__payout\"] =", "datasource = self.get_datasource_mock() df = pd.DataFrame({\"beds\": [0, 1, nan, 2],", "test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 0, 0)], name=DTTM_ALIAS) )", "= \"%Y-%m-%d %H:%M:%S\" expected = { t1.strftime(time_format): {\"a1\": 15, \"a2\":", "{\"x\": 100, \"y\": 7}, {\"x\": 200, \"y\": 8}, {\"x\": 300,", "{\"x\": 100, \"y\": 400}, {\"x\": 200, \"y\": 500}, {\"x\": 300,", "], \"having\": \"SUM(value1) > 5\", } datasource = self.get_datasource_mock() test_viz", "0 results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01\"]}) mock_dttm_col.python_date_format = \"%Y-%m-%d\" result =", "[ { \"key\": NULL_STRING, \"values\": [{\"x\": \"pepperoni\", \"y\": 2}, {\"x\":", "form_data) result = test_viz_deckgl.get_js_columns(mock_d) assert result == {\"color\": None} def", "45, \"metric2\": 450, \"metric3\": 4500} self.assertEqual(expected, levels[0].to_dict()) expected = {", "self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) time_op", "10.0], ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"sum\",", "= test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 0, 0)], name=DTTM_ALIAS)", "\"a2\", \"b2\", \"b2\", \"b2\", \"c2\", \"c2\", \"c2\"] raw[\"groupC\"] = [\"a3\",", "{ u\"values\": [ {u\"y\": 2, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 2, u\"x\":", "self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"\", query_obj[\"extras\"][\"having\"]) def test_query_obj_merges_percent_metrics(self): datasource", "test_viz.query_obj() @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_merges_all_columns(self, super_query_obj): datasource = self.get_datasource_mock() form_data =", "\"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, } ], \"adhoc_filters\":", "\"y\": 50}, {\"x\": 300, \"y\": 60}, ], \"group\": (\"b1\", \"b2\",", "2}, {\"x\": 300, \"y\": 3}, ], \"group\": \"All\", } ],", "= test_viz_deckgl.get_metrics() assert result == [] def test_get_js_columns(self): form_data =", "= [ { u\"values\": [ {u\"y\": 4, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\":", "def test_get_data_metrics(self): form_data = {\"metrics\": [\"sum__A\", \"count\"], \"groupby\": []} datasource", "as context: test_viz_deckgl.get_properties(mock_d) self.assertTrue(\"\" in str(context.exception)) def test_process_spatial_query_obj(self): form_data =", "datasource = self.get_datasource_mock() test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj()", "or more contributor license agreements. See the NOTICE file #", "expected = { DTTM_ALIAS: {\"a1\": 600, \"b1\": 600, \"c1\": 600},", "test_viz.get_data(df) # Check method correctly transforms data self.assertEqual(set([\"count\", \"sum__A\"]), set(data[\"columns\"]))", "logger = logging.getLogger(__name__) class BaseVizTestCase(SupersetTestCase): def test_constructor_exception_no_datasource(self): form_data = {}", "\"y\": 4}, {\"x\": 200, \"y\": 5}, {\"x\": 300, \"y\": 6},", "= test_viz.query_obj() self.assertEqual([\"colA\", \"colB\", metric], query_obj[\"metrics\"]) self.assertEqual([(metric, True)], query_obj[\"orderby\"]) run_test(\"simple_metric\")", "\"clause\": \"WHERE\", \"subject\": \"value2\", \"operator\": \">\", \"comparator\": \"100\", }, {", "\"2018-03-09T00:00:00\", \"2018-02-20T00:00:00\", \"2018-03-09T00:00:00\", ] raw[\"sum__payout\"] = [2, 2, 4, 4]", "\"B\", \"groupB\": \"x\", \"SUM(value1)\": 20, \"count\": 7, \"avg__C\": 22, \"%SUM(value1)\":", "Mock() results.error_message = Mock() datasource = Mock() datasource.type = \"table\"", "data self.assertEqual(set([\"count\", \"sum__A\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\" expected =", "\"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"},", "\"y\": 80}, {\"x\": 300, \"y\": 90}, ], \"group\": (\"c1\", \"c2\",", "datasource = self.get_datasource_mock() expected_results = { \"latlong_key\": [\"lon\", \"lat\"], \"delimited_key\":", "test_viz.levels_for_diff = Mock(return_value=1) test_viz.get_data(df) self.assertEqual(\"point_diff\", test_viz.levels_for_diff.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_percent\" test_viz.get_data(df)", "\"name\": (\"b1\",)}, {\"time\": t1, \"value\": 7, \"key\": (\"c1\",), \"name\": (\"c1\",)},", "[ {u\"y\": 2, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 2, u\"x\": u\"2018-03-09T00:00:00\"}, ],", "raw[DTTM_ALIAS] = [t1, t2, t3, t1, t2, t3, t1, t2,", "\"y\": 3}, ], \"group\": (\"a1\", \"a2\", \"a3\"), }, { \"values\":", "adhoc_filters class TimeSeriesVizTestCase(SupersetTestCase): def test_timeseries_unicode_data(self): datasource = self.get_datasource_mock() form_data =", "900] df = pd.DataFrame(raw) groups = [\"groupA\", \"groupB\", \"groupC\"] time_op", "self.assertEqual(set([\"count\", \"sum__A\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\" expected = {", "df = pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource, form_data) data = test_viz.get_data(df)", "u\"count\", ] self.assertEqual(test_viz.metric_labels, expect_metric_labels) self.assertEqual(test_viz.all_metrics, expect_metric_labels) def test_get_df_returns_empty_df(self): form_data =", "def test_get_df_handles_dttm_col(self): form_data = {\"dummy\": 123} query_obj = {\"granularity\": \"day\"}", "correct order form_data = { \"url_params\": {}, \"row_limit\": 500, \"metric\":", "[] def test_get_js_columns(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_d", "pd.DataFrame( { \"SUM(value1)\": [15, 20, 25, 40], \"avg__B\": [10, 20,", "self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) self.assertEqual( 1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"][0][\"children\"]) ) def test_get_data_calls_correct_method(self): test_viz =", "30] df = pd.DataFrame(raw) pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource, form_data) data =", "= viz.PartitionViz(datasource, form_data) super_query_obj.return_value = {} query_obj = test_viz.query_obj() self.assertFalse(query_obj[\"is_timeseries\"])", "result = test_viz_deckgl.get_metrics() assert result == [form_data.get(\"size\")] form_data = {}", "transforms data and computes percents self.assertEqual( [ \"groupA\", \"groupB\", \"SUM(value1)\",", "range(0, 3): self.assertEqual(\"metric\" + str(i + 1), nest[i][\"name\"]) self.assertEqual(None, nest[i].get(\"val\"))", "\"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lonlat\", \"isExtra\":", "[\"latlong_key\", \"delimited_key\", \"geohash_key\"]: test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data.copy()) test_viz_deckgl.spatial_control_keys = [mock_key]", "self.assertEqual(4, len(test_viz.process_data.mock_calls)) def test_nest_values_returns_hierarchy(self): raw = {} raw[\"groupA\"] = [\"a1\",", "in range(0, 3): self.assertEqual(\"metric\" + str(i + 1), nest[i][\"name\"]) self.assertEqual(None,", "}, \"order_desc\": False, } df = pd.DataFrame({\"SUM(value1)\": [15], \"sum_value\": [15]})", "30, \"a2\": 35, \"a3\": 40}, } self.assertEqual(expected, data[\"records\"]) @patch(\"superset.viz.BaseViz.query_obj\") def", "def test_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl =", "\"delimited_key\": {\"type\": \"delimited\", \"lonlatCol\": \"lonlat\"}, \"geohash_key\": {\"type\": \"geohash\", \"geohashCol\": \"geo\"},", "numpy as np import pandas as pd import tests.test_app import", "\"row_limit\": 500, \"metric\": \"sum__SP_POP_TOTL\", \"entity\": \"country_code\", \"secondary_metric\": \"sum__SP_POP_TOTL\", \"granularity_sqla\": \"year\",", "33, \"%SUM(value1)\": 0.25, \"%avg__B\": 0.1, }, { \"groupA\": \"C\", \"groupB\":", "= viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual([\"colA\", \"colB\", metric], query_obj[\"metrics\"])", "\"count\", \"avg__C\", \"avg__B\", \"max__Y\"], query_obj[\"metrics\"] ) def test_query_obj_throws_columns_and_metrics(self): datasource =", "[0, 1, nan, 2], \"count\": [30, 42, 3, 29]}) test_viz", "\"metric1\": {\"a1\": 2, \"b1\": 2, \"c1\": 2}, \"metric2\": {\"a1\": 20,", "7] df = pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource, form_data) data =", "= [\"a3\", \"a3\", \"a3\", \"b3\", \"b3\", \"b3\", \"c3\", \"c3\", \"c3\"]", "0.25, \"%avg__B\": 0.1, }, { \"groupA\": \"C\", \"groupB\": \"z\", \"SUM(value1)\":", "\"2014-01-01\", \"until\": \"2014-01-02\", \"metrics\": [\"sum__SP_POP_TOTL\", \"SUM(SE_PRM_NENR_MA)\", \"SUM(SP_URB_TOTL)\"], \"country_fieldtype\": \"cca3\", \"percent_metrics\":", "query_obj = test_viz.query_obj() self.assertEqual(form_data[\"all_columns\"], query_obj[\"columns\"]) self.assertEqual([], query_obj[\"groupby\"]) self.assertEqual([[\"colA\", \"colB\"], [\"colC\"]],", "or implied. See the License for the # specific language", "self.assertRaises(Exception): test_viz.query_obj() class BaseDeckGLVizTestCase(SupersetTestCase): def test_get_metrics(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource", "\"adhoc_filters\": [ { \"expressionType\": \"SIMPLE\", \"clause\": \"WHERE\", \"subject\": \"value2\", \"operator\":", "\"expressionType\": \"SIMPLE\", \"clause\": \"HAVING\", \"subject\": \"SUM(value1)\", \"operator\": \"<\", \"comparator\": \"10\",", "viz.PartitionViz(Mock(), {}) time_op = \"point_diff\" levels = test_viz.levels_for_diff(time_op, groups, df)", "[\"sum__payout\"]} raw = {} raw[\"name\"] = [ \"Real Madrid C.F.🇺🇸🇬🇧\",", "= {DTTM_ALIAS: 1800, \"metric1\": 45, \"metric2\": 450, \"metric3\": 4500} self.assertEqual(expected,", "mock_gb) self.assertTrue(\"Bad spatial key\" in str(context.exception)) test_form_data = { \"latlong_key\":", "\"rolling_periods\": 2, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0,", "[1, 2, 3, 4, 5, 6, 7, 8, 9] df", "= viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_js_columns(mock_d) assert result == {\"color\":", "viz.BaseViz(datasource, form_data) result = test_viz.get_df(query_obj) self.assertEqual(type(result), pd.DataFrame) self.assertTrue(result.empty) def test_get_df_handles_dttm_col(self):", "= viz.BaseDeckGLViz(datasource, test_form_data) test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) assert expected_results.get(mock_key) == mock_gb def", "\"mean\", \"rolling_periods\": 10, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0,", "the # specific language governing permissions and limitations # under", "test_viz_deckgl.point_radius_fixed = {\"type\": \"metric\", \"value\": \"int\"} result = test_viz_deckgl.get_metrics() assert", "\"c1\": 24}, \"metric2\": {\"a1\": 60, \"b1\": 150, \"c1\": 240}, \"metric3\":", "raw[\"sum__payout\"] = [2, 2, 4, 4] df = pd.DataFrame(raw) test_viz", "\"order_desc\": False, } df = pd.DataFrame({\"SUM(value1)\": [15], \"sum_value\": [15]}) datasource", "= [\"groupA\", \"groupB\", \"groupC\"] test_viz = viz.PartitionViz(Mock(), {\"groupby\": groups}) def", "self.assertEqual(app.config[\"CACHE_DEFAULT_TIMEOUT\"], test_viz.cache_timeout) class TableVizTestCase(SupersetTestCase): def test_get_data_applies_percentage(self): form_data = { \"groupby\":", "\"metric1\", \"metric2\", \"metric3\"] self.assertEqual(sorted(cols), sorted(levels[0].columns.tolist())) cols += [\"groupA\"] self.assertEqual(sorted(cols), sorted(levels[1].columns.tolist()))", "= { 946684800000000000: [ {\"time\": t1, \"value\": 1, \"key\": (\"a1\",),", "t1, t1, t2, t2, t2] raw[\"sum__A\"] = [15, 20, 25,", "Mock() datasource.get_column = Mock(return_value=mock_dttm_col) mock_dttm_col.python_date_format = \"epoch_ms\" result = test_viz.get_df(query_obj)", "80, 90] raw[\"metric3\"] = [100, 200, 300, 400, 500, 600,", "The ASF licenses this file # to you under the", "def test_groupby_nulls(self): form_data = { \"metrics\": [\"votes\"], \"adhoc_filters\": [], \"groupby\":", "%H:%M:%S\" expected = { t1.strftime(time_format): {\"a1\": 15, \"a2\": 20, \"a3\":", "90}, ], \"group\": (\"c1\", \"c2\", \"c3\"), }, ], \"metric3\": [", "viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(NotImplementedError) as context: test_viz_deckgl.get_properties(mock_d) self.assertTrue(\"\" in str(context.exception))", "= {\"a\": \"dummy1\", \"b\": \"dummy2\", \"c\": \"dummy3\"} test_viz_deckgl = viz.BaseDeckGLViz(datasource,", "= 0 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(0, test_viz.cache_timeout) datasource.cache_timeout =", "[\"x\", \"y\"]} with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj() del", "} self.assertEqual(expected, data[\"records\"]) @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_throws_metrics_and_groupby(self, super_query_obj): datasource = self.get_datasource_mock()", "results.query = Mock() results.status = Mock() results.error_message = Mock() datasource", "test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual( [{\"col\": \"value2\",", "[], } datasource = self.get_datasource_mock() df = pd.DataFrame( { \"toppings\":", "{} form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.BaseDeckGLViz(datasource,", "@patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_merges_all_columns(self, super_query_obj): datasource = self.get_datasource_mock() form_data = {", "\"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"order_desc\": False,", "time_format = \"%Y-%m-%d %H:%M:%S\" expected = { t1.strftime(time_format): {\"a1\": 15,", "datasource.type = \"table\" datasource.query = Mock(return_value=results) mock_dttm_col = Mock() datasource.get_column", "TableViz metrics in correct order form_data = { \"url_params\": {},", "], \"group\": \"All\", } ], \"NULL\": [ { \"values\": [", "}, ], \"metric2\": [ { \"values\": [ {\"x\": 100, \"y\":", "test_viz.levels_for(time_op, groups, df) self.assertEqual(4, len(levels)) expected = { DTTM_ALIAS: 200.0,", "] self.assertEqual(expected, data[\"records\"]) def test_parse_adhoc_filters(self): form_data = { \"metrics\": [", "law or agreed to in writing, # software distributed under", "[ {\"x\": 100, \"y\": 70}, {\"x\": 200, \"y\": 80}, {\"x\":", "2.0, None, 4.0], } ) data = viz.BigNumberViz(datasource, {\"metrics\": [\"y\"]}).get_data(df)", "}, { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\",", "0 mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col) mock_dttm_col.python_date_format = \"epoch_ms\"", "def test_query_obj_merges_percent_metrics(self): datasource = self.get_datasource_mock() form_data = { \"metrics\": [\"sum__A\",", "= Mock() test_viz.get_fillna_for_columns = Mock(return_value=0) results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01 05:00:00\"]})", "for mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data.copy())", "], u\"key\": (u\"Real Madrid C.F.\\U0001f1fa\\U0001f1f8\\U0001f1ec\\U0001f1e7\",), }, ] self.assertEqual(expected, viz_data) def", "self.assertEqual(coord, (1.23, 3.21)) self.assertEqual(viz_instance.parse_coordinates(None), None) self.assertEqual(viz_instance.parse_coordinates(\"\"), None) def test_parse_coordinates_raises(self): form_data", "300, 400, 500, 600, 700, 800, 900] df = pd.DataFrame(raw)", "\"metric\", \"value\": \"int\"} result = test_viz_deckgl.get_metrics() assert result == [\"int\"]", "form_data = { \"all_columns\": [\"colA\", \"colB\", \"colC\"], \"order_by_cols\": ['[\"colA\", \"colB\"]',", "\"__timestamp\": pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0,", "super_query_obj): datasource = self.get_datasource_mock() form_data = { \"all_columns\": [\"colA\", \"colB\",", "viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual( [\"sum__A\", \"count\", \"avg__C\", \"avg__B\",", "[\"A\", \"B\", \"C\", \"C\"], \"groupB\": [\"x\", \"x\", \"y\", \"z\"], }", "\"value3 in ('North America')\", }, ], \"having\": \"SUM(value1) > 5\",", "{}) time_op = \"point_diff\" levels = test_viz.levels_for_diff(time_op, groups, df) expected", "\"y\"]} with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj() del form_data[\"metrics\"]", "t2, \"value\": 8, \"key\": (\"c1\",), \"name\": (\"c1\",)}, ], 1072915200000000000: [", "\"rolling_periods\": 0, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0,", "percents self.assertEqual( [ \"groupA\", \"groupB\", \"SUM(value1)\", \"count\", \"avg__C\", \"%SUM(value1)\", \"%avg__B\",", "test_process_metrics(self): # test TableViz metrics in correct order form_data =", "test_get_properties(self): mock_d = {} form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock()", "\"c3\"), }, ], \"metric2\": [ { \"values\": [ {\"x\": 100,", "test_get_df_handles_dttm_col(self): form_data = {\"dummy\": 123} query_obj = {\"granularity\": \"day\"} results", "OR CONDITIONS OF ANY # KIND, either express or implied.", "viz.TimeTableViz(datasource, form_data) data = test_viz.get_data(df) # Check method correctly transforms", "= viz.viz_types[\"paired_ttest\"](datasource, form_data) data = pairedTTestViz.get_data(df) # Check method correctly", ".tolist(), [1.0, 3.0, 5.0, 7.0], ) self.assertEqual( viz.BigNumberViz( datasource, {", "uuid from datetime import datetime import logging from math import", "15, \"a2\": 20, \"a3\": 25}, t2.strftime(time_format): {\"a1\": 30, \"a2\": 35,", "40, 50, 60, 70, 80, 90] raw[\"metric3\"] = [100, 200,", "2400}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"],", "self.assertEqual(expected_values, data[\"values\"]) def test_groupby_nans(self): form_data = { \"metrics\": [\"count\"], \"adhoc_filters\":", "3, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\": t3, \"value\": 6, \"key\":", "key\" in str(context.exception)) test_form_data = { \"latlong_key\": {\"type\": \"latlong\", \"lonCol\":", "[30, 42, 3, 29]}) test_viz = viz.DistributionBarViz(datasource, form_data) data =", "test_viz.get_data(df) expected = [ { u\"values\": [ {u\"y\": 4, u\"x\":", "= Mock(return_value=mock_dttm_col) test_viz = viz.BaseViz(datasource, form_data) test_viz.df_metrics_to_num = Mock() test_viz.get_fillna_for_columns", "[\"colA\", \"colB\", \"colC\"], \"order_by_cols\": ['[\"colA\", \"colB\"]', '[\"colC\"]'], } super_query_obj.return_value =", "test_geojson_query_obj(self): form_data = load_fixture(\"deck_geojson_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.DeckGeoJson(datasource,", "copyright ownership. The ASF licenses this file # to you", "test_viz_deckgl.add_null_filters() adhoc_filters = test_viz_deckgl.form_data[\"adhoc_filters\"] assert expected_results.get(mock_key) == adhoc_filters class TimeSeriesVizTestCase(SupersetTestCase):", "5, 15], \"avg__C\": [11, 22, 33, 44], \"count\": [6, 7,", "\"sqlExpression\": \"SUM(value1) > 5\", }, { \"expressionType\": \"SQL\", \"clause\": \"WHERE\",", "data[\"records\"]) @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_throws_metrics_and_groupby(self, super_query_obj): datasource = self.get_datasource_mock() form_data =", "[\"metric1\", \"metric2\", \"metric3\"] procs = {} for i in range(0,", "and computes percents self.assertEqual( [ \"groupA\", \"groupB\", \"SUM(value1)\", \"count\", \"avg__C\",", "\"SQL\", \"clause\": \"WHERE\", \"sqlExpression\": \"value3 in ('North America')\", }, ],", "self.assertEqual(form_data[\"all_columns\"], query_obj[\"columns\"]) self.assertEqual([], query_obj[\"groupby\"]) self.assertEqual([[\"colA\", \"colB\"], [\"colC\"]], query_obj[\"orderby\"]) def test_query_obj_uses_sortby(self):", "[ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"sum_value\", \"column\": {\"column_name\":", "expect_metric_labels = [ u\"sum__SP_POP_TOTL\", u\"SUM(SE_PRM_NENR_MA)\", u\"SUM(SP_URB_TOTL)\", u\"count\", ] self.assertEqual(test_viz.metric_labels, expect_metric_labels)", "\"c3\", \"c3\", \"c3\"] raw[\"metric1\"] = [1, 2, 3, 4, 5,", "in writing, # software distributed under the License is distributed", "\"c1\": 80}, \"metric3\": {\"a1\": 200, \"b1\": 500, \"c1\": 800}, }", "1, 6, 0)], name=DTTM_ALIAS) ) datasource.offset = 0 results.df =", "\"y\": 700}, {\"x\": 200, \"y\": 800}, {\"x\": 300, \"y\": 900},", "[15, 20] raw[\"count\"] = [6, 7] df = pd.DataFrame(raw) test_viz", "adhoc_filters = test_viz_deckgl.form_data[\"adhoc_filters\"] assert expected_results.get(mock_key) == adhoc_filters class TimeSeriesVizTestCase(SupersetTestCase): def", "test_viz.get_df(query_obj) import logging logger.info(result) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5,", "\"avg__C\": 44, \"%SUM(value1)\": 0.4, \"%avg__B\": 0.3, }, ] self.assertEqual(expected, data[\"records\"])", "{} for i in range(0, 4): df_drop = df.drop(groups[i:], 1)", "[6, 7] df = pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource, form_data) data", "[\"votes\"], \"adhoc_filters\": [], \"groupby\": [\"toppings\"], \"columns\": [], } datasource =", "}, { \"groupA\": \"C\", \"groupB\": \"z\", \"SUM(value1)\": 40, \"count\": 9,", "raw[\"metric2\"] = [10, 20, 30, 40, 50, 60, 70, 80,", "\"y\": 2}, {\"x\": \"cheese\", \"y\": 1}], }, { \"key\": \"engineer\",", "}, ], } self.assertEqual(data, expected) def test_get_data_empty_null_keys(self): form_data = {\"groupby\":", "[\"toppings\"], \"columns\": [], } datasource = self.get_datasource_mock() df = pd.DataFrame(", "levels[0].to_dict()) expected = { DTTM_ALIAS: {\"a1\": 600, \"b1\": 600, \"c1\":", "= [15, 20, 25, 30, 35, 40] raw[\"groupby1\"] = [\"a1\",", "self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.should_be_timeseries() def test_adhoc_metric_with_sortby(self): metrics =", "\"value1\", \"type\": \"DOUBLE\"}, } ], \"adhoc_filters\": [ { \"expressionType\": \"SIMPLE\",", "[\"cheese\", \"pepperoni\", \"cheese\", \"pepperoni\"], \"role\": [\"engineer\", \"engineer\", None, None], \"votes\":", "data = test_viz.get_data(df) # Check method correctly transforms data self.assertEqual(set([\"count\",", ") .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 5.0, 7.0], ) self.assertEqual( viz.BigNumberViz(", "test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data) test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) assert expected_results.get(mock_key) == mock_gb", "\"metrics\": metrics, \"timeseries_limit_metric\": { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\",", "mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: mock_gb = [] test_viz_deckgl =", "[\"metric1\", \"metric2\", \"metric3\"], } datasource = self.get_datasource_mock() # Test data", "def test_nest_values_returns_hierarchy(self): raw = {} raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\",", "self.assertEqual(None, nest[i].get(\"val\")) self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(3, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) self.assertEqual( 1,", "\"subject\": \"lon\", \"isExtra\": False, }, ], \"delimited_key\": [ { \"clause\":", "\"%avg__B\": 0.4, }, { \"groupA\": \"C\", \"groupB\": \"y\", \"SUM(value1)\": 25,", "7}, } self.assertEqual(expected, data[\"records\"]) def test_get_data_group_by(self): form_data = {\"metrics\": [\"sum__A\"],", "= viz.RoseViz(Mock(), fd) test_viz.metrics = fd[\"metrics\"] res = test_viz.get_data(df) expected", "pd.DataFrame({\"beds\": [0, 1, nan, 2], \"count\": [30, 42, 3, 29]})", "NOT NULL\", \"subject\": \"lonlat\", \"isExtra\": False, } ], \"geohash_key\": [", "viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics() assert result == [] def", "expected = {\"metric1\": 6, \"metric2\": 60, \"metric3\": 600} self.assertEqual(expected, levels[0].to_dict())", "= self.get_datasource_mock() form_data = {\"groupby\": [\"a\"]} super_query_obj.return_value = {} test_viz", "30}, ], \"group\": \"All\", } ], } self.assertEqual(data, expected) class", "test_levels_for_time_calls_process_data_and_drops_cols(self): raw = {} raw[DTTM_ALIAS] = [100, 200, 300, 100,", "test_viz.get_data(df)[0] self.assertEqual(\"votes\", data[\"key\"]) expected_values = [ {\"x\": \"pepperoni\", \"y\": 5},", "\"value\": 4, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t1, \"value\": 7,", "(\"a1\",)}, {\"time\": t2, \"value\": 5, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\":", "\"int\"} result = test_viz_deckgl.get_metrics() assert result == [\"int\"] form_data =", "context: test_viz_deckgl.get_properties(mock_d) self.assertTrue(\"\" in str(context.exception)) def test_process_spatial_query_obj(self): form_data = load_fixture(\"deck_path_form_data.json\")", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "600, \"b1\": 1500, \"c1\": 2400}, } self.assertEqual(expected, levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"],", "{ \"groupA\": \"B\", \"groupB\": \"x\", \"SUM(value1)\": 20, \"count\": 7, \"avg__C\":", "\">\", \"comparator\": \"100\", }, { \"expressionType\": \"SIMPLE\", \"clause\": \"HAVING\", \"subject\":", "def test_get_data_with_none(self): datasource = self.get_datasource_mock() df = pd.DataFrame( data={ DTTM_ALIAS:", "datasource = self.get_datasource_mock() df = pd.DataFrame( { \"SUM(value1)\": [15, 20,", "\"adv_anal\" test_viz.get_data(df) self.assertEqual(1, len(test_viz.levels_for_time.mock_calls)) self.assertEqual(1, len(test_viz.nest_procs.mock_calls)) test_viz.form_data[\"time_series_option\"] = \"time_series\" test_viz.get_data(df)", "= test_viz.levels_for_diff(time_op, groups, df) expected = {\"metric1\": 6, \"metric2\": 60,", "assert results[\"columns\"] == [\"test_col\"] def test_parse_coordinates(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource", "correctly transforms data and computes percents self.assertEqual( [ \"groupA\", \"groupB\",", "= self.get_datasource_mock() # Test data raw = {} raw[DTTM_ALIAS] =", "self.get_datasource_mock() df = pd.DataFrame( { \"SUM(value1)\": [15, 20, 25, 40],", "\"c1\"] raw[\"groupB\"] = [\"a2\", \"a2\", \"a2\", \"b2\", \"b2\", \"b2\", \"c2\",", "{\"granularity\": \"day\"} datasource = self.get_datasource_mock() test_viz = viz.BaseViz(datasource, form_data) result", "query_obj[\"filter\"] ) self.assertEqual( [{\"op\": \"<\", \"val\": \"10\", \"col\": \"SUM(value1)\"}], query_obj[\"extras\"][\"having_druid\"],", "{ \"metrics\": [\"y\"], \"rolling_type\": \"sum\", \"rolling_periods\": 2, \"min_periods\": 0, },", "\"delimited_key\": [\"lonlat\"], \"geohash_key\": [\"geo\"], } for mock_key in [\"latlong_key\", \"delimited_key\",", "\"metric2\", \"metric3\"], } datasource = self.get_datasource_mock() # Test data raw", "expected) class PartitionVizTestCase(SupersetTestCase): @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_time_series_option(self, super_query_obj): datasource = self.get_datasource_mock()", "CONDITIONS OF ANY # KIND, either express or implied. See", "test_viz.query_obj() self.assertTrue(query_obj[\"is_timeseries\"]) def test_levels_for_computes_levels(self): raw = {} raw[DTTM_ALIAS] = [100,", "test_viz = viz.TableViz(datasource, form_data) query_obj = test_viz.query_obj() self.assertEqual(form_data[\"all_columns\"], query_obj[\"columns\"]) self.assertEqual([],", "= \"agg_sum\" query_obj = test_viz.query_obj() self.assertTrue(query_obj[\"is_timeseries\"]) def test_levels_for_computes_levels(self): raw =", "\"sum__SP_POP_TOTL\", \"entity\": \"country_code\", \"secondary_metric\": \"sum__SP_POP_TOTL\", \"granularity_sqla\": \"year\", \"page_length\": 0, \"all_columns\":", "= {} form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl =", "200, \"y\": 800}, {\"x\": 300, \"y\": 900}, ], \"group\": (\"c1\",", "600}, \"metric1\": {\"a1\": 6, \"b1\": 15, \"c1\": 24}, \"metric2\": {\"a1\":", "= viz.PartitionViz(Mock(), {}) df = Mock() with self.assertRaises(ValueError): test_viz.get_data(df) test_viz.levels_for", "\"cumsum\", \"rolling_periods\": 0, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0,", "= self.get_datasource_mock() df = pd.DataFrame( { \"__timestamp\": pd.to_datetime( [\"2019-01-01\", \"2019-01-02\",", "\"type\": \"DOUBLE\"}, }, \"count\", \"avg__C\", ], \"percent_metrics\": [ { \"expressionType\":", "= pivot nest = test_viz.nest_procs(procs) self.assertEqual(3, len(nest)) for i in", "expected_values = [ {\"x\": \"pepperoni\", \"y\": 5}, {\"x\": \"cheese\", \"y\":", "], \"group\": (\"a1\", \"a2\", \"a3\"), }, { \"values\": [ {\"x\":", "], \"geohash_key\": [ { \"clause\": \"WHERE\", \"expressionType\": \"SIMPLE\", \"filterOptionName\": \"12345678-1234-5678-1234-567812345678\",", "= test_viz_deckgl.get_js_columns(mock_d) assert result == {\"color\": None} def test_get_properties(self): mock_d", "\"IS NOT NULL\", \"subject\": \"lonlat\", \"isExtra\": False, } ], \"geohash_key\":", "= {} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics() assert", "\"metrics\": [\"sum__SP_POP_TOTL\", \"SUM(SE_PRM_NENR_MA)\", \"SUM(SP_URB_TOTL)\"], \"country_fieldtype\": \"cca3\", \"percent_metrics\": [\"count\"], \"slice_id\": 74,", "[t1, t2] raw[\"sum__A\"] = [15, 20] raw[\"count\"] = [6, 7]", "= {} query_obj = test_viz.query_obj() self.assertFalse(query_obj[\"is_timeseries\"]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" query_obj", "8, 9] raw[\"metric2\"] = [10, 20, 30, 40, 50, 60,", "form_data) with self.assertRaises(ValueError) as context: test_viz_deckgl.process_spatial_query_obj(mock_key, mock_gb) self.assertTrue(\"Bad spatial key\"", "\"key\": (\"c1\",), \"name\": (\"c1\",)}, ], 1009843200000000000: [ {\"time\": t2, \"value\":", "self.assertEqual(0, test_viz.cache_timeout) datasource.cache_timeout = 156 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(156,", "20, 5, 15], \"avg__C\": [11, 22, 33, 44], \"count\": [6,", "query_obj[\"filter\"] ) self.assertEqual([], query_obj[\"extras\"][\"having_druid\"]) self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"\",", "form_data = {} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics()", "results[\"columns\"] == [\"test_col\"] def test_parse_coordinates(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource =", "self.assertEqual([[\"colA\", \"colB\"], [\"colC\"]], query_obj[\"orderby\"]) def test_query_obj_uses_sortby(self): datasource = self.get_datasource_mock() form_data", "\"metric1\": {\"a1\": 6, \"b1\": 15, \"c1\": 24}, \"metric2\": {\"a1\": 60,", "df) nest = test_viz.nest_values(levels) self.assertEqual(3, len(nest)) for i in range(0,", "{\"x\": NULL_STRING, \"y\": 3}, ] self.assertEqual(expected_values, data[\"values\"]) def test_column_nulls(self): form_data", "\"metrics\": [\"metric1\", \"metric2\", \"metric3\"], } datasource = self.get_datasource_mock() # Test", "form_data = { \"metrics\": [\"colA\", \"colB\"], \"order_desc\": False, } def", "test_viz = viz.PartitionViz(Mock(), {\"groupby\": groups}) def return_args(df_drop, aggregate): return df_drop", "NULL\", \"subject\": \"lonlat\", \"isExtra\": False, } ], \"geohash_key\": [ {", ".tolist(), [1.0, 2.0, np.nan, np.nan, 5.0, np.nan, 7.0], ) def", "\"metric1\": {\"a1\": 2, \"b1\": 5, \"c1\": 8}, \"metric2\": {\"a1\": 20,", "pd.DataFrame( { \"__timestamp\": pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\":", "\"entity\": \"country_code\", \"secondary_metric\": \"sum__SP_POP_TOTL\", \"granularity_sqla\": \"year\", \"page_length\": 0, \"all_columns\": [],", "levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) time_op =", "mock_dttm_col.python_date_format = \"epoch_ms\" result = test_viz.get_df(query_obj) import logging logger.info(result) pd.testing.assert_series_equal(", "def test_geojson_query_obj(self): form_data = load_fixture(\"deck_geojson_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl =", "levels[1].to_dict()) self.assertEqual([\"groupA\", \"groupB\"], levels[2].index.names) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_diff_computes_difference(self):", "\"engineer\", None, None], \"votes\": [3, 5, 1, 2], } )", "5.0, 0.0, 7.0], ) np.testing.assert_equal( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\":", "], } self.assertEqual(expected, res) class TimeSeriesTableVizTestCase(SupersetTestCase): def test_get_data_metrics(self): form_data =", "(\"c1\",), \"name\": (\"c1\",)}, ], } self.assertEqual(expected, res) class TimeSeriesTableVizTestCase(SupersetTestCase): def", "with self.assertRaises(Exception): test_viz = viz.TableViz(datasource, form_data) test_viz.query_obj() del form_data[\"metrics\"] form_data[\"groupby\"]", "len(levels)) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_time_calls_process_data_and_drops_cols(self): raw = {}", "[ {\"time\": t3, \"value\": 3, \"key\": (\"a1\",), \"name\": (\"a1\",)}, {\"time\":", "SupersetTestCase from .utils import load_fixture logger = logging.getLogger(__name__) class BaseVizTestCase(SupersetTestCase):", "[\"y\"], \"rolling_type\": \"mean\", \"rolling_periods\": 10, \"min_periods\": 0, }, ) .apply_rolling(df)[\"y\"]", "transforms data self.assertEqual(set([\"a1\", \"a2\", \"a3\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d %H:%M:%S\"", "= fd[\"metrics\"] res = test_viz.get_data(df) expected = { 946684800000000000: [", "7.0], ) def test_apply_rolling(self): datasource = self.get_datasource_mock() df = pd.DataFrame(", "\"groupC\"], levels[3].index.names) time_op = \"agg_mean\" levels = test_viz.levels_for(time_op, groups, df)", "100, 200, 300] raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\", \"b1\",", "\"anchovies\", None], \"votes\": [3, 5, 1, 2], } ) test_viz", "\"c2\"] raw[\"groupC\"] = [\"a3\", \"a3\", \"a3\", \"b3\", \"b3\", \"b3\", \"c3\",", "(\"c1\",)}, ], } self.assertEqual(expected, res) class TimeSeriesTableVizTestCase(SupersetTestCase): def test_get_data_metrics(self): form_data", "\"y\"] test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception): test_viz.query_obj() class BaseDeckGLVizTestCase(SupersetTestCase):", "3}], }, ] self.assertEqual(expected, data) class PairedTTestTestCase(SupersetTestCase): def test_get_data_transforms_dataframe(self): form_data", "\"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid Basket\", \"Real Madrid Basket\", ]", "{\"a1\": 2, \"b1\": 5, \"c1\": 8}, \"metric2\": {\"a1\": 20, \"b1\":", "def test_query_obj_time_series_option(self, super_query_obj): datasource = self.get_datasource_mock() form_data = {} test_viz", "] self.assertEqual(expected, viz_data) def test_process_data_resample(self): datasource = self.get_datasource_mock() df =", "= Mock(return_value=0) results.df = pd.DataFrame(data={DTTM_ALIAS: [\"1960-01-01 05:00:00\"]}) datasource.offset = 0", "74, \"time_grain_sqla\": None, \"order_by_cols\": [], \"groupby\": [\"country_name\"], \"compare_lag\": \"10\", \"limit\":", "t2 = pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t2] raw[\"sum__A\"] = [15,", "\"clause\": \"HAVING\", \"sqlExpression\": \"SUM(value1) > 5\", }, { \"expressionType\": \"SQL\",", "expected = { \"metric1\": [ { \"values\": [ {\"x\": 100,", "the License is distributed on an # \"AS IS\" BASIS,", "5, 6, 7, 8, 9] df = pd.DataFrame(raw) fd =", "def test_query_obj_merges_all_columns(self, super_query_obj): datasource = self.get_datasource_mock() form_data = { \"all_columns\":", "[ \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid C.F.🇺🇸🇬🇧\", \"Real Madrid Basket\",", "def test_get_properties(self): mock_d = {} form_data = load_fixture(\"deck_path_form_data.json\") datasource =", "= [6, 7] df = pd.DataFrame(raw) test_viz = viz.TimeTableViz(datasource, form_data)", "test_viz_deckgl.get_metrics() assert result == [\"int\"] form_data = {} test_viz_deckgl =", "viz.BaseViz(datasource, form_data={}) self.assertEqual(app.config[\"CACHE_DEFAULT_TIMEOUT\"], test_viz.cache_timeout) class TableVizTestCase(SupersetTestCase): def test_get_data_applies_percentage(self): form_data =", "viz.BaseDeckGLViz(datasource, form_data) result = test_viz_deckgl.get_metrics() assert result == [form_data.get(\"size\")] form_data", "\"metric2\": [ { \"values\": [ {\"x\": 100, \"y\": 10}, {\"x\":", "test_viz_deckgl.get_metrics() assert result == [form_data.get(\"size\")] form_data = {} test_viz_deckgl =", "\"DOUBLE\"}, }, \"order_desc\": False, } df = pd.DataFrame({\"SUM(value1)\": [15], \"sum_value\":", "\"y\": 42}, {\"x\": \"0.0\", \"y\": 30}, {\"x\": \"2.0\", \"y\": 29},", "[\"a1\", \"a2\", \"a3\", \"a1\", \"a2\", \"a3\"] df = pd.DataFrame(raw) test_viz", "form_data = {\"dummy\": 123} query_obj = {\"granularity\": \"day\"} results =", "class RoseVisTestCase(SupersetTestCase): def test_rose_vis_get_data(self): raw = {} t1 = pd.Timestamp(\"2000\")", "\"100\", \"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual([], query_obj[\"extras\"][\"having_druid\"]) self.assertEqual(\"(value3 in ('North", "raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\", \"b1\", \"b1\", \"c1\", \"c1\",", "800}, {\"x\": 300, \"y\": 900}, ], \"group\": (\"c1\", \"c2\", \"c3\"),", "\">\", \"comparator\": \"100\", }, { \"expressionType\": \"SQL\", \"clause\": \"WHERE\", \"sqlExpression\":", "class TableVizTestCase(SupersetTestCase): def test_get_data_applies_percentage(self): form_data = { \"groupby\": [\"groupA\", \"groupB\"],", "Check method correctly transforms data expected = { \"N/A\": [", "} self.assertEqual(data, expected) class PartitionVizTestCase(SupersetTestCase): @patch(\"superset.viz.BaseViz.query_obj\") def test_query_obj_time_series_option(self, super_query_obj): datasource", "@patch(\"superset.utils.core.uuid.uuid4\") def test_filter_nulls(self, mock_uuid4): mock_uuid4.return_value = uuid.UUID(\"12345678123456781234567812345678\") test_form_data = {", "= Mock(return_value=mock_dttm_col) mock_dttm_col.python_date_format = \"epoch_ms\" result = test_viz.get_df(query_obj) import logging", "600, \"b1\": 600, \"c1\": 600}, \"metric1\": {\"a1\": 6, \"b1\": 15,", "30, 35, 40] raw[\"groupby1\"] = [\"a1\", \"a2\", \"a3\", \"a1\", \"a2\",", "levels[1].to_dict()) self.assertEqual(4, len(levels)) self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_time_calls_process_data_and_drops_cols(self): raw", "test_viz.get_data(df) expected = { 946684800000000000: [ {\"time\": t1, \"value\": 1,", "\"b1\": 200}, \"metric1\": {\"a1\": 2, \"b1\": 5, \"c1\": 8}, \"metric2\":", "{DTTM_ALIAS: pd.Timestamp(\"2019-01-05\"), \"y\": 3}) def test_get_data_with_none(self): datasource = self.get_datasource_mock() df", "\"key\": (\"c1\",), \"name\": (\"c1\",)}, ], 1072915200000000000: [ {\"time\": t3, \"value\":", "25, 30, 35, 40] raw[\"groupby1\"] = [\"a1\", \"a2\", \"a3\", \"a1\",", "self.assertEqual(4, len(levels)) cols = [DTTM_ALIAS, \"metric1\", \"metric2\", \"metric3\"] self.assertEqual(sorted(cols), sorted(levels[0].columns.tolist()))", "4500} self.assertEqual(expected, levels[0].to_dict()) expected = { DTTM_ALIAS: {\"a1\": 600, \"b1\":", "[ { \"values\": [ {\"x\": 100, \"y\": 100}, {\"x\": 200,", "viz.BaseDeckGLViz(datasource, test_form_data.copy()) test_viz_deckgl.spatial_control_keys = [mock_key] test_viz_deckgl.add_null_filters() adhoc_filters = test_viz_deckgl.form_data[\"adhoc_filters\"] assert", "\"avg__B\": [10, 20, 5, 15], \"avg__C\": [11, 22, 33, 44],", "form_data) query_obj = test_viz.query_obj() self.assertEqual( [\"sum__A\", \"count\", \"avg__C\", \"avg__B\", \"max__Y\"],", "= { \"metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\":", "metrics, \"timeseries_limit_metric\": { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\", \"column\":", "\"SIMPLE\", \"clause\": \"WHERE\", \"subject\": \"value2\", \"operator\": \">\", \"comparator\": \"100\", },", "\"time_grain_sqla\": None, \"order_by_cols\": [], \"groupby\": [\"country_name\"], \"compare_lag\": \"10\", \"limit\": \"25\",", "7.0], } ) self.assertEqual( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"], \"resample_method\": \"sum\",", "= self.get_datasource_mock() form_data = { \"all_columns\": [\"colA\", \"colB\", \"colC\"], \"order_by_cols\":", "in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: test_viz_deckgl = viz.BaseDeckGLViz(datasource, test_form_data.copy()) test_viz_deckgl.spatial_control_keys =", "data = test_viz.get_data(df)[0] self.assertEqual(\"votes\", data[\"key\"]) expected_values = [ {\"x\": \"pepperoni\",", "200, \"y\": 8}, {\"x\": 300, \"y\": 9}, ], \"group\": (\"c1\",", "%H:%M:%S\", \"markup_type\": \"markdown\", \"where\": \"\", \"compare_suffix\": \"o10Y\", } datasource =", "test_process_data_resample(self): datasource = self.get_datasource_mock() df = pd.DataFrame( { \"__timestamp\": pd.to_datetime(", "\"groupB\"], \"metrics\": [ { \"expressionType\": \"SIMPLE\", \"aggregate\": \"SUM\", \"label\": \"SUM(value1)\",", "{ \"url_params\": {}, \"row_limit\": 500, \"metric\": \"sum__SP_POP_TOTL\", \"entity\": \"country_code\", \"secondary_metric\":", "5.0, \"metric2\": 50.0, \"metric3\": 500.0, } self.assertEqual(expected, levels[0].to_dict()) expected =", "test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(0, test_viz.cache_timeout) datasource.cache_timeout = 156 test_viz", "(the # \"License\"); you may not use this file except", "3.0, 6.0, 10.0], ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"],", "datetime import datetime import logging from math import nan from", "\"metric3\": {\"a1\": 600, \"b1\": 1500, \"c1\": 2400}, } self.assertEqual(expected, levels[1].to_dict())", "load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_d = {\"a\": \"dummy1\", \"b\": \"dummy2\",", "\"a2\", \"a3\"), }, { \"values\": [ {\"x\": 100, \"y\": 40},", "[10, 20, 30] df = pd.DataFrame(raw) pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource, form_data)", "= Mock() datasource = Mock() datasource.type = \"table\" datasource.query =", "\"a3\"), }, { \"values\": [ {\"x\": 100, \"y\": 40}, {\"x\":", "import logging logger.info(result) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1, 1, 5, 0)],", "self.assertRaises(SpatialException): test_viz_deckgl.parse_coordinates(\"fldkjsalkj,fdlaskjfjadlksj\") @patch(\"superset.utils.core.uuid.uuid4\") def test_filter_nulls(self, mock_uuid4): mock_uuid4.return_value = uuid.UUID(\"12345678123456781234567812345678\") test_form_data", "\"pepperoni\"], \"role\": [\"engineer\", \"engineer\", None, None], \"votes\": [3, 5, 1,", "200, \"y\": 2}, {\"x\": 300, \"y\": 3}, ], \"group\": (\"a1\",", "test_viz.get_data(df) expected = [ { \"key\": NULL_STRING, \"values\": [{\"x\": \"pepperoni\",", "test_parse_coordinates(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() viz_instance = viz.BaseDeckGLViz(datasource,", "[ {\"x\": 100, \"y\": 4}, {\"x\": 200, \"y\": 5}, {\"x\":", "200.0, \"metric1\": 5.0, \"metric2\": 50.0, \"metric3\": 500.0, } self.assertEqual(expected, levels[0].to_dict())", "\"table\" datasource.query = Mock(return_value=results) mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col)", "\"avg__B\", ], } datasource = self.get_datasource_mock() df = pd.DataFrame( {", "data = viz.BigNumberViz(datasource, {\"metrics\": [\"y\"]}).get_data(df) self.assertEqual(data[2], {DTTM_ALIAS: pd.Timestamp(\"2019-01-05\"), \"y\": 3})", "viz.BigNumberViz(datasource, {\"metrics\": [\"y\"]}).get_data(df) self.assertEqual(data[2], {DTTM_ALIAS: pd.Timestamp(\"2019-01-05\"), \"y\": 3}) def test_get_data_with_none(self):", ") def test_query_obj_throws_columns_and_metrics(self): datasource = self.get_datasource_mock() form_data = {\"all_columns\": [\"A\",", "self.get_datasource_mock() form_data = {\"all_columns\": [\"A\", \"B\"], \"metrics\": [\"x\", \"y\"]} with", "], \"metric2\": [ { \"values\": [ {\"x\": 100, \"y\": 10},", "\"value\": \"int\"} result = test_viz_deckgl.get_metrics() assert result == [\"int\"] form_data", ".apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 6.0, 10.0], ) self.assertEqual( viz.BigNumberViz( datasource,", "mock_dttm_col.python_date_format = \"%Y-%m-%d\" result = test_viz.get_df(query_obj) pd.testing.assert_series_equal( result[DTTM_ALIAS], pd.Series([datetime(1960, 1,", "query_obj[\"extras\"][\"having\"]) def test_query_obj_merges_percent_metrics(self): datasource = self.get_datasource_mock() form_data = { \"metrics\":", "\"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, 3.0, 4.0], }", "\"sum\", \"resample_rule\": \"1D\"}, ) .process_data(df)[\"y\"] .tolist(), [1.0, 2.0, 0.0, 0.0,", "{}) groups = [\"groupA\", \"groupB\", \"groupC\"] metrics = [\"metric1\", \"metric2\",", "), \"y\": [1.0, 2.0, None, 4.0], } ) data =", "= \"point_diff\" test_viz.levels_for_diff = Mock(return_value=1) test_viz.get_data(df) self.assertEqual(\"point_diff\", test_viz.levels_for_diff.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] =", "\"<\", \"comparator\": \"10\", }, { \"expressionType\": \"SQL\", \"clause\": \"HAVING\", \"sqlExpression\":", "expected) def test_get_data_empty_null_keys(self): form_data = {\"groupby\": [], \"metrics\": [\"\", None]}", "self.assertEqual(3, len(nest[0][\"children\"])) self.assertEqual(3, len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) self.assertEqual( 1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"][0][\"children\"]) )", "with the License. You may obtain a copy of the", "self.assertEqual([], query_obj[\"extras\"][\"having_druid\"]) self.assertEqual(\"(value3 in ('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"\", query_obj[\"extras\"][\"having\"]) def", "import NULL_STRING from superset.exceptions import SpatialException from superset.utils.core import DTTM_ALIAS", "self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" test_viz.get_data(df) self.assertEqual(\"agg_sum\", test_viz.levels_for.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] =", "= { t1.strftime(time_format): {\"sum__A\": 15, \"count\": 6}, t2.strftime(time_format): {\"sum__A\": 20,", "= None test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(app.config[\"CACHE_DEFAULT_TIMEOUT\"], test_viz.cache_timeout) class TableVizTestCase(SupersetTestCase):", "\"engineer\", \"values\": [{\"x\": \"pepperoni\", \"y\": 5}, {\"x\": \"cheese\", \"y\": 3}],", "correctly transforms data self.assertEqual(set([\"a1\", \"a2\", \"a3\"]), set(data[\"columns\"])) time_format = \"%Y-%m-%d", "applicable law or agreed to in writing, # software distributed", "\"label\": \"SUM(value1)\", \"column\": {\"column_name\": \"value1\", \"type\": \"DOUBLE\"}, }, \"avg__B\", ],", "= \"point_percent\" test_viz.get_data(df) self.assertEqual(\"point_percent\", test_viz.levels_for_diff.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_factor\" test_viz.get_data(df) self.assertEqual(\"point_factor\",", "test_viz.cache_timeout) datasource.cache_timeout = None datasource.database.cache_timeout = 0 self.assertEqual(0, test_viz.cache_timeout) datasource.database.cache_timeout", "= logging.getLogger(__name__) class BaseVizTestCase(SupersetTestCase): def test_constructor_exception_no_datasource(self): form_data = {} datasource", "] self.assertEqual(test_viz.metric_labels, expect_metric_labels) self.assertEqual(test_viz.all_metrics, expect_metric_labels) def test_get_df_returns_empty_df(self): form_data = {\"dummy\":", "form_data) results = test_viz_deckgl.query_obj() assert results[\"metrics\"] == [] assert results[\"groupby\"]", "for i in range(0, 4): df_drop = df.drop(groups[i:], 1) pivot", "= Mock() results.error_message = Mock() datasource = Mock() datasource.type =", "= self.get_datasource_mock() form_data = {\"include_time\": True} with self.assertRaises(Exception): test_viz =", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "600, 700, 800, 900] df = pd.DataFrame(raw) pairedTTestViz = viz.viz_types[\"paired_ttest\"](datasource,", "file # to you under the Apache License, Version 2.0", "form_data = {\"all_columns\": [\"A\", \"B\"], \"metrics\": [\"x\", \"y\"]} with self.assertRaises(Exception):", "\"C\", \"C\"], \"groupB\": [\"x\", \"x\", \"y\", \"z\"], } ) test_viz", "test_viz.form_data[\"time_series_option\"] = \"point_diff\" test_viz.levels_for_diff = Mock(return_value=1) test_viz.get_data(df) self.assertEqual(\"point_diff\", test_viz.levels_for_diff.mock_calls[0][1][0]) test_viz.form_data[\"time_series_option\"]", "# with the License. You may obtain a copy of", "\"values\": [ {\"x\": 100, \"y\": 10}, {\"x\": 200, \"y\": 20},", "viz.BaseViz(datasource, form_data) test_viz.df_metrics_to_num = Mock() test_viz.get_fillna_for_columns = Mock(return_value=0) results.df =", "form_data = load_fixture(\"deck_geojson_form_data.json\") datasource = self.get_datasource_mock() test_viz_deckgl = viz.DeckGeoJson(datasource, form_data)", "= self.get_datasource_mock() df = pd.DataFrame( index=pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"]", "test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) with self.assertRaises(NotImplementedError) as context: test_viz_deckgl.get_properties(mock_d) self.assertTrue(\"\"", "[100, 200, 300, 400, 500, 600, 700, 800, 900] df", "= [\"groupA\", \"groupB\", \"groupC\"] metrics = [\"metric1\", \"metric2\", \"metric3\"] procs", "t3] raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\", \"b1\", \"b1\", \"c1\",", "\"y\": 300}, ], \"group\": (\"a1\", \"a2\", \"a3\"), }, { \"values\":", "test_get_data_metrics(self): form_data = {\"metrics\": [\"sum__A\", \"count\"], \"groupby\": []} datasource =", "t1.strftime(time_format): {\"a1\": 15, \"a2\": 20, \"a3\": 25}, t2.strftime(time_format): {\"a1\": 30,", "= { \"latlong_key\": [\"lon\", \"lat\"], \"delimited_key\": [\"lonlat\"], \"geohash_key\": [\"geo\"], }", "{} viz_data = test_viz.get_data(df) expected = [ { u\"values\": [", "\"y\": 900}, ], \"group\": (\"c1\", \"c2\", \"c3\"), }, ], }", "= { DTTM_ALIAS: {\"a1\": 600, \"b1\": 600, \"c1\": 600}, \"metric1\":", "\"b1\": 15, \"c1\": 24}, \"metric2\": {\"a1\": 60, \"b1\": 150, \"c1\":", "300, \"y\": 30}, ], \"group\": \"All\", } ], } self.assertEqual(data,", "pd.DataFrame(raw) test_viz = viz.PartitionViz(Mock(), {}) groups = [\"groupA\", \"groupB\", \"groupC\"]", "\"SUM(value1)\": 40, \"count\": 9, \"avg__C\": 44, \"%SUM(value1)\": 0.4, \"%avg__B\": 0.3,", "under one # or more contributor license agreements. See the", "\"geo\"}, } datasource = self.get_datasource_mock() expected_results = { \"latlong_key\": [\"lon\",", "[1.0, 2.0, 3.0, 4.0], } ) data = viz.BigNumberViz(datasource, {\"metrics\":", "# Check method correctly transforms data self.assertEqual(set([\"a1\", \"a2\", \"a3\"]), set(data[\"columns\"]))", "\"%avg__B\": 0.2, }, { \"groupA\": \"B\", \"groupB\": \"x\", \"SUM(value1)\": 20,", "= viz.BaseViz(datasource, form_data={}) self.assertEqual(156, test_viz.cache_timeout) datasource.cache_timeout = None datasource.database.cache_timeout =", "15, \"count\": 6, \"avg__C\": 11, \"%SUM(value1)\": 0.15, \"%avg__B\": 0.2, },", "\"filterOptionName\": \"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lon\",", "def test_query_obj_throws_metrics_and_groupby(self, super_query_obj): datasource = self.get_datasource_mock() form_data = {\"groupby\": [\"a\"]}", "datasource = self.get_datasource_mock() test_viz = viz.BaseViz(datasource, form_data) result = test_viz.get_df(query_obj)", "test_viz.query_obj() self.assertFalse(query_obj[\"is_timeseries\"]) test_viz.form_data[\"time_series_option\"] = \"agg_sum\" query_obj = test_viz.query_obj() self.assertTrue(query_obj[\"is_timeseries\"]) def", "test_viz = viz.RoseViz(Mock(), fd) test_viz.metrics = fd[\"metrics\"] res = test_viz.get_data(df)", ") test_viz = viz.DistributionBarViz(datasource, form_data) data = test_viz.get_data(df) expected =", "self.assertEqual( 1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"][0][\"children\"]) ) def test_get_data_calls_correct_method(self): test_viz = viz.PartitionViz(Mock(), {})", "{ \"metrics\": [\"votes\"], \"adhoc_filters\": [], \"groupby\": [\"toppings\"], \"columns\": [\"role\"], }", "8, 9] df = pd.DataFrame(raw) fd = {\"metrics\": [\"metric1\"], \"groupby\":", "C.F.🇺🇸🇬🇧\", \"Real Madrid Basket\", \"Real Madrid Basket\", ] raw[\"__timestamp\"] =", "len(nest[0][\"children\"][0][\"children\"])) self.assertEqual(1, len(nest[0][\"children\"][0][\"children\"][0][\"children\"])) def test_nest_procs_returns_hierarchy(self): raw = {} raw[DTTM_ALIAS] =", "pd.to_datetime( [\"2019-01-01\", \"2019-01-02\", \"2019-01-05\", \"2019-01-07\"] ), \"y\": [1.0, 2.0, None,", "viz.PartitionViz(Mock(), {}) groups = [\"groupA\", \"groupB\", \"groupC\"] metrics = [\"metric1\",", "u\"values\": [ {u\"y\": 4, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 4, u\"x\": u\"2018-03-09T00:00:00\"},", "4, \"key\": (\"b1\",), \"name\": (\"b1\",)}, {\"time\": t1, \"value\": 7, \"key\":", "form_data[\"metrics\"] = [\"x\", \"y\"] test_viz = viz.TimeTableViz(datasource, form_data) with self.assertRaises(Exception):", "44, \"%SUM(value1)\": 0.4, \"%avg__B\": 0.3, }, ] self.assertEqual(expected, data[\"records\"]) def", "= Mock() results.status = Mock() results.error_message = Mock() datasource =", "0, }, ) .apply_rolling(df)[\"y\"] .tolist(), [1.0, 3.0, 5.0, 7.0], )", "= Mock(return_value=results) mock_dttm_col = Mock() datasource.get_column = Mock(return_value=mock_dttm_col) test_viz =", "60}, ], \"group\": (\"b1\", \"b2\", \"b3\"), }, { \"values\": [", "None, None], \"votes\": [3, 5, 1, 2], } ) test_viz", "datasource = Mock() datasource.type = \"table\" datasource.query = Mock(return_value=results) mock_dttm_col", "\"12345678-1234-5678-1234-567812345678\", \"comparator\": \"\", \"operator\": \"IS NOT NULL\", \"subject\": \"lat\", \"isExtra\":", "[1.0, 2.0, 3.0, 4.0]}, ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\":", "\"x\", \"SUM(value1)\": 15, \"count\": 6, \"avg__C\": 11, \"%SUM(value1)\": 0.15, \"%avg__B\":", "agreements. See the NOTICE file # distributed with this work", "\"metric2\": {\"a1\": 60, \"b1\": 150, \"c1\": 240}, \"metric3\": {\"a1\": 600,", "self.assertEqual([\"groupA\", \"groupB\", \"groupC\"], levels[3].index.names) def test_levels_for_diff_computes_difference(self): raw = {} raw[DTTM_ALIAS]", "u\"values\": [ {u\"y\": 2, u\"x\": u\"2018-02-20T00:00:00\"}, {u\"y\": 2, u\"x\": u\"2018-03-09T00:00:00\"},", "[DTTM_ALIAS, \"metric1\", \"metric2\", \"metric3\"] self.assertEqual(sorted(cols), sorted(levels[0].columns.tolist())) cols += [\"groupA\"] self.assertEqual(sorted(cols),", "{\"x\": 100, \"y\": 1}, {\"x\": 200, \"y\": 2}, {\"x\": 300,", "2.0, 5.0, 7.0], } ) self.assertEqual( viz.NVD3TimeSeriesViz( datasource, {\"metrics\": [\"y\"],", "class DistBarVizTestCase(SupersetTestCase): def test_groupby_nulls(self): form_data = { \"metrics\": [\"votes\"], \"adhoc_filters\":", "(\"b1\",), \"name\": (\"b1\",)}, {\"time\": t2, \"value\": 8, \"key\": (\"c1\",), \"name\":", "\"avg__C\", \"avg__B\", \"max__Y\"], query_obj[\"metrics\"] ) def test_query_obj_throws_columns_and_metrics(self): datasource = self.get_datasource_mock()", "= [100, 200, 300, 400, 500, 600, 700, 800, 900]", "pd.Timestamp(\"2002\") raw[DTTM_ALIAS] = [t1, t2] raw[\"sum__A\"] = [15, 20] raw[\"count\"]", "viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"mean\", \"rolling_periods\": 10, \"min_periods\":", "(1.23, 3.21)) self.assertEqual(viz_instance.parse_coordinates(None), None) self.assertEqual(viz_instance.parse_coordinates(\"\"), None) def test_parse_coordinates_raises(self): form_data =", "t2, t3] raw[\"groupA\"] = [\"a1\", \"a1\", \"a1\", \"b1\", \"b1\", \"b1\",", "{\"x\": 200, \"y\": 20}, {\"x\": 300, \"y\": 30}, ], \"group\":", "{ \"SUM(value1)\": [15, 20, 25, 40], \"avg__B\": [10, 20, 5,", "\"values\": [ {\"x\": 100, \"y\": 40}, {\"x\": 200, \"y\": 50},", "u\"2018-02-20T00:00:00\"}, {u\"y\": 2, u\"x\": u\"2018-03-09T00:00:00\"}, ], u\"key\": (u\"Real Madrid C.F.\\U0001f1fa\\U0001f1f8\\U0001f1ec\\U0001f1e7\",),", "self.assertRaises(NotImplementedError) as context: test_viz_deckgl.get_properties(mock_d) self.assertTrue(\"\" in str(context.exception)) def test_process_spatial_query_obj(self): form_data", "= {} test_viz_deckgl = viz.DeckScatterViz(datasource, form_data) test_viz_deckgl.point_radius_fixed = {\"type\": \"metric\",", "License. You may obtain a copy of the License at", "\"slice_id\": 74, \"time_grain_sqla\": None, \"order_by_cols\": [], \"groupby\": [\"country_name\"], \"compare_lag\": \"10\",", "('North America'))\", query_obj[\"extras\"][\"where\"]) self.assertEqual(\"\", query_obj[\"extras\"][\"having\"]) def test_query_obj_merges_percent_metrics(self): datasource = self.get_datasource_mock()", "100, \"y\": 1}, {\"x\": 200, \"y\": 2}, {\"x\": 300, \"y\":", "\"name\": (\"a1\",)}, {\"time\": t1, \"value\": 4, \"key\": (\"b1\",), \"name\": (\"b1\",)},", "= test_viz.get_df(query_obj) self.assertEqual(type(result), pd.DataFrame) self.assertTrue(result.empty) def test_get_df_handles_dttm_col(self): form_data = {\"dummy\":", "}, { \"values\": [ {\"x\": 100, \"y\": 70}, {\"x\": 200,", "self.assertEqual( [{\"col\": \"value2\", \"val\": \"100\", \"op\": \">\"}], query_obj[\"filter\"] ) self.assertEqual([],", "def test_adhoc_filters_overwrite_legacy_filters(self): form_data = { \"metrics\": [ { \"expressionType\": \"SIMPLE\",", ") def test_cache_timeout(self): datasource = self.get_datasource_mock() datasource.cache_timeout = 0 test_viz", "} for mock_key in [\"latlong_key\", \"delimited_key\", \"geohash_key\"]: test_viz_deckgl = viz.BaseDeckGLViz(datasource,", "= self.get_datasource_mock() df = pd.DataFrame( { \"toppings\": [\"cheese\", \"pepperoni\", \"anchovies\",", "\"dummy1\", \"b\": \"dummy2\", \"c\": \"dummy3\"} test_viz_deckgl = viz.BaseDeckGLViz(datasource, form_data) result", "= 0 self.assertEqual(0, test_viz.cache_timeout) datasource.database.cache_timeout = 1666 self.assertEqual(1666, test_viz.cache_timeout) datasource.database.cache_timeout", "== {\"color\": None} def test_get_properties(self): mock_d = {} form_data =", "4.0]}, ) self.assertEqual( viz.BigNumberViz( datasource, { \"metrics\": [\"y\"], \"rolling_type\": \"cumsum\",", "\"groupA\": \"C\", \"groupB\": \"z\", \"SUM(value1)\": 40, \"count\": 9, \"avg__C\": 44,", "self.assertEqual(\"point_percent\", test_viz.levels_for_diff.mock_calls[1][1][0]) test_viz.form_data[\"time_series_option\"] = \"point_factor\" test_viz.get_data(df) self.assertEqual(\"point_factor\", test_viz.levels_for_diff.mock_calls[2][1][0]) test_viz.levels_for_time =", "\"type\": \"DOUBLE\"}, } ] form_data = { \"metrics\": metrics, \"timeseries_limit_metric\":", "str(context.exception)) def test_process_spatial_query_obj(self): form_data = load_fixture(\"deck_path_form_data.json\") datasource = self.get_datasource_mock() mock_key", "test_viz.levels_for.mock_calls[3][1][0]) self.assertEqual(7, len(test_viz.nest_values.mock_calls)) class RoseVisTestCase(SupersetTestCase): def test_rose_vis_get_data(self): raw = {}", "form_data) viz_data = {} viz_data = test_viz.get_data(df) expected = [", "} self.assertEqual(expected, res) class TimeSeriesTableVizTestCase(SupersetTestCase): def test_get_data_metrics(self): form_data = {\"metrics\":", "datasource = self.get_datasource_mock() form_data = {\"groupby\": [\"name\"], \"metrics\": [\"sum__payout\"]} raw", "200, \"y\": 50}, {\"x\": 300, \"y\": 60}, ], \"group\": (\"b1\",", "range(0, 4): df_drop = df.drop(groups[i:], 1) pivot = df_drop.pivot_table( index=DTTM_ALIAS,", "= self.get_datasource_mock() datasource.cache_timeout = 0 test_viz = viz.BaseViz(datasource, form_data={}) self.assertEqual(0,", "\"count\": [6, 7, 8, 9], \"groupA\": [\"A\", \"B\", \"C\", \"C\"]," ]
[ "def append_task(self, task_code : str): self.tqueue.append(task_code) # キュー内の最初のタスクを実行する # 処理が失敗した場合は先頭に戻す", "task_code : str): self.tqueue.append(task_code) # キュー内の最初のタスクを実行する # 処理が失敗した場合は先頭に戻す def exec_first(self):", "実行に失敗したため再実行すべく先頭に戻す # self.tqueue.insert(0, task_code) # ChordUtil.dprint(\"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\"", "TYPE_CHECKING: from .chord_node import ChordNode class TaskQueue: JOIN_PARTIAL = \"join_partial\"", "exec_first(self): if len(self.tqueue) > 0: ChordUtil.dprint(\"exec_first_0,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\"", "class TaskQueue: JOIN_PARTIAL = \"join_partial\" def __init__(self, existing_node : 'ChordNode'):", "# except (InternalControlFlowException, NodeIsDownedExceptiopn): # # 実行に失敗したため再実行すべく先頭に戻す # self.tqueue.insert(0, task_code)", "else: # ret.err_code == ErrorCode.InternalControlFlowException_CODE # 実行に失敗したため再実行すべく先頭に戻す self.tqueue.insert(0, task_code) ChordUtil.dprint(", "'ChordNode'): self.tqueue : List[str] = [] self.existing_node = existing_node def", "append_task(self, task_code : str): self.tqueue.append(task_code) # キュー内の最初のタスクを実行する # 処理が失敗した場合は先頭に戻す def", "JOIN_PARTIAL = \"join_partial\" def __init__(self, existing_node : 'ChordNode'): self.tqueue :", "Optional, cast, TYPE_CHECKING from .chord_util import ChordUtil, InternalControlFlowException, NodeIsDownedExceptiopn if", "+ \",\" + str(self.tqueue)) task_code : str = self.tqueue.pop() if", "# ret.err_code == ErrorCode.InternalControlFlowException_CODE # 実行に失敗したため再実行すべく先頭に戻す self.tqueue.insert(0, task_code) ChordUtil.dprint( \"exec_first_1,\"", "__init__(self, existing_node : 'ChordNode'): self.tqueue : List[str] = [] self.existing_node", "(ret.is_ok): pass else: # ret.err_code == ErrorCode.InternalControlFlowException_CODE # 実行に失敗したため再実行すべく先頭に戻す self.tqueue.insert(0,", "# 処理が失敗した場合は先頭に戻す def exec_first(self): if len(self.tqueue) > 0: ChordUtil.dprint(\"exec_first_0,\" +", "self.tqueue.append(task_code) # キュー内の最初のタスクを実行する # 処理が失敗した場合は先頭に戻す def exec_first(self): if len(self.tqueue) >", ": List[str] = [] self.existing_node = existing_node def append_task(self, task_code", "import ChordUtil, InternalControlFlowException, NodeIsDownedExceptiopn if TYPE_CHECKING: from .chord_node import ChordNode", "ChordUtil, InternalControlFlowException, NodeIsDownedExceptiopn if TYPE_CHECKING: from .chord_node import ChordNode class", "self.existing_node = existing_node def append_task(self, task_code : str): self.tqueue.append(task_code) #", "self.tqueue.insert(0, task_code) ChordUtil.dprint( \"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + \"INTERNAL_CONTROL_FLOW_EXCEPTION_OCCURED\")", "ret = self.existing_node.stabilizer.partial_join_op() if (ret.is_ok): pass else: # ret.err_code ==", "InternalControlFlowException, NodeIsDownedExceptiopn if TYPE_CHECKING: from .chord_node import ChordNode class TaskQueue:", "coding:utf-8 from typing import Dict, List, Optional, cast, TYPE_CHECKING from", "\"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + \"INTERNAL_CONTROL_FLOW_EXCEPTION_OCCURED\") # except (InternalControlFlowException,", "NodeIsDownedExceptiopn if TYPE_CHECKING: from .chord_node import ChordNode class TaskQueue: JOIN_PARTIAL", "from .chord_node import ChordNode class TaskQueue: JOIN_PARTIAL = \"join_partial\" def", "処理が失敗した場合は先頭に戻す def exec_first(self): if len(self.tqueue) > 0: ChordUtil.dprint(\"exec_first_0,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info)", "try: #self.existing_node.stabilizer.partial_join_op() ret = self.existing_node.stabilizer.partial_join_op() if (ret.is_ok): pass else: #", "self.existing_node.stabilizer.partial_join_op() if (ret.is_ok): pass else: # ret.err_code == ErrorCode.InternalControlFlowException_CODE #", "if task_code == TaskQueue.JOIN_PARTIAL: # try: #self.existing_node.stabilizer.partial_join_op() ret = self.existing_node.stabilizer.partial_join_op()", "NodeIsDownedExceptiopn): # # 実行に失敗したため再実行すべく先頭に戻す # self.tqueue.insert(0, task_code) # ChordUtil.dprint(\"exec_first_1,\" +", "\"join_partial\" def __init__(self, existing_node : 'ChordNode'): self.tqueue : List[str] =", "TYPE_CHECKING from .chord_util import ChordUtil, InternalControlFlowException, NodeIsDownedExceptiopn if TYPE_CHECKING: from", "[] self.existing_node = existing_node def append_task(self, task_code : str): self.tqueue.append(task_code)", "str = self.tqueue.pop() if task_code == TaskQueue.JOIN_PARTIAL: # try: #self.existing_node.stabilizer.partial_join_op()", "ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + str(self.tqueue)) task_code : str = self.tqueue.pop()", ".chord_util import ChordUtil, InternalControlFlowException, NodeIsDownedExceptiopn if TYPE_CHECKING: from .chord_node import", "ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + \"INTERNAL_CONTROL_FLOW_EXCEPTION_OCCURED\") # except (InternalControlFlowException, NodeIsDownedExceptiopn): #", "\",\" + str(self.tqueue)) task_code : str = self.tqueue.pop() if task_code", "(InternalControlFlowException, NodeIsDownedExceptiopn): # # 実行に失敗したため再実行すべく先頭に戻す # self.tqueue.insert(0, task_code) # ChordUtil.dprint(\"exec_first_1,\"", "from .chord_util import ChordUtil, InternalControlFlowException, NodeIsDownedExceptiopn if TYPE_CHECKING: from .chord_node", "+ ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + \"INTERNAL_CONTROL_FLOW_EXCEPTION_OCCURED\") # except (InternalControlFlowException, NodeIsDownedExceptiopn):", "# 実行に失敗したため再実行すべく先頭に戻す self.tqueue.insert(0, task_code) ChordUtil.dprint( \"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\"", "= [] self.existing_node = existing_node def append_task(self, task_code : str):", "\"INTERNAL_CONTROL_FLOW_EXCEPTION_OCCURED\") # except (InternalControlFlowException, NodeIsDownedExceptiopn): # # 実行に失敗したため再実行すべく先頭に戻す # self.tqueue.insert(0,", "+ \"INTERNAL_CONTROL_FLOW_EXCEPTION_OCCURED\") # except (InternalControlFlowException, NodeIsDownedExceptiopn): # # 実行に失敗したため再実行すべく先頭に戻す #", "task_code == TaskQueue.JOIN_PARTIAL: # try: #self.existing_node.stabilizer.partial_join_op() ret = self.existing_node.stabilizer.partial_join_op() if", "task_code) # ChordUtil.dprint(\"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" # + \"INTERNAL_CONTROL_FLOW_EXCEPTION_OCCURED\")", "task_code) ChordUtil.dprint( \"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + \"INTERNAL_CONTROL_FLOW_EXCEPTION_OCCURED\") #", "from typing import Dict, List, Optional, cast, TYPE_CHECKING from .chord_util", "len(self.tqueue) > 0: ChordUtil.dprint(\"exec_first_0,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + str(self.tqueue))", "\",\" + \"INTERNAL_CONTROL_FLOW_EXCEPTION_OCCURED\") # except (InternalControlFlowException, NodeIsDownedExceptiopn): # # 実行に失敗したため再実行すべく先頭に戻す", "ErrorCode.InternalControlFlowException_CODE # 実行に失敗したため再実行すべく先頭に戻す self.tqueue.insert(0, task_code) ChordUtil.dprint( \"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) +", "# coding:utf-8 from typing import Dict, List, Optional, cast, TYPE_CHECKING", "if (ret.is_ok): pass else: # ret.err_code == ErrorCode.InternalControlFlowException_CODE # 実行に失敗したため再実行すべく先頭に戻す", "self.tqueue : List[str] = [] self.existing_node = existing_node def append_task(self,", "Dict, List, Optional, cast, TYPE_CHECKING from .chord_util import ChordUtil, InternalControlFlowException,", "TaskQueue.JOIN_PARTIAL: # try: #self.existing_node.stabilizer.partial_join_op() ret = self.existing_node.stabilizer.partial_join_op() if (ret.is_ok): pass", "0: ChordUtil.dprint(\"exec_first_0,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + str(self.tqueue)) task_code :", "== ErrorCode.InternalControlFlowException_CODE # 実行に失敗したため再実行すべく先頭に戻す self.tqueue.insert(0, task_code) ChordUtil.dprint( \"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info)", "+ \",\" + \"INTERNAL_CONTROL_FLOW_EXCEPTION_OCCURED\") # except (InternalControlFlowException, NodeIsDownedExceptiopn): # #", "List, Optional, cast, TYPE_CHECKING from .chord_util import ChordUtil, InternalControlFlowException, NodeIsDownedExceptiopn", "import ChordNode class TaskQueue: JOIN_PARTIAL = \"join_partial\" def __init__(self, existing_node", "self.tqueue.insert(0, task_code) # ChordUtil.dprint(\"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" # +", "import Dict, List, Optional, cast, TYPE_CHECKING from .chord_util import ChordUtil,", "TaskQueue: JOIN_PARTIAL = \"join_partial\" def __init__(self, existing_node : 'ChordNode'): self.tqueue", "+ str(self.tqueue)) task_code : str = self.tqueue.pop() if task_code ==", "if len(self.tqueue) > 0: ChordUtil.dprint(\"exec_first_0,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" +", ": str = self.tqueue.pop() if task_code == TaskQueue.JOIN_PARTIAL: # try:", "+ ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + str(self.tqueue)) task_code : str =", "pass else: # ret.err_code == ErrorCode.InternalControlFlowException_CODE # 実行に失敗したため再実行すべく先頭に戻す self.tqueue.insert(0, task_code)", "typing import Dict, List, Optional, cast, TYPE_CHECKING from .chord_util import", "self.tqueue.pop() if task_code == TaskQueue.JOIN_PARTIAL: # try: #self.existing_node.stabilizer.partial_join_op() ret =", "> 0: ChordUtil.dprint(\"exec_first_0,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + str(self.tqueue)) task_code", "existing_node : 'ChordNode'): self.tqueue : List[str] = [] self.existing_node =", "if TYPE_CHECKING: from .chord_node import ChordNode class TaskQueue: JOIN_PARTIAL =", "= self.existing_node.stabilizer.partial_join_op() if (ret.is_ok): pass else: # ret.err_code == ErrorCode.InternalControlFlowException_CODE", "def __init__(self, existing_node : 'ChordNode'): self.tqueue : List[str] = []", "str): self.tqueue.append(task_code) # キュー内の最初のタスクを実行する # 処理が失敗した場合は先頭に戻す def exec_first(self): if len(self.tqueue)", "キュー内の最初のタスクを実行する # 処理が失敗した場合は先頭に戻す def exec_first(self): if len(self.tqueue) > 0: ChordUtil.dprint(\"exec_first_0,\"", "実行に失敗したため再実行すべく先頭に戻す self.tqueue.insert(0, task_code) ChordUtil.dprint( \"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" +", "# try: #self.existing_node.stabilizer.partial_join_op() ret = self.existing_node.stabilizer.partial_join_op() if (ret.is_ok): pass else:", "#self.existing_node.stabilizer.partial_join_op() ret = self.existing_node.stabilizer.partial_join_op() if (ret.is_ok): pass else: # ret.err_code", "except (InternalControlFlowException, NodeIsDownedExceptiopn): # # 実行に失敗したため再実行すべく先頭に戻す # self.tqueue.insert(0, task_code) #", ": str): self.tqueue.append(task_code) # キュー内の最初のタスクを実行する # 処理が失敗した場合は先頭に戻す def exec_first(self): if", "== TaskQueue.JOIN_PARTIAL: # try: #self.existing_node.stabilizer.partial_join_op() ret = self.existing_node.stabilizer.partial_join_op() if (ret.is_ok):", ".chord_node import ChordNode class TaskQueue: JOIN_PARTIAL = \"join_partial\" def __init__(self,", "List[str] = [] self.existing_node = existing_node def append_task(self, task_code :", "ChordUtil.dprint( \"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + \"INTERNAL_CONTROL_FLOW_EXCEPTION_OCCURED\") # except", "= existing_node def append_task(self, task_code : str): self.tqueue.append(task_code) # キュー内の最初のタスクを実行する", ": 'ChordNode'): self.tqueue : List[str] = [] self.existing_node = existing_node", "= self.tqueue.pop() if task_code == TaskQueue.JOIN_PARTIAL: # try: #self.existing_node.stabilizer.partial_join_op() ret", "# self.tqueue.insert(0, task_code) # ChordUtil.dprint(\"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" #", "# キュー内の最初のタスクを実行する # 処理が失敗した場合は先頭に戻す def exec_first(self): if len(self.tqueue) > 0:", "# # 実行に失敗したため再実行すべく先頭に戻す # self.tqueue.insert(0, task_code) # ChordUtil.dprint(\"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info)", "= \"join_partial\" def __init__(self, existing_node : 'ChordNode'): self.tqueue : List[str]", "ChordNode class TaskQueue: JOIN_PARTIAL = \"join_partial\" def __init__(self, existing_node :", "ChordUtil.dprint(\"exec_first_0,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) + \",\" + str(self.tqueue)) task_code : str", "ret.err_code == ErrorCode.InternalControlFlowException_CODE # 実行に失敗したため再実行すべく先頭に戻す self.tqueue.insert(0, task_code) ChordUtil.dprint( \"exec_first_1,\" +", "str(self.tqueue)) task_code : str = self.tqueue.pop() if task_code == TaskQueue.JOIN_PARTIAL:", "# 実行に失敗したため再実行すべく先頭に戻す # self.tqueue.insert(0, task_code) # ChordUtil.dprint(\"exec_first_1,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) +", "cast, TYPE_CHECKING from .chord_util import ChordUtil, InternalControlFlowException, NodeIsDownedExceptiopn if TYPE_CHECKING:", "def exec_first(self): if len(self.tqueue) > 0: ChordUtil.dprint(\"exec_first_0,\" + ChordUtil.gen_debug_str_of_node(self.existing_node.node_info) +", "existing_node def append_task(self, task_code : str): self.tqueue.append(task_code) # キュー内の最初のタスクを実行する #", "task_code : str = self.tqueue.pop() if task_code == TaskQueue.JOIN_PARTIAL: #" ]
[ "= DataLoader(self.train_ds, self._bs, shuffle=True, drop_last=True) self.val_ds = dataset_class.load_data_and_vectorizer(self.val_df, self.vectorizer) self.val_dl", "self._bs, shuffle=True, drop_last=True) self.val_ds = dataset_class.load_data_and_vectorizer(self.val_df, self.vectorizer) self.val_dl = DataLoader(self.val_ds,", "{'train_size': len(self.train_df), 'val_size': len(self.val_df)} self._n_batches = [self._lengths['train_size'] // self._bs, self._lengths['val_size']", "model self.optimizer = optimizer self.loss_fn = loss_fn self.scheduler = scheduler", "@property def val_batches(self): return self._n_batches[1] @property def test_batches(self): if not", "= self.vectorizer.surname_vocab self.nationality_vocab = self.vectorizer.nationality_vocab self.train_dl = DataLoader(self.train_ds, self._bs, shuffle=True,", "is_load self._lengths = {'train_size': len(self.train_df), 'val_size': len(self.val_df)} self._n_batches = [self._lengths['train_size']", "DataContainer(object): def __init__(self, df_with_split: pd.DataFrame, dataset_class, vectorizer_file: Path, batch_size: int,", "self.model = model self.optimizer = optimizer self.loss_fn = loss_fn self.scheduler", "self._n_batches.append(self._lengths['test_size'] // self._bs) self.test_ds = dataset_class.load_data_and_vectorizer(self.test_df, self.vectorizer) self.test_dl = DataLoader(self.test_ds,", "as pd from pathlib import Path from torch.utils.data import DataLoader", "saving vectorizer\") train_ds = dataset_class.load_data_and_create_vectorizer(self.train_df) train_ds.save_vectorizer(vectorizer_file) self.train_ds = dataset_class.load_data_and_vectorizer_from_file(self.train_df, vectorizer_file)", "DataLoader(self.val_ds, self._bs, shuffle=True, drop_last=True) if self.with_test: self.test_df = df_with_split.loc[df_with_split['split'] ==", "self.vectorizer.surname_vocab self.nationality_vocab = self.vectorizer.nationality_vocab self.train_dl = DataLoader(self.train_ds, self._bs, shuffle=True, drop_last=True)", "scheduler class DataContainer(object): def __init__(self, df_with_split: pd.DataFrame, dataset_class, vectorizer_file: Path,", "== 'train'] self.val_df = df_with_split.loc[df_with_split['split'] == 'val'] self._bs = batch_size", "batch_size self.with_test = with_test self.is_load = is_load self._lengths = {'train_size':", "dataset_class.load_data_and_vectorizer(self.val_df, self.vectorizer) self.val_dl = DataLoader(self.val_ds, self._bs, shuffle=True, drop_last=True) if self.with_test:", "loss_fn self.scheduler = scheduler class DataContainer(object): def __init__(self, df_with_split: pd.DataFrame,", "== 'val'] self._bs = batch_size self.with_test = with_test self.is_load =", "vectorizer\") train_ds = dataset_class.load_data_and_create_vectorizer(self.train_df) train_ds.save_vectorizer(vectorizer_file) self.train_ds = dataset_class.load_data_and_vectorizer_from_file(self.train_df, vectorizer_file) self.vectorizer", "provided\") return self._n_batches[2] @property def vocab_size(self): return len(self.surname_vocab) @property def", "self.val_dl = DataLoader(self.val_ds, self._bs, shuffle=True, drop_last=True) if self.with_test: self.test_df =", "def get_loaders(self): return self.train_dl, self.val_dl, self.test_dl @property def train_batches(self): return", "self._n_batches[0] @property def val_batches(self): return self._n_batches[1] @property def test_batches(self): if", "if not self.with_test: raise NameError(\"No test dataset was provided\") return", "= dataset_class.load_data_and_create_vectorizer(self.train_df) train_ds.save_vectorizer(vectorizer_file) self.train_ds = dataset_class.load_data_and_vectorizer_from_file(self.train_df, vectorizer_file) self.vectorizer = self.train_ds.vectorizer", "dataset_class, vectorizer_file: Path, batch_size: int, with_test=True, is_load: bool=True) -> None:", "vocab_size(self): return len(self.surname_vocab) @property def n_classes(self): return len(self.nationality_vocab) @property def", "self.val_ds = dataset_class.load_data_and_vectorizer(self.val_df, self.vectorizer) self.val_dl = DataLoader(self.val_ds, self._bs, shuffle=True, drop_last=True)", "with_test=True, is_load: bool=True) -> None: self.train_df = df_with_split.loc[df_with_split['split'] == 'train']", "return self._n_batches[2] @property def vocab_size(self): return len(self.surname_vocab) @property def n_classes(self):", "self._bs) self.test_ds = dataset_class.load_data_and_vectorizer(self.test_df, self.vectorizer) self.test_dl = DataLoader(self.test_ds, self._bs, shuffle=True,", "model, optimizer, loss_fn, scheduler=None): self.model = model self.optimizer = optimizer", "def test_batches(self): if not self.with_test: raise NameError(\"No test dataset was", "return self._n_batches[0] @property def val_batches(self): return self._n_batches[1] @property def test_batches(self):", "self.vectorizer) self.val_dl = DataLoader(self.val_ds, self._bs, shuffle=True, drop_last=True) if self.with_test: self.test_df", "if not self.is_load: print(\"Creating and saving vectorizer\") train_ds = dataset_class.load_data_and_create_vectorizer(self.train_df)", "import Path from torch.utils.data import DataLoader class ModelContainer(object): def __init__(self,", "self.train_df = df_with_split.loc[df_with_split['split'] == 'train'] self.val_df = df_with_split.loc[df_with_split['split'] == 'val']", "self.val_df = df_with_split.loc[df_with_split['split'] == 'val'] self._bs = batch_size self.with_test =", "__init__(self, df_with_split: pd.DataFrame, dataset_class, vectorizer_file: Path, batch_size: int, with_test=True, is_load:", "if self.with_test: self.test_df = df_with_split.loc[df_with_split['split'] == 'test'] self._lengths['test_size'] = len(self.test_df)", "DataLoader(self.test_ds, self._bs, shuffle=True, drop_last=True) def get_loaders(self): return self.train_dl, self.val_dl, self.test_dl", "self.val_dl, self.test_dl @property def train_batches(self): return self._n_batches[0] @property def val_batches(self):", "= optimizer self.loss_fn = loss_fn self.scheduler = scheduler class DataContainer(object):", "dataset_class.load_data_and_vectorizer(self.test_df, self.vectorizer) self.test_dl = DataLoader(self.test_ds, self._bs, shuffle=True, drop_last=True) def get_loaders(self):", "is_load: bool=True) -> None: self.train_df = df_with_split.loc[df_with_split['split'] == 'train'] self.val_df", "drop_last=True) def get_loaders(self): return self.train_dl, self.val_dl, self.test_dl @property def train_batches(self):", "def vocab_size(self): return len(self.surname_vocab) @property def n_classes(self): return len(self.nationality_vocab) @property", "optimizer self.loss_fn = loss_fn self.scheduler = scheduler class DataContainer(object): def", "'train'] self.val_df = df_with_split.loc[df_with_split['split'] == 'val'] self._bs = batch_size self.with_test", "def __init__(self, df_with_split: pd.DataFrame, dataset_class, vectorizer_file: Path, batch_size: int, with_test=True,", "drop_last=True) self.val_ds = dataset_class.load_data_and_vectorizer(self.val_df, self.vectorizer) self.val_dl = DataLoader(self.val_ds, self._bs, shuffle=True,", "= model self.optimizer = optimizer self.loss_fn = loss_fn self.scheduler =", "def __init__(self, model, optimizer, loss_fn, scheduler=None): self.model = model self.optimizer", "= scheduler class DataContainer(object): def __init__(self, df_with_split: pd.DataFrame, dataset_class, vectorizer_file:", "import pandas as pd from pathlib import Path from torch.utils.data", "vectorizer_file: Path, batch_size: int, with_test=True, is_load: bool=True) -> None: self.train_df", "len(self.test_df) self._n_batches.append(self._lengths['test_size'] // self._bs) self.test_ds = dataset_class.load_data_and_vectorizer(self.test_df, self.vectorizer) self.test_dl =", "= df_with_split.loc[df_with_split['split'] == 'val'] self._bs = batch_size self.with_test = with_test", "df_with_split.loc[df_with_split['split'] == 'val'] self._bs = batch_size self.with_test = with_test self.is_load", "test dataset was provided\") return self._n_batches[2] @property def vocab_size(self): return", "self.vectorizer = self.train_ds.vectorizer self.surname_vocab = self.vectorizer.surname_vocab self.nationality_vocab = self.vectorizer.nationality_vocab self.train_dl", "== 'test'] self._lengths['test_size'] = len(self.test_df) self._n_batches.append(self._lengths['test_size'] // self._bs) self.test_ds =", "self._bs] if not self.is_load: print(\"Creating and saving vectorizer\") train_ds =", "was provided\") return self._n_batches[2] @property def vocab_size(self): return len(self.surname_vocab) @property", "self.train_ds = dataset_class.load_data_and_vectorizer_from_file(self.train_df, vectorizer_file) self.vectorizer = self.train_ds.vectorizer self.surname_vocab = self.vectorizer.surname_vocab", "train_ds.save_vectorizer(vectorizer_file) self.train_ds = dataset_class.load_data_and_vectorizer_from_file(self.train_df, vectorizer_file) self.vectorizer = self.train_ds.vectorizer self.surname_vocab =", "int, with_test=True, is_load: bool=True) -> None: self.train_df = df_with_split.loc[df_with_split['split'] ==", "'test'] self._lengths['test_size'] = len(self.test_df) self._n_batches.append(self._lengths['test_size'] // self._bs) self.test_ds = dataset_class.load_data_and_vectorizer(self.test_df,", "@property def vocab_size(self): return len(self.surname_vocab) @property def n_classes(self): return len(self.nationality_vocab)", "shuffle=True, drop_last=True) def get_loaders(self): return self.train_dl, self.val_dl, self.test_dl @property def", "python import pandas as pd from pathlib import Path from", "self.train_ds.vectorizer self.surname_vocab = self.vectorizer.surname_vocab self.nationality_vocab = self.vectorizer.nationality_vocab self.train_dl = DataLoader(self.train_ds,", "#!/usr/bin/env python import pandas as pd from pathlib import Path", "len(self.val_df)} self._n_batches = [self._lengths['train_size'] // self._bs, self._lengths['val_size'] // self._bs] if", "self._n_batches = [self._lengths['train_size'] // self._bs, self._lengths['val_size'] // self._bs] if not", "= dataset_class.load_data_and_vectorizer(self.val_df, self.vectorizer) self.val_dl = DataLoader(self.val_ds, self._bs, shuffle=True, drop_last=True) if", "def val_batches(self): return self._n_batches[1] @property def test_batches(self): if not self.with_test:", "self.test_ds = dataset_class.load_data_and_vectorizer(self.test_df, self.vectorizer) self.test_dl = DataLoader(self.test_ds, self._bs, shuffle=True, drop_last=True)", "self.test_dl @property def train_batches(self): return self._n_batches[0] @property def val_batches(self): return", "get_loaders(self): return self.train_dl, self.val_dl, self.test_dl @property def train_batches(self): return self._n_batches[0]", "= DataLoader(self.val_ds, self._bs, shuffle=True, drop_last=True) if self.with_test: self.test_df = df_with_split.loc[df_with_split['split']", "def train_batches(self): return self._n_batches[0] @property def val_batches(self): return self._n_batches[1] @property", "DataLoader(self.train_ds, self._bs, shuffle=True, drop_last=True) self.val_ds = dataset_class.load_data_and_vectorizer(self.val_df, self.vectorizer) self.val_dl =", "= with_test self.is_load = is_load self._lengths = {'train_size': len(self.train_df), 'val_size':", "self.with_test = with_test self.is_load = is_load self._lengths = {'train_size': len(self.train_df),", "self.vectorizer.nationality_vocab self.train_dl = DataLoader(self.train_ds, self._bs, shuffle=True, drop_last=True) self.val_ds = dataset_class.load_data_and_vectorizer(self.val_df,", "@property def train_batches(self): return self._n_batches[0] @property def val_batches(self): return self._n_batches[1]", "// self._bs) self.test_ds = dataset_class.load_data_and_vectorizer(self.test_df, self.vectorizer) self.test_dl = DataLoader(self.test_ds, self._bs,", "-> None: self.train_df = df_with_split.loc[df_with_split['split'] == 'train'] self.val_df = df_with_split.loc[df_with_split['split']", "self._n_batches[2] @property def vocab_size(self): return len(self.surname_vocab) @property def n_classes(self): return", "df_with_split.loc[df_with_split['split'] == 'train'] self.val_df = df_with_split.loc[df_with_split['split'] == 'val'] self._bs =", "torch.utils.data import DataLoader class ModelContainer(object): def __init__(self, model, optimizer, loss_fn,", "class ModelContainer(object): def __init__(self, model, optimizer, loss_fn, scheduler=None): self.model =", "self._bs, self._lengths['val_size'] // self._bs] if not self.is_load: print(\"Creating and saving", "= dataset_class.load_data_and_vectorizer_from_file(self.train_df, vectorizer_file) self.vectorizer = self.train_ds.vectorizer self.surname_vocab = self.vectorizer.surname_vocab self.nationality_vocab", "self._bs, shuffle=True, drop_last=True) def get_loaders(self): return self.train_dl, self.val_dl, self.test_dl @property", "return self.train_dl, self.val_dl, self.test_dl @property def train_batches(self): return self._n_batches[0] @property", "dataset was provided\") return self._n_batches[2] @property def vocab_size(self): return len(self.surname_vocab)", "NameError(\"No test dataset was provided\") return self._n_batches[2] @property def vocab_size(self):", "self._n_batches[1] @property def test_batches(self): if not self.with_test: raise NameError(\"No test", "__init__(self, model, optimizer, loss_fn, scheduler=None): self.model = model self.optimizer =", "shuffle=True, drop_last=True) if self.with_test: self.test_df = df_with_split.loc[df_with_split['split'] == 'test'] self._lengths['test_size']", "@property def n_classes(self): return len(self.nationality_vocab) @property def sizes(self): return self._lengths", "train_ds = dataset_class.load_data_and_create_vectorizer(self.train_df) train_ds.save_vectorizer(vectorizer_file) self.train_ds = dataset_class.load_data_and_vectorizer_from_file(self.train_df, vectorizer_file) self.vectorizer =", "self.is_load: print(\"Creating and saving vectorizer\") train_ds = dataset_class.load_data_and_create_vectorizer(self.train_df) train_ds.save_vectorizer(vectorizer_file) self.train_ds", "return len(self.surname_vocab) @property def n_classes(self): return len(self.nationality_vocab) @property def sizes(self):", "= self.vectorizer.nationality_vocab self.train_dl = DataLoader(self.train_ds, self._bs, shuffle=True, drop_last=True) self.val_ds =", "batch_size: int, with_test=True, is_load: bool=True) -> None: self.train_df = df_with_split.loc[df_with_split['split']", "import DataLoader class ModelContainer(object): def __init__(self, model, optimizer, loss_fn, scheduler=None):", "dataset_class.load_data_and_vectorizer_from_file(self.train_df, vectorizer_file) self.vectorizer = self.train_ds.vectorizer self.surname_vocab = self.vectorizer.surname_vocab self.nationality_vocab =", "test_batches(self): if not self.with_test: raise NameError(\"No test dataset was provided\")", "self.train_dl, self.val_dl, self.test_dl @property def train_batches(self): return self._n_batches[0] @property def", "ModelContainer(object): def __init__(self, model, optimizer, loss_fn, scheduler=None): self.model = model", "len(self.train_df), 'val_size': len(self.val_df)} self._n_batches = [self._lengths['train_size'] // self._bs, self._lengths['val_size'] //", "= self.train_ds.vectorizer self.surname_vocab = self.vectorizer.surname_vocab self.nationality_vocab = self.vectorizer.nationality_vocab self.train_dl =", "df_with_split.loc[df_with_split['split'] == 'test'] self._lengths['test_size'] = len(self.test_df) self._n_batches.append(self._lengths['test_size'] // self._bs) self.test_ds", "DataLoader class ModelContainer(object): def __init__(self, model, optimizer, loss_fn, scheduler=None): self.model", "self.scheduler = scheduler class DataContainer(object): def __init__(self, df_with_split: pd.DataFrame, dataset_class,", "bool=True) -> None: self.train_df = df_with_split.loc[df_with_split['split'] == 'train'] self.val_df =", "and saving vectorizer\") train_ds = dataset_class.load_data_and_create_vectorizer(self.train_df) train_ds.save_vectorizer(vectorizer_file) self.train_ds = dataset_class.load_data_and_vectorizer_from_file(self.train_df,", "self.surname_vocab = self.vectorizer.surname_vocab self.nationality_vocab = self.vectorizer.nationality_vocab self.train_dl = DataLoader(self.train_ds, self._bs,", "= batch_size self.with_test = with_test self.is_load = is_load self._lengths =", "shuffle=True, drop_last=True) self.val_ds = dataset_class.load_data_and_vectorizer(self.val_df, self.vectorizer) self.val_dl = DataLoader(self.val_ds, self._bs,", "= df_with_split.loc[df_with_split['split'] == 'test'] self._lengths['test_size'] = len(self.test_df) self._n_batches.append(self._lengths['test_size'] // self._bs)", "self.test_df = df_with_split.loc[df_with_split['split'] == 'test'] self._lengths['test_size'] = len(self.test_df) self._n_batches.append(self._lengths['test_size'] //", "not self.is_load: print(\"Creating and saving vectorizer\") train_ds = dataset_class.load_data_and_create_vectorizer(self.train_df) train_ds.save_vectorizer(vectorizer_file)", "self.vectorizer) self.test_dl = DataLoader(self.test_ds, self._bs, shuffle=True, drop_last=True) def get_loaders(self): return", "drop_last=True) if self.with_test: self.test_df = df_with_split.loc[df_with_split['split'] == 'test'] self._lengths['test_size'] =", "self.with_test: self.test_df = df_with_split.loc[df_with_split['split'] == 'test'] self._lengths['test_size'] = len(self.test_df) self._n_batches.append(self._lengths['test_size']", "self.optimizer = optimizer self.loss_fn = loss_fn self.scheduler = scheduler class", "self.with_test: raise NameError(\"No test dataset was provided\") return self._n_batches[2] @property", "= is_load self._lengths = {'train_size': len(self.train_df), 'val_size': len(self.val_df)} self._n_batches =", "Path, batch_size: int, with_test=True, is_load: bool=True) -> None: self.train_df =", "self._lengths['val_size'] // self._bs] if not self.is_load: print(\"Creating and saving vectorizer\")", "= [self._lengths['train_size'] // self._bs, self._lengths['val_size'] // self._bs] if not self.is_load:", "val_batches(self): return self._n_batches[1] @property def test_batches(self): if not self.with_test: raise", "optimizer, loss_fn, scheduler=None): self.model = model self.optimizer = optimizer self.loss_fn", "Path from torch.utils.data import DataLoader class ModelContainer(object): def __init__(self, model,", "'val'] self._bs = batch_size self.with_test = with_test self.is_load = is_load", "// self._bs] if not self.is_load: print(\"Creating and saving vectorizer\") train_ds", "not self.with_test: raise NameError(\"No test dataset was provided\") return self._n_batches[2]", "from pathlib import Path from torch.utils.data import DataLoader class ModelContainer(object):", "= loss_fn self.scheduler = scheduler class DataContainer(object): def __init__(self, df_with_split:", "= {'train_size': len(self.train_df), 'val_size': len(self.val_df)} self._n_batches = [self._lengths['train_size'] // self._bs,", "pd from pathlib import Path from torch.utils.data import DataLoader class", "with_test self.is_load = is_load self._lengths = {'train_size': len(self.train_df), 'val_size': len(self.val_df)}", "self.nationality_vocab = self.vectorizer.nationality_vocab self.train_dl = DataLoader(self.train_ds, self._bs, shuffle=True, drop_last=True) self.val_ds", "= DataLoader(self.test_ds, self._bs, shuffle=True, drop_last=True) def get_loaders(self): return self.train_dl, self.val_dl,", "= dataset_class.load_data_and_vectorizer(self.test_df, self.vectorizer) self.test_dl = DataLoader(self.test_ds, self._bs, shuffle=True, drop_last=True) def", "raise NameError(\"No test dataset was provided\") return self._n_batches[2] @property def", "from torch.utils.data import DataLoader class ModelContainer(object): def __init__(self, model, optimizer,", "self._bs, shuffle=True, drop_last=True) if self.with_test: self.test_df = df_with_split.loc[df_with_split['split'] == 'test']", "return self._n_batches[1] @property def test_batches(self): if not self.with_test: raise NameError(\"No", "len(self.surname_vocab) @property def n_classes(self): return len(self.nationality_vocab) @property def sizes(self): return", "self.is_load = is_load self._lengths = {'train_size': len(self.train_df), 'val_size': len(self.val_df)} self._n_batches", "self._bs = batch_size self.with_test = with_test self.is_load = is_load self._lengths", "pandas as pd from pathlib import Path from torch.utils.data import", "[self._lengths['train_size'] // self._bs, self._lengths['val_size'] // self._bs] if not self.is_load: print(\"Creating", "self.test_dl = DataLoader(self.test_ds, self._bs, shuffle=True, drop_last=True) def get_loaders(self): return self.train_dl,", "pathlib import Path from torch.utils.data import DataLoader class ModelContainer(object): def", "train_batches(self): return self._n_batches[0] @property def val_batches(self): return self._n_batches[1] @property def", "pd.DataFrame, dataset_class, vectorizer_file: Path, batch_size: int, with_test=True, is_load: bool=True) ->", "// self._bs, self._lengths['val_size'] // self._bs] if not self.is_load: print(\"Creating and", "print(\"Creating and saving vectorizer\") train_ds = dataset_class.load_data_and_create_vectorizer(self.train_df) train_ds.save_vectorizer(vectorizer_file) self.train_ds =", "None: self.train_df = df_with_split.loc[df_with_split['split'] == 'train'] self.val_df = df_with_split.loc[df_with_split['split'] ==", "df_with_split: pd.DataFrame, dataset_class, vectorizer_file: Path, batch_size: int, with_test=True, is_load: bool=True)", "loss_fn, scheduler=None): self.model = model self.optimizer = optimizer self.loss_fn =", "self._lengths['test_size'] = len(self.test_df) self._n_batches.append(self._lengths['test_size'] // self._bs) self.test_ds = dataset_class.load_data_and_vectorizer(self.test_df, self.vectorizer)", "self.loss_fn = loss_fn self.scheduler = scheduler class DataContainer(object): def __init__(self,", "'val_size': len(self.val_df)} self._n_batches = [self._lengths['train_size'] // self._bs, self._lengths['val_size'] // self._bs]", "vectorizer_file) self.vectorizer = self.train_ds.vectorizer self.surname_vocab = self.vectorizer.surname_vocab self.nationality_vocab = self.vectorizer.nationality_vocab", "= len(self.test_df) self._n_batches.append(self._lengths['test_size'] // self._bs) self.test_ds = dataset_class.load_data_and_vectorizer(self.test_df, self.vectorizer) self.test_dl", "scheduler=None): self.model = model self.optimizer = optimizer self.loss_fn = loss_fn", "@property def test_batches(self): if not self.with_test: raise NameError(\"No test dataset", "= df_with_split.loc[df_with_split['split'] == 'train'] self.val_df = df_with_split.loc[df_with_split['split'] == 'val'] self._bs", "self._lengths = {'train_size': len(self.train_df), 'val_size': len(self.val_df)} self._n_batches = [self._lengths['train_size'] //", "dataset_class.load_data_and_create_vectorizer(self.train_df) train_ds.save_vectorizer(vectorizer_file) self.train_ds = dataset_class.load_data_and_vectorizer_from_file(self.train_df, vectorizer_file) self.vectorizer = self.train_ds.vectorizer self.surname_vocab", "self.train_dl = DataLoader(self.train_ds, self._bs, shuffle=True, drop_last=True) self.val_ds = dataset_class.load_data_and_vectorizer(self.val_df, self.vectorizer)", "class DataContainer(object): def __init__(self, df_with_split: pd.DataFrame, dataset_class, vectorizer_file: Path, batch_size:" ]
[]
[ "the messages to show. level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO') level_name_to_level =", "'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, 'NOTSET': logging.NOTSET,", "__future__ import print_function import logging import os def setup_logging(): #", "log level of the messages to show. level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL',", "'DEBUG': logging.DEBUG, 'NOTSET': logging.NOTSET, } level = level_name_to_level.get(level_name.upper(), logging.INFO) logging.basicConfig(", "python from __future__ import print_function import logging import os def", "import os def setup_logging(): # Set log level of the", "= { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO,", "'INFO') level_name_to_level = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING,", "'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG,", "messages to show. level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO') level_name_to_level = {", "os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO') level_name_to_level = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING':", "logging.INFO, 'DEBUG': logging.DEBUG, 'NOTSET': logging.NOTSET, } level = level_name_to_level.get(level_name.upper(), logging.INFO)", "'INFO': logging.INFO, 'DEBUG': logging.DEBUG, 'NOTSET': logging.NOTSET, } level = level_name_to_level.get(level_name.upper(),", "= os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO') level_name_to_level = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR,", "of the messages to show. level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO') level_name_to_level", "# Set log level of the messages to show. level_name", "import print_function import logging import os def setup_logging(): # Set", "setup_logging(): # Set log level of the messages to show.", "logging import os def setup_logging(): # Set log level of", "os def setup_logging(): # Set log level of the messages", "import logging import os def setup_logging(): # Set log level", "to show. level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO') level_name_to_level = { 'CRITICAL':", "#!/usr/bin/env python from __future__ import print_function import logging import os", "'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, 'NOTSET': logging.NOTSET, } level", "level_name_to_level = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO':", "from __future__ import print_function import logging import os def setup_logging():", "logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, 'NOTSET': logging.NOTSET, }", "{ 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG':", "} level = level_name_to_level.get(level_name.upper(), logging.INFO) logging.basicConfig( level=level, format=( '%(asctime)s [%(levelname)s][%(filename)s:%(lineno)d]", "logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, 'NOTSET':", "logging.NOTSET, } level = level_name_to_level.get(level_name.upper(), logging.INFO) logging.basicConfig( level=level, format=( '%(asctime)s", "level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO') level_name_to_level = { 'CRITICAL': logging.CRITICAL, 'ERROR':", "logging.DEBUG, 'NOTSET': logging.NOTSET, } level = level_name_to_level.get(level_name.upper(), logging.INFO) logging.basicConfig( level=level,", "logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, 'NOTSET': logging.NOTSET, } level =", "level of the messages to show. level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO')", "= level_name_to_level.get(level_name.upper(), logging.INFO) logging.basicConfig( level=level, format=( '%(asctime)s [%(levelname)s][%(filename)s:%(lineno)d] %(message)s' ))", "def setup_logging(): # Set log level of the messages to", "'NOTSET': logging.NOTSET, } level = level_name_to_level.get(level_name.upper(), logging.INFO) logging.basicConfig( level=level, format=(", "Set log level of the messages to show. level_name =", "show. level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO') level_name_to_level = { 'CRITICAL': logging.CRITICAL,", "print_function import logging import os def setup_logging(): # Set log", "level = level_name_to_level.get(level_name.upper(), logging.INFO) logging.basicConfig( level=level, format=( '%(asctime)s [%(levelname)s][%(filename)s:%(lineno)d] %(message)s'" ]
[ "1 for i in range(n): for j in range(m): if", "len(elemnts[0]) rotten = [] for i in range(n): for j", "for i in range(n): for j in range(m): if elemnts[i][j]", "- 1 and rotten[i][j] == 1: count.append((i, j)) elemnts[i][j] =", "return 0 n = len(elemnts) m = len(elemnts[0]) rotten =", "elemnts[i][j] = 2 return count while rotten: rotten = dfs(rotten)", "range(n): for j in range(m): if elemnts[i][j] == 2: rotten.append((i,", "== 2: rotten.append((i, j)) mins = 0 def dfs(rotten): count", "not elemnts or len(elemnts) == 0: return 0 n =", "def orangesRotting(elemnts): if not elemnts or len(elemnts) == 0: return", "not rotten: break mins += 1 for i in range(n):", "0: return 0 n = len(elemnts) m = len(elemnts[0]) rotten", "= dfs(rotten) if not rotten: break mins += 1 for", "< m - 1 and rotten[i][j] == 1: count.append((i, j))", "if i > 0 and rotten[i - 1][j] == 1:", "== 1: count.append((i, j - 1)) elemnts[i][j - 1] =", "[] for i in range(n): for j in range(m): if", "== 1: count.append((i, j)) elemnts[i][j] = 2 if j <", "+= 1 for i in range(n): for j in range(m):", "j in range(m): if elemnts[i][j] == 1: return -1 return", "and rotten[i][j - 1] == 1: count.append((i, j - 1))", "break mins += 1 for i in range(n): for j", "1: count.append((i, j)) elemnts[i][j] = 2 return count while rotten:", "0 and rotten[i - 1][j] == 1: count.append((i - 1,", "len(elemnts) == 0: return 0 n = len(elemnts) m =", "in range(m): if elemnts[i][j] == 1: return -1 return mins", "- 1] == 1: count.append((i, j - 1)) elemnts[i][j -", "count.append((i, j - 1)) elemnts[i][j - 1] = 2 if", "in rotten: if i > 0 and rotten[i - 1][j]", "0 def dfs(rotten): count = [] for i, j in", "if not elemnts or len(elemnts) == 0: return 0 n", "> 0 and rotten[i - 1][j] == 1: count.append((i -", "j in range(m): if elemnts[i][j] == 2: rotten.append((i, j)) mins", "for j in range(m): if elemnts[i][j] == 1: return -1", "in range(n): for j in range(m): if elemnts[i][j] == 1:", "j < m - 1 and rotten[i][j] == 1: count.append((i,", "rotten: rotten = dfs(rotten) if not rotten: break mins +=", "m - 1 and rotten[i][j] == 1: count.append((i, j)) elemnts[i][j]", "rotten: break mins += 1 for i in range(n): for", "1: count.append((i, j - 1)) elemnts[i][j - 1] = 2", "range(m): if elemnts[i][j] == 2: rotten.append((i, j)) mins = 0", "rotten[i][j] == 1: count.append((i, j)) elemnts[i][j] = 2 return count", "count.append((i - 1, j)) elemnts[i - 1][j] = 2 if", "while rotten: rotten = dfs(rotten) if not rotten: break mins", "- 1][j] == 1: count.append((i - 1, j)) elemnts[i -", "2 if j > 0 and rotten[i][j - 1] ==", "and rotten[i][j] == 1: count.append((i, j)) elemnts[i][j] = 2 if", "- 1][j] = 2 if j > 0 and rotten[i][j", "orangesRotting(elemnts): if not elemnts or len(elemnts) == 0: return 0", "and rotten[i - 1][j] == 1: count.append((i - 1, j))", "= [] for i in range(n): for j in range(m):", "- 1, j)) elemnts[i - 1][j] = 2 if j", "elemnts or len(elemnts) == 0: return 0 n = len(elemnts)", "= [] for i, j in rotten: if i >", "1] = 2 if i < n - 1 and", "count while rotten: rotten = dfs(rotten) if not rotten: break", "= len(elemnts) m = len(elemnts[0]) rotten = [] for i", "< n - 1 and rotten[i][j] == 1: count.append((i, j))", "rotten = dfs(rotten) if not rotten: break mins += 1", "<reponame>Web-Dev-Collaborative/DS-ALGO-OFFICIAL<gh_stars>10-100 def orangesRotting(elemnts): if not elemnts or len(elemnts) == 0:", "len(elemnts) m = len(elemnts[0]) rotten = [] for i in", "mins += 1 for i in range(n): for j in", "i < n - 1 and rotten[i][j] == 1: count.append((i,", "= 2 if i < n - 1 and rotten[i][j]", "dfs(rotten) if not rotten: break mins += 1 for i", "mins = 0 def dfs(rotten): count = [] for i,", "= 0 def dfs(rotten): count = [] for i, j", "rotten = [] for i in range(n): for j in", "rotten[i][j - 1] == 1: count.append((i, j - 1)) elemnts[i][j", "if j < m - 1 and rotten[i][j] == 1:", "dfs(rotten): count = [] for i, j in rotten: if", "1 and rotten[i][j] == 1: count.append((i, j)) elemnts[i][j] = 2", "j)) mins = 0 def dfs(rotten): count = [] for", "in range(m): if elemnts[i][j] == 2: rotten.append((i, j)) mins =", "elemnts[i][j] == 2: rotten.append((i, j)) mins = 0 def dfs(rotten):", "1][j] = 2 if j > 0 and rotten[i][j -", "2 if i < n - 1 and rotten[i][j] ==", "= 2 return count while rotten: rotten = dfs(rotten) if", "> 0 and rotten[i][j - 1] == 1: count.append((i, j", "return count while rotten: rotten = dfs(rotten) if not rotten:", "j)) elemnts[i - 1][j] = 2 if j > 0", "== 1: count.append((i, j)) elemnts[i][j] = 2 return count while", "i in range(n): for j in range(m): if elemnts[i][j] ==", "for j in range(m): if elemnts[i][j] == 2: rotten.append((i, j))", "rotten[i - 1][j] == 1: count.append((i - 1, j)) elemnts[i", "elemnts[i - 1][j] = 2 if j > 0 and", "== 1: count.append((i - 1, j)) elemnts[i - 1][j] =", "rotten[i][j] == 1: count.append((i, j)) elemnts[i][j] = 2 if j", "n - 1 and rotten[i][j] == 1: count.append((i, j)) elemnts[i][j]", "1: count.append((i - 1, j)) elemnts[i - 1][j] = 2", "1, j)) elemnts[i - 1][j] = 2 if j >", "i > 0 and rotten[i - 1][j] == 1: count.append((i", "or len(elemnts) == 0: return 0 n = len(elemnts) m", "j - 1)) elemnts[i][j - 1] = 2 if i", "n = len(elemnts) m = len(elemnts[0]) rotten = [] for", "rotten.append((i, j)) mins = 0 def dfs(rotten): count = []", "2 if j < m - 1 and rotten[i][j] ==", "== 0: return 0 n = len(elemnts) m = len(elemnts[0])", "j in rotten: if i > 0 and rotten[i -", "2: rotten.append((i, j)) mins = 0 def dfs(rotten): count =", "count = [] for i, j in rotten: if i", "= len(elemnts[0]) rotten = [] for i in range(n): for", "range(n): for j in range(m): if elemnts[i][j] == 1: return", "in range(n): for j in range(m): if elemnts[i][j] == 2:", "j > 0 and rotten[i][j - 1] == 1: count.append((i,", "for i, j in rotten: if i > 0 and", "if i < n - 1 and rotten[i][j] == 1:", "- 1)) elemnts[i][j - 1] = 2 if i <", "def dfs(rotten): count = [] for i, j in rotten:", "- 1] = 2 if i < n - 1", "count.append((i, j)) elemnts[i][j] = 2 return count while rotten: rotten", "[] for i, j in rotten: if i > 0", "m = len(elemnts[0]) rotten = [] for i in range(n):", "2 return count while rotten: rotten = dfs(rotten) if not", "0 and rotten[i][j - 1] == 1: count.append((i, j -", "rotten: if i > 0 and rotten[i - 1][j] ==", "elemnts[i][j - 1] = 2 if i < n -", "1)) elemnts[i][j - 1] = 2 if i < n", "count.append((i, j)) elemnts[i][j] = 2 if j < m -", "= 2 if j < m - 1 and rotten[i][j]", "elemnts[i][j] = 2 if j < m - 1 and", "1: count.append((i, j)) elemnts[i][j] = 2 if j < m", "and rotten[i][j] == 1: count.append((i, j)) elemnts[i][j] = 2 return", "1][j] == 1: count.append((i - 1, j)) elemnts[i - 1][j]", "if j > 0 and rotten[i][j - 1] == 1:", "j)) elemnts[i][j] = 2 if j < m - 1", "if not rotten: break mins += 1 for i in", "j)) elemnts[i][j] = 2 return count while rotten: rotten =", "= 2 if j > 0 and rotten[i][j - 1]", "if elemnts[i][j] == 2: rotten.append((i, j)) mins = 0 def", "0 n = len(elemnts) m = len(elemnts[0]) rotten = []", "i, j in rotten: if i > 0 and rotten[i", "1] == 1: count.append((i, j - 1)) elemnts[i][j - 1]" ]
[ "2.0 (the \"License\"); # you may not use this file", "x = self.relu(self.conv3b(x)) x = self.pool3(x) x = self.relu(self.conv4a(x)) x", "isinstance(cell, nn.Conv3d): cell.weight.set_data(init.initializer( KaimingNormal(a=math.sqrt(5), mode='fan_out', nonlinearity='relu'), cell.weight.shape, cell.weight.dtype)) if cell.bias", "def __init_weight(self): default_recurisive_init(self) self.custom_init_weight() def construct(self, x): x = self.relu(self.conv1(x))", "kernel_size=(3, 3, 3), padding=(1, 1, 1, 1, 1, 1), pad_mode='pad',", "initializer as init from src.utils import default_recurisive_init, KaimingNormal class C3D(nn.Cell):", "definition. Args: num_classes (int): Class numbers. Default: 1000. Returns: Tensor,", "x = x.view(-1, 8192) x = self.relu(self.fc6(x)) x = self.dropout(x)", "pad_mode='pad', has_bias=True) self.pool2 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2),", "1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv3b = nn.Conv3d(in_channels=256,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "import default_recurisive_init, KaimingNormal class C3D(nn.Cell): \"\"\" C3D network definition. Args:", "7, 7) x = self.pad(x) x = x.view(-1, 512, 2,", "from src.utils import default_recurisive_init, KaimingNormal class C3D(nn.Cell): \"\"\" C3D network", "def custom_init_weight(self): \"\"\" Init the weight of Conv3d and Dense", "of Conv3d and Dense in the net. \"\"\" for _,", "self.pool2 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.conv3a", "is not None: cell.bias.set_data(init.initializer( 'zeros', cell.bias.shape, cell.bias.dtype)) elif isinstance(cell, nn.Dense):", "cell.bias.set_data(init.initializer( 'zeros', cell.bias.shape, cell.bias.dtype)) elif isinstance(cell, nn.Dense): cell.weight.set_data(init.initializer( init.Normal(0.01), cell.weight.shape,", "cell.weight.dtype)) if cell.bias is not None: cell.bias.set_data(init.initializer( 'zeros', cell.bias.shape, cell.bias.dtype))", "Class numbers. Default: 1000. Returns: Tensor, infer output tensor. Examples:", "has_bias=True) self.conv3b = nn.Conv3d(in_channels=256, out_channels=256, kernel_size=(3, 3, 3), padding=(1, 1,", "use this file except in compliance with the License. #", "2), pad_mode='same') self.conv4a = nn.Conv3d(in_channels=256, out_channels=512, kernel_size=(3, 3, 3), padding=(1,", "self.conv1 = nn.Conv3d(in_channels=3, out_channels=64, kernel_size=(3, 3, 3), padding=(1, 1, 1,", "2), pad_mode='same') self.conv3a = nn.Conv3d(in_channels=128, out_channels=256, kernel_size=(3, 3, 3), padding=(1,", "0)), mode=\"CONSTANT\") self.__init_weight() def __init_weight(self): default_recurisive_init(self) self.custom_init_weight() def construct(self, x):", "elif isinstance(cell, nn.Dense): cell.weight.set_data(init.initializer( init.Normal(0.01), cell.weight.shape, cell.weight.dtype)) if cell.bias is", "1, 1), pad_mode='pad', has_bias=True) self.conv3b = nn.Conv3d(in_channels=256, out_channels=256, kernel_size=(3, 3,", "padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv4b =", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "License. # You may obtain a copy of the License", "self.relu(self.conv4b(x)) x = self.pool4(x) x = self.relu(self.conv5a(x)) x = self.relu(self.conv5b(x))", "nn.Conv3d(in_channels=64, out_channels=128, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1, 1,", "self.relu(self.conv4a(x)) x = self.relu(self.conv4b(x)) x = self.pool4(x) x = self.relu(self.conv5a(x))", "under the License is distributed on an \"AS IS\" BASIS,", "Init the weight of Conv3d and Dense in the net.", "License for the specific language governing permissions and # limitations", "1, 1), pad_mode='pad', has_bias=True) self.pool1 = P.MaxPool3D(kernel_size=(1, 2, 2), strides=(1,", "2), strides=(2, 2, 2), pad_mode='same') self.conv3a = nn.Conv3d(in_channels=128, out_channels=256, kernel_size=(3,", "import mindspore.nn as nn import mindspore.ops as P from mindspore.common", "self.fc8(x) return logits def custom_init_weight(self): \"\"\" Init the weight of", "= x.view(-1, 512, 2, 8, 8) x = self.pool5(x) x", "padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv5b =", "self.pool1 = P.MaxPool3D(kernel_size=(1, 2, 2), strides=(1, 2, 2), pad_mode='same') self.conv2", "1), pad_mode='pad', has_bias=True) self.conv5b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3),", "padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool5 =", "= self.relu(self.conv2(x)) x = self.pool2(x) x = self.relu(self.conv3a(x)) x =", "init.Normal(0.01), cell.weight.shape, cell.weight.dtype)) if cell.bias is not None: cell.bias.set_data(init.initializer( 'zeros',", "out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1, 1, 1),", "construct(self, x): x = self.relu(self.conv1(x)) x = self.pool1(x) x =", "self.pool1(x) x = self.relu(self.conv2(x)) x = self.pool2(x) x = self.relu(self.conv3a(x))", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "= self.pool1(x) x = self.relu(self.conv2(x)) x = self.pool2(x) x =", "math import mindspore.nn as nn import mindspore.ops as P from", "1, 1), pad_mode='pad', has_bias=True) self.pool4 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2,", "x = self.relu(self.conv5a(x)) x = self.relu(self.conv5b(x)) x = x.view(-1, 512", "Huawei Technologies Co., Ltd # # Licensed under the Apache", "has_bias=True) self.pool4 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same')", "Returns: Tensor, infer output tensor. Examples: >>> C3D(num_classes=1000) \"\"\" def", "numbers. Default: 1000. Returns: Tensor, infer output tensor. Examples: >>>", "1, 1), pad_mode='pad', has_bias=True) self.conv5b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3,", "has_bias=True) self.conv4b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1,", "Dense in the net. \"\"\" for _, cell in self.cells_and_names():", "= self.relu(self.fc7(x)) x = self.dropout(x) logits = self.fc8(x) return logits", "padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool2 =", "2), pad_mode='same') self.conv5a = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3), padding=(1,", "Co., Ltd # # Licensed under the Apache License, Version", "2, 2), pad_mode='same') self.conv3a = nn.Conv3d(in_channels=128, out_channels=256, kernel_size=(3, 3, 3),", "= self.fc8(x) return logits def custom_init_weight(self): \"\"\" Init the weight", "1, 1, 1), pad_mode='pad', has_bias=True) self.pool5 = P.MaxPool3D(kernel_size=(2, 2, 2),", "x = self.pool4(x) x = self.relu(self.conv5a(x)) x = self.relu(self.conv5b(x)) x", "= P.MaxPool3D(kernel_size=(1, 2, 2), strides=(1, 2, 2), pad_mode='same') self.conv2 =", "padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool4 =", "import initializer as init from src.utils import default_recurisive_init, KaimingNormal class", "3), padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv3b", "1), pad_mode='pad', has_bias=True) self.pool2 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2,", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "x = self.pool1(x) x = self.relu(self.conv2(x)) x = self.pool2(x) x", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "__init_weight(self): default_recurisive_init(self) self.custom_init_weight() def construct(self, x): x = self.relu(self.conv1(x)) x", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "to in writing, software # distributed under the License is", "self.fc8 = nn.Dense(in_channels=4096, out_channels=num_classes, bias_init=init.Normal(0.02)) self.dropout = nn.Dropout(keep_prob=0.5) self.relu =", "# See the License for the specific language governing permissions", "1), pad_mode='pad', has_bias=True) self.conv4b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3),", "self.conv4a = nn.Conv3d(in_channels=256, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1, 1,", "language governing permissions and # limitations under the License. #", "or agreed to in writing, software # distributed under the", "nn.Dense(in_channels=8192, out_channels=4096) self.fc7 = nn.Dense(in_channels=4096, out_channels=4096) self.fc8 = nn.Dense(in_channels=4096, out_channels=num_classes,", "strides=(1, 2, 2), pad_mode='same') self.conv2 = nn.Conv3d(in_channels=64, out_channels=128, kernel_size=(3, 3,", "required by applicable law or agreed to in writing, software", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "mode=\"CONSTANT\") self.__init_weight() def __init_weight(self): default_recurisive_init(self) self.custom_init_weight() def construct(self, x): x", "with the License. # You may obtain a copy of", "self.fc6 = nn.Dense(in_channels=8192, out_channels=4096) self.fc7 = nn.Dense(in_channels=4096, out_channels=4096) self.fc8 =", "2), strides=(1, 2, 2), pad_mode='same') self.conv2 = nn.Conv3d(in_channels=64, out_channels=128, kernel_size=(3,", "P.MaxPool3D(kernel_size=(1, 2, 2), strides=(1, 2, 2), pad_mode='same') self.conv2 = nn.Conv3d(in_channels=64,", "x = x.view(-1, 512 * 2, 7, 7) x =", "pad_mode='pad', has_bias=True) self.pool3 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2),", "2, 2), pad_mode='same') self.conv2 = nn.Conv3d(in_channels=64, out_channels=128, kernel_size=(3, 3, 3),", "self.custom_init_weight() def construct(self, x): x = self.relu(self.conv1(x)) x = self.pool1(x)", "pad_mode='pad', has_bias=True) self.conv3b = nn.Conv3d(in_channels=256, out_channels=256, kernel_size=(3, 3, 3), padding=(1,", "pad_mode='same') self.conv3a = nn.Conv3d(in_channels=128, out_channels=256, kernel_size=(3, 3, 3), padding=(1, 1,", "pad_mode='pad', has_bias=True) self.pool1 = P.MaxPool3D(kernel_size=(1, 2, 2), strides=(1, 2, 2),", "compliance with the License. # You may obtain a copy", "============================================================================ import math import mindspore.nn as nn import mindspore.ops as", "agreed to in writing, software # distributed under the License", "1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool2 = P.MaxPool3D(kernel_size=(2, 2,", "= self.relu(self.conv5a(x)) x = self.relu(self.conv5b(x)) x = x.view(-1, 512 *", "distributed under the License is distributed on an \"AS IS\"", "x = self.dropout(x) logits = self.fc8(x) return logits def custom_init_weight(self):", "custom_init_weight(self): \"\"\" Init the weight of Conv3d and Dense in", "Tensor, infer output tensor. Examples: >>> C3D(num_classes=1000) \"\"\" def __init__(self,", "= self.pool4(x) x = self.relu(self.conv5a(x)) x = self.relu(self.conv5b(x)) x =", "cell.bias.shape, cell.bias.dtype)) elif isinstance(cell, nn.Dense): cell.weight.set_data(init.initializer( init.Normal(0.01), cell.weight.shape, cell.weight.dtype)) if", "1000. Returns: Tensor, infer output tensor. Examples: >>> C3D(num_classes=1000) \"\"\"", "mindspore.ops as P from mindspore.common import initializer as init from", "8192) x = self.relu(self.fc6(x)) x = self.dropout(x) x = self.relu(self.fc7(x))", "net. \"\"\" for _, cell in self.cells_and_names(): if isinstance(cell, nn.Conv3d):", "nn.Dense(in_channels=4096, out_channels=4096) self.fc8 = nn.Dense(in_channels=4096, out_channels=num_classes, bias_init=init.Normal(0.02)) self.dropout = nn.Dropout(keep_prob=0.5)", "express or implied. # See the License for the specific", "= self.relu(self.conv1(x)) x = self.pool1(x) x = self.relu(self.conv2(x)) x =", "except in compliance with the License. # You may obtain", "cell.weight.set_data(init.initializer( KaimingNormal(a=math.sqrt(5), mode='fan_out', nonlinearity='relu'), cell.weight.shape, cell.weight.dtype)) if cell.bias is not", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "3, 3), padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True)", "= nn.Conv3d(in_channels=3, out_channels=64, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1,", "x = self.relu(self.fc6(x)) x = self.dropout(x) x = self.relu(self.fc7(x)) x", "and Dense in the net. \"\"\" for _, cell in", "writing, software # distributed under the License is distributed on", "= self.relu(self.conv4a(x)) x = self.relu(self.conv4b(x)) x = self.pool4(x) x =", "you may not use this file except in compliance with", "logits = self.fc8(x) return logits def custom_init_weight(self): \"\"\" Init the", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool1 = P.MaxPool3D(kernel_size=(1, 2,", "def __init__(self, num_classes=1000): super(C3D, self).__init__() self.conv1 = nn.Conv3d(in_channels=3, out_channels=64, kernel_size=(3,", "x = self.dropout(x) x = self.relu(self.fc7(x)) x = self.dropout(x) logits", "if isinstance(cell, nn.Conv3d): cell.weight.set_data(init.initializer( KaimingNormal(a=math.sqrt(5), mode='fan_out', nonlinearity='relu'), cell.weight.shape, cell.weight.dtype)) if", "x = x.view(-1, 512, 2, 8, 8) x = self.pool5(x)", "self.relu(self.fc6(x)) x = self.dropout(x) x = self.relu(self.fc7(x)) x = self.dropout(x)", "permissions and # limitations under the License. # ============================================================================ import", "CONDITIONS OF ANY KIND, either express or implied. # See", "3), padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool3", "Ltd # # Licensed under the Apache License, Version 2.0", "logits def custom_init_weight(self): \"\"\" Init the weight of Conv3d and", "x.view(-1, 512 * 2, 7, 7) x = self.pad(x) x", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "2, 2), pad_mode='same') self.conv5a = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3),", "self.pad(x) x = x.view(-1, 512, 2, 8, 8) x =", "self.conv3a = nn.Conv3d(in_channels=128, out_channels=256, kernel_size=(3, 3, 3), padding=(1, 1, 1,", "the weight of Conv3d and Dense in the net. \"\"\"", "2021 Huawei Technologies Co., Ltd # # Licensed under the", "nn.Conv3d(in_channels=256, out_channels=256, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1, 1,", "self.relu(self.conv3b(x)) x = self.pool3(x) x = self.relu(self.conv4a(x)) x = self.relu(self.conv4b(x))", "cell.bias.dtype)) elif isinstance(cell, nn.Dense): cell.weight.set_data(init.initializer( init.Normal(0.01), cell.weight.shape, cell.weight.dtype)) if cell.bias", "OR CONDITIONS OF ANY KIND, either express or implied. #", "cell.weight.set_data(init.initializer( init.Normal(0.01), cell.weight.shape, cell.weight.dtype)) if cell.bias is not None: cell.bias.set_data(init.initializer(", "the License is distributed on an \"AS IS\" BASIS, #", "(1, 0), (1, 0)), mode=\"CONSTANT\") self.__init_weight() def __init_weight(self): default_recurisive_init(self) self.custom_init_weight()", "2, 7, 7) x = self.pad(x) x = x.view(-1, 512,", "in self.cells_and_names(): if isinstance(cell, nn.Conv3d): cell.weight.set_data(init.initializer( KaimingNormal(a=math.sqrt(5), mode='fan_out', nonlinearity='relu'), cell.weight.shape,", "2), strides=(2, 2, 2), pad_mode='same') self.conv4a = nn.Conv3d(in_channels=256, out_channels=512, kernel_size=(3,", "pad_mode='pad', has_bias=True) self.pool5 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2),", "C3D(num_classes=1000) \"\"\" def __init__(self, num_classes=1000): super(C3D, self).__init__() self.conv1 = nn.Conv3d(in_channels=3,", "pad_mode='same') self.conv4a = nn.Conv3d(in_channels=256, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1,", "init from src.utils import default_recurisive_init, KaimingNormal class C3D(nn.Cell): \"\"\" C3D", "self.conv3b = nn.Conv3d(in_channels=256, out_channels=256, kernel_size=(3, 3, 3), padding=(1, 1, 1,", "nn.Dropout(keep_prob=0.5) self.relu = nn.ReLU() self.pad = nn.Pad(paddings=((0, 0), (0, 0),", "and # limitations under the License. # ============================================================================ import math", "= nn.Conv3d(in_channels=128, out_channels=256, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1,", "1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv4b = nn.Conv3d(in_channels=512,", "the License. # ============================================================================ import math import mindspore.nn as nn", "law or agreed to in writing, software # distributed under", "if cell.bias is not None: cell.bias.set_data(init.initializer( 'zeros', cell.bias.shape, cell.bias.dtype)) elif", "from mindspore.common import initializer as init from src.utils import default_recurisive_init,", "has_bias=True) self.conv5b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1,", "nn import mindspore.ops as P from mindspore.common import initializer as", "self.pool3 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.conv4a", "512, 2, 8, 8) x = self.pool5(x) x = x.view(-1,", "P from mindspore.common import initializer as init from src.utils import", "2, 2), strides=(2, 2, 2), pad_mode='same') self.conv4a = nn.Conv3d(in_channels=256, out_channels=512,", "0), (0, 0), (1, 0), (1, 0)), mode=\"CONSTANT\") self.__init_weight() def", "# ============================================================================ import math import mindspore.nn as nn import mindspore.ops", "self.conv5b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1, 1,", "1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool4 = P.MaxPool3D(kernel_size=(2,", "1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool3 = P.MaxPool3D(kernel_size=(2, 2,", "self.dropout = nn.Dropout(keep_prob=0.5) self.relu = nn.ReLU() self.pad = nn.Pad(paddings=((0, 0),", "padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool1 =", "3), padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool2", "KaimingNormal(a=math.sqrt(5), mode='fan_out', nonlinearity='relu'), cell.weight.shape, cell.weight.dtype)) if cell.bias is not None:", "may obtain a copy of the License at # #", "x.view(-1, 512, 2, 8, 8) x = self.pool5(x) x =", "1, 1, 1), pad_mode='pad', has_bias=True) self.conv3b = nn.Conv3d(in_channels=256, out_channels=256, kernel_size=(3,", "1), pad_mode='pad', has_bias=True) self.pool1 = P.MaxPool3D(kernel_size=(1, 2, 2), strides=(1, 2,", "network definition. Args: num_classes (int): Class numbers. Default: 1000. Returns:", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "= nn.Dense(in_channels=4096, out_channels=4096) self.fc8 = nn.Dense(in_channels=4096, out_channels=num_classes, bias_init=init.Normal(0.02)) self.dropout =", "P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.fc6 = nn.Dense(in_channels=8192,", "8, 8) x = self.pool5(x) x = x.view(-1, 8192) x", "may not use this file except in compliance with the", "P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.conv5a = nn.Conv3d(in_channels=512,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "this file except in compliance with the License. # You", "2, 2), pad_mode='same') self.conv4a = nn.Conv3d(in_channels=256, out_channels=512, kernel_size=(3, 3, 3),", "= nn.Conv3d(in_channels=64, out_channels=128, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1,", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "# # Licensed under the Apache License, Version 2.0 (the", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "3), padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv4b", "padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv3b =", "out_channels=256, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1, 1, 1),", "1), pad_mode='pad', has_bias=True) self.pool4 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "has_bias=True) self.pool5 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same')", "0), (1, 0), (1, 0)), mode=\"CONSTANT\") self.__init_weight() def __init_weight(self): default_recurisive_init(self)", "out_channels=128, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1, 1, 1),", "<gh_stars>10-100 # Copyright 2021 Huawei Technologies Co., Ltd # #", "1), pad_mode='pad', has_bias=True) self.conv3b = nn.Conv3d(in_channels=256, out_channels=256, kernel_size=(3, 3, 3),", "self).__init__() self.conv1 = nn.Conv3d(in_channels=3, out_channels=64, kernel_size=(3, 3, 3), padding=(1, 1,", "x = self.pool5(x) x = x.view(-1, 8192) x = self.relu(self.fc6(x))", "x.view(-1, 8192) x = self.relu(self.fc6(x)) x = self.dropout(x) x =", "self.fc7 = nn.Dense(in_channels=4096, out_channels=4096) self.fc8 = nn.Dense(in_channels=4096, out_channels=num_classes, bias_init=init.Normal(0.02)) self.dropout", "2, 2), strides=(2, 2, 2), pad_mode='same') self.conv5a = nn.Conv3d(in_channels=512, out_channels=512,", "1, 1, 1), pad_mode='pad', has_bias=True) self.pool3 = P.MaxPool3D(kernel_size=(2, 2, 2),", "mindspore.common import initializer as init from src.utils import default_recurisive_init, KaimingNormal", "self.pool4 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.conv5a", "\"\"\" for _, cell in self.cells_and_names(): if isinstance(cell, nn.Conv3d): cell.weight.set_data(init.initializer(", "self.pool5 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.fc6", "= self.relu(self.fc6(x)) x = self.dropout(x) x = self.relu(self.fc7(x)) x =", "1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv5b = nn.Conv3d(in_channels=512, out_channels=512,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "self.conv2 = nn.Conv3d(in_channels=64, out_channels=128, kernel_size=(3, 3, 3), padding=(1, 1, 1,", "1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool5 = P.MaxPool3D(kernel_size=(2,", "or implied. # See the License for the specific language", ">>> C3D(num_classes=1000) \"\"\" def __init__(self, num_classes=1000): super(C3D, self).__init__() self.conv1 =", "strides=(2, 2, 2), pad_mode='same') self.conv3a = nn.Conv3d(in_channels=128, out_channels=256, kernel_size=(3, 3,", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "= nn.Dense(in_channels=8192, out_channels=4096) self.fc7 = nn.Dense(in_channels=4096, out_channels=4096) self.fc8 = nn.Dense(in_channels=4096,", "1, 1, 1), pad_mode='pad', has_bias=True) self.conv4b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3,", "self.dropout(x) x = self.relu(self.fc7(x)) x = self.dropout(x) logits = self.fc8(x)", "nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1, 1,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "under the License. # ============================================================================ import math import mindspore.nn as", "1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv5b = nn.Conv3d(in_channels=512,", "super(C3D, self).__init__() self.conv1 = nn.Conv3d(in_channels=3, out_channels=64, kernel_size=(3, 3, 3), padding=(1,", "1), pad_mode='pad', has_bias=True) self.pool3 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2,", "cell.bias is not None: cell.bias.set_data(init.initializer( 'zeros', cell.bias.shape, cell.bias.dtype)) elif isinstance(cell,", "pad_mode='pad', has_bias=True) self.conv4b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3), padding=(1,", "Conv3d and Dense in the net. \"\"\" for _, cell", "self.cells_and_names(): if isinstance(cell, nn.Conv3d): cell.weight.set_data(init.initializer( KaimingNormal(a=math.sqrt(5), mode='fan_out', nonlinearity='relu'), cell.weight.shape, cell.weight.dtype))", "x = self.relu(self.conv3a(x)) x = self.relu(self.conv3b(x)) x = self.pool3(x) x", "(the \"License\"); # you may not use this file except", "3), padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv5b", "self.relu(self.conv1(x)) x = self.pool1(x) x = self.relu(self.conv2(x)) x = self.pool2(x)", "# you may not use this file except in compliance", "(1, 0)), mode=\"CONSTANT\") self.__init_weight() def __init_weight(self): default_recurisive_init(self) self.custom_init_weight() def construct(self,", "2), pad_mode='same') self.fc6 = nn.Dense(in_channels=8192, out_channels=4096) self.fc7 = nn.Dense(in_channels=4096, out_channels=4096)", "* 2, 7, 7) x = self.pad(x) x = x.view(-1,", "x = self.relu(self.conv4a(x)) x = self.relu(self.conv4b(x)) x = self.pool4(x) x", "= self.pool3(x) x = self.relu(self.conv4a(x)) x = self.relu(self.conv4b(x)) x =", "1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool1 = P.MaxPool3D(kernel_size=(1,", "(int): Class numbers. Default: 1000. Returns: Tensor, infer output tensor.", "nn.Conv3d(in_channels=3, out_channels=64, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1, 1,", "= self.dropout(x) logits = self.fc8(x) return logits def custom_init_weight(self): \"\"\"", "nn.Conv3d): cell.weight.set_data(init.initializer( KaimingNormal(a=math.sqrt(5), mode='fan_out', nonlinearity='relu'), cell.weight.shape, cell.weight.dtype)) if cell.bias is", "C3D network definition. Args: num_classes (int): Class numbers. Default: 1000.", "self.relu(self.conv5a(x)) x = self.relu(self.conv5b(x)) x = x.view(-1, 512 * 2,", "self.relu(self.conv3a(x)) x = self.relu(self.conv3b(x)) x = self.pool3(x) x = self.relu(self.conv4a(x))", "# # Unless required by applicable law or agreed to", "output tensor. Examples: >>> C3D(num_classes=1000) \"\"\" def __init__(self, num_classes=1000): super(C3D,", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "src.utils import default_recurisive_init, KaimingNormal class C3D(nn.Cell): \"\"\" C3D network definition.", "Version 2.0 (the \"License\"); # you may not use this", "self.pool2(x) x = self.relu(self.conv3a(x)) x = self.relu(self.conv3b(x)) x = self.pool3(x)", "class C3D(nn.Cell): \"\"\" C3D network definition. Args: num_classes (int): Class", "pad_mode='same') self.conv2 = nn.Conv3d(in_channels=64, out_channels=128, kernel_size=(3, 3, 3), padding=(1, 1,", "2), strides=(2, 2, 2), pad_mode='same') self.fc6 = nn.Dense(in_channels=8192, out_channels=4096) self.fc7", "= nn.Conv3d(in_channels=256, out_channels=256, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1,", "License. # ============================================================================ import math import mindspore.nn as nn import", "1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool2 = P.MaxPool3D(kernel_size=(2,", "default_recurisive_init, KaimingNormal class C3D(nn.Cell): \"\"\" C3D network definition. Args: num_classes", "pad_mode='same') self.fc6 = nn.Dense(in_channels=8192, out_channels=4096) self.fc7 = nn.Dense(in_channels=4096, out_channels=4096) self.fc8", "= P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.conv5a =", "= P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.conv4a =", "self.dropout(x) logits = self.fc8(x) return logits def custom_init_weight(self): \"\"\" Init", "implied. # See the License for the specific language governing", "KaimingNormal class C3D(nn.Cell): \"\"\" C3D network definition. Args: num_classes (int):", "under the Apache License, Version 2.0 (the \"License\"); # you", "bias_init=init.Normal(0.02)) self.dropout = nn.Dropout(keep_prob=0.5) self.relu = nn.ReLU() self.pad = nn.Pad(paddings=((0,", "as P from mindspore.common import initializer as init from src.utils", "2, 2), strides=(2, 2, 2), pad_mode='same') self.fc6 = nn.Dense(in_channels=8192, out_channels=4096)", "nn.ReLU() self.pad = nn.Pad(paddings=((0, 0), (0, 0), (1, 0), (1,", "x = self.pad(x) x = x.view(-1, 512, 2, 8, 8)", "1), pad_mode='pad', has_bias=True) self.pool5 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2,", "P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.conv3a = nn.Conv3d(in_channels=128,", "self.relu = nn.ReLU() self.pad = nn.Pad(paddings=((0, 0), (0, 0), (1,", "x): x = self.relu(self.conv1(x)) x = self.pool1(x) x = self.relu(self.conv2(x))", "1, 1, 1), pad_mode='pad', has_bias=True) self.pool1 = P.MaxPool3D(kernel_size=(1, 2, 2),", "pad_mode='same') self.conv5a = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1,", "by applicable law or agreed to in writing, software #", "x = self.relu(self.conv4b(x)) x = self.pool4(x) x = self.relu(self.conv5a(x)) x", "= P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.conv3a =", "__init__(self, num_classes=1000): super(C3D, self).__init__() self.conv1 = nn.Conv3d(in_channels=3, out_channels=64, kernel_size=(3, 3,", "\"\"\" def __init__(self, num_classes=1000): super(C3D, self).__init__() self.conv1 = nn.Conv3d(in_channels=3, out_channels=64,", "strides=(2, 2, 2), pad_mode='same') self.conv5a = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3,", "= self.relu(self.conv4b(x)) x = self.pool4(x) x = self.relu(self.conv5a(x)) x =", "weight of Conv3d and Dense in the net. \"\"\" for", "x = self.relu(self.conv2(x)) x = self.pool2(x) x = self.relu(self.conv3a(x)) x", "2, 2), pad_mode='same') self.fc6 = nn.Dense(in_channels=8192, out_channels=4096) self.fc7 = nn.Dense(in_channels=4096,", "num_classes (int): Class numbers. Default: 1000. Returns: Tensor, infer output", "Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under", "3), padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool1", "= self.pad(x) x = x.view(-1, 512, 2, 8, 8) x", "2, 2), strides=(2, 2, 2), pad_mode='same') self.conv3a = nn.Conv3d(in_channels=128, out_channels=256,", "self.relu(self.conv2(x)) x = self.pool2(x) x = self.relu(self.conv3a(x)) x = self.relu(self.conv3b(x))", "1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool4 = P.MaxPool3D(kernel_size=(2, 2,", "self.__init_weight() def __init_weight(self): default_recurisive_init(self) self.custom_init_weight() def construct(self, x): x =", "return logits def custom_init_weight(self): \"\"\" Init the weight of Conv3d", "= nn.Conv3d(in_channels=256, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1,", "pad_mode='pad', has_bias=True) self.pool4 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2),", "Default: 1000. Returns: Tensor, infer output tensor. Examples: >>> C3D(num_classes=1000)", "self.relu(self.fc7(x)) x = self.dropout(x) logits = self.fc8(x) return logits def", "= self.relu(self.conv3a(x)) x = self.relu(self.conv3b(x)) x = self.pool3(x) x =", "out_channels=4096) self.fc8 = nn.Dense(in_channels=4096, out_channels=num_classes, bias_init=init.Normal(0.02)) self.dropout = nn.Dropout(keep_prob=0.5) self.relu", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "= nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1,", "Unless required by applicable law or agreed to in writing,", "has_bias=True) self.pool3 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same')", "out_channels=64, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1, 1, 1),", "_, cell in self.cells_and_names(): if isinstance(cell, nn.Conv3d): cell.weight.set_data(init.initializer( KaimingNormal(a=math.sqrt(5), mode='fan_out',", "self.relu(self.conv5b(x)) x = x.view(-1, 512 * 2, 7, 7) x", "num_classes=1000): super(C3D, self).__init__() self.conv1 = nn.Conv3d(in_channels=3, out_channels=64, kernel_size=(3, 3, 3),", "cell in self.cells_and_names(): if isinstance(cell, nn.Conv3d): cell.weight.set_data(init.initializer( KaimingNormal(a=math.sqrt(5), mode='fan_out', nonlinearity='relu'),", "= self.relu(self.conv3b(x)) x = self.pool3(x) x = self.relu(self.conv4a(x)) x =", "Technologies Co., Ltd # # Licensed under the Apache License,", "the specific language governing permissions and # limitations under the", "0), (1, 0)), mode=\"CONSTANT\") self.__init_weight() def __init_weight(self): default_recurisive_init(self) self.custom_init_weight() def", "mode='fan_out', nonlinearity='relu'), cell.weight.shape, cell.weight.dtype)) if cell.bias is not None: cell.bias.set_data(init.initializer(", "applicable law or agreed to in writing, software # distributed", "def construct(self, x): x = self.relu(self.conv1(x)) x = self.pool1(x) x", "1, 1, 1), pad_mode='pad', has_bias=True) self.conv5b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3,", "infer output tensor. Examples: >>> C3D(num_classes=1000) \"\"\" def __init__(self, num_classes=1000):", "7) x = self.pad(x) x = x.view(-1, 512, 2, 8,", "2), pad_mode='same') self.conv2 = nn.Conv3d(in_channels=64, out_channels=128, kernel_size=(3, 3, 3), padding=(1,", "in writing, software # distributed under the License is distributed", "has_bias=True) self.pool2 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same')", "3), padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool4", "self.pad = nn.Pad(paddings=((0, 0), (0, 0), (1, 0), (1, 0)),", "# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed", "self.conv5a = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1, 1,", "the net. \"\"\" for _, cell in self.cells_and_names(): if isinstance(cell,", "out_channels=num_classes, bias_init=init.Normal(0.02)) self.dropout = nn.Dropout(keep_prob=0.5) self.relu = nn.ReLU() self.pad =", "= nn.ReLU() self.pad = nn.Pad(paddings=((0, 0), (0, 0), (1, 0),", "None: cell.bias.set_data(init.initializer( 'zeros', cell.bias.shape, cell.bias.dtype)) elif isinstance(cell, nn.Dense): cell.weight.set_data(init.initializer( init.Normal(0.01),", "2, 8, 8) x = self.pool5(x) x = x.view(-1, 8192)", "Args: num_classes (int): Class numbers. Default: 1000. Returns: Tensor, infer", "= self.pool2(x) x = self.relu(self.conv3a(x)) x = self.relu(self.conv3b(x)) x =", "= nn.Pad(paddings=((0, 0), (0, 0), (1, 0), (1, 0)), mode=\"CONSTANT\")", "= x.view(-1, 8192) x = self.relu(self.fc6(x)) x = self.dropout(x) x", "= self.dropout(x) x = self.relu(self.fc7(x)) x = self.dropout(x) logits =", "mindspore.nn as nn import mindspore.ops as P from mindspore.common import", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "Examples: >>> C3D(num_classes=1000) \"\"\" def __init__(self, num_classes=1000): super(C3D, self).__init__() self.conv1", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "x = self.relu(self.conv1(x)) x = self.pool1(x) x = self.relu(self.conv2(x)) x", "cell.weight.shape, cell.weight.dtype)) if cell.bias is not None: cell.bias.set_data(init.initializer( 'zeros', cell.bias.shape,", "self.pool5(x) x = x.view(-1, 8192) x = self.relu(self.fc6(x)) x =", "padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool3 =", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "nonlinearity='relu'), cell.weight.shape, cell.weight.dtype)) if cell.bias is not None: cell.bias.set_data(init.initializer( 'zeros',", "1, 1, 1), pad_mode='pad', has_bias=True) self.pool4 = P.MaxPool3D(kernel_size=(2, 2, 2),", "1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv4b = nn.Conv3d(in_channels=512, out_channels=512,", "# limitations under the License. # ============================================================================ import math import", "x = self.relu(self.fc7(x)) x = self.dropout(x) logits = self.fc8(x) return", "'zeros', cell.bias.shape, cell.bias.dtype)) elif isinstance(cell, nn.Dense): cell.weight.set_data(init.initializer( init.Normal(0.01), cell.weight.shape, cell.weight.dtype))", "= nn.Dense(in_channels=4096, out_channels=num_classes, bias_init=init.Normal(0.02)) self.dropout = nn.Dropout(keep_prob=0.5) self.relu = nn.ReLU()", "the License for the specific language governing permissions and #", "self.pool3(x) x = self.relu(self.conv4a(x)) x = self.relu(self.conv4b(x)) x = self.pool4(x)", "Apache License, Version 2.0 (the \"License\"); # you may not", "either express or implied. # See the License for the", "has_bias=True) self.pool1 = P.MaxPool3D(kernel_size=(1, 2, 2), strides=(1, 2, 2), pad_mode='same')", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "nn.Pad(paddings=((0, 0), (0, 0), (1, 0), (1, 0)), mode=\"CONSTANT\") self.__init_weight()", "= x.view(-1, 512 * 2, 7, 7) x = self.pad(x)", "for _, cell in self.cells_and_names(): if isinstance(cell, nn.Conv3d): cell.weight.set_data(init.initializer( KaimingNormal(a=math.sqrt(5),", "self.pool4(x) x = self.relu(self.conv5a(x)) x = self.relu(self.conv5b(x)) x = x.view(-1,", "P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.conv4a = nn.Conv3d(in_channels=256,", "1, 1), pad_mode='pad', has_bias=True) self.pool2 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2,", "1, 1, 1, 1), pad_mode='pad', has_bias=True) self.conv3b = nn.Conv3d(in_channels=256, out_channels=256,", "= self.relu(self.conv5b(x)) x = x.view(-1, 512 * 2, 7, 7)", "1, 1, 1), pad_mode='pad', has_bias=True) self.pool2 = P.MaxPool3D(kernel_size=(2, 2, 2),", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "nn.Conv3d(in_channels=256, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1, 1,", "pad_mode='pad', has_bias=True) self.conv5b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3), padding=(1,", "nn.Dense(in_channels=4096, out_channels=num_classes, bias_init=init.Normal(0.02)) self.dropout = nn.Dropout(keep_prob=0.5) self.relu = nn.ReLU() self.pad", "default_recurisive_init(self) self.custom_init_weight() def construct(self, x): x = self.relu(self.conv1(x)) x =", "as init from src.utils import default_recurisive_init, KaimingNormal class C3D(nn.Cell): \"\"\"", "3), padding=(1, 1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool5", "limitations under the License. # ============================================================================ import math import mindspore.nn", "import mindspore.ops as P from mindspore.common import initializer as init", "8) x = self.pool5(x) x = x.view(-1, 8192) x =", "1, 1), pad_mode='pad', has_bias=True) self.pool3 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2,", "1, 1), pad_mode='pad', has_bias=True) self.conv4b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3,", "\"\"\" C3D network definition. Args: num_classes (int): Class numbers. Default:", "(0, 0), (1, 0), (1, 0)), mode=\"CONSTANT\") self.__init_weight() def __init_weight(self):", "not None: cell.bias.set_data(init.initializer( 'zeros', cell.bias.shape, cell.bias.dtype)) elif isinstance(cell, nn.Dense): cell.weight.set_data(init.initializer(", "nn.Conv3d(in_channels=128, out_channels=256, kernel_size=(3, 3, 3), padding=(1, 1, 1, 1, 1,", "isinstance(cell, nn.Dense): cell.weight.set_data(init.initializer( init.Normal(0.01), cell.weight.shape, cell.weight.dtype)) if cell.bias is not", "\"License\"); # you may not use this file except in", "strides=(2, 2, 2), pad_mode='same') self.conv4a = nn.Conv3d(in_channels=256, out_channels=512, kernel_size=(3, 3,", "= P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2, 2, 2), pad_mode='same') self.fc6 =", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "strides=(2, 2, 2), pad_mode='same') self.fc6 = nn.Dense(in_channels=8192, out_channels=4096) self.fc7 =", "C3D(nn.Cell): \"\"\" C3D network definition. Args: num_classes (int): Class numbers.", "x = self.pool2(x) x = self.relu(self.conv3a(x)) x = self.relu(self.conv3b(x)) x", "# distributed under the License is distributed on an \"AS", "1, 1), pad_mode='pad', has_bias=True) self.pool5 = P.MaxPool3D(kernel_size=(2, 2, 2), strides=(2,", "# Unless required by applicable law or agreed to in", "as nn import mindspore.ops as P from mindspore.common import initializer", "1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool5 = P.MaxPool3D(kernel_size=(2, 2,", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "out_channels=4096) self.fc7 = nn.Dense(in_channels=4096, out_channels=4096) self.fc8 = nn.Dense(in_channels=4096, out_channels=num_classes, bias_init=init.Normal(0.02))", "import math import mindspore.nn as nn import mindspore.ops as P", "nn.Dense): cell.weight.set_data(init.initializer( init.Normal(0.01), cell.weight.shape, cell.weight.dtype)) if cell.bias is not None:", "= nn.Dropout(keep_prob=0.5) self.relu = nn.ReLU() self.pad = nn.Pad(paddings=((0, 0), (0,", "2, 2), strides=(1, 2, 2), pad_mode='same') self.conv2 = nn.Conv3d(in_channels=64, out_channels=128,", "You may obtain a copy of the License at #", "x = self.pool3(x) x = self.relu(self.conv4a(x)) x = self.relu(self.conv4b(x)) x", "x = self.relu(self.conv5b(x)) x = x.view(-1, 512 * 2, 7,", "2), strides=(2, 2, 2), pad_mode='same') self.conv5a = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3,", "self.conv4b = nn.Conv3d(in_channels=512, out_channels=512, kernel_size=(3, 3, 3), padding=(1, 1, 1,", "the Apache License, Version 2.0 (the \"License\"); # you may", "= self.pool5(x) x = x.view(-1, 8192) x = self.relu(self.fc6(x)) x", "1, 1, 1, 1, 1), pad_mode='pad', has_bias=True) self.pool3 = P.MaxPool3D(kernel_size=(2,", "in the net. \"\"\" for _, cell in self.cells_and_names(): if", "tensor. Examples: >>> C3D(num_classes=1000) \"\"\" def __init__(self, num_classes=1000): super(C3D, self).__init__()", "governing permissions and # limitations under the License. # ============================================================================", "\"\"\" Init the weight of Conv3d and Dense in the", "512 * 2, 7, 7) x = self.pad(x) x =" ]
[ "given point. Return a tuple: farthest_point, index_of_farthest_point. ''' absolute_distances =", "of points in space corresponding to the vertices that immediately", "return points[np.argmax(coords_on_axis)] def inflection_points(points, axis, span): ''' Find the list", "differentiated with respect to the coordinate system defined by axis", "of the curve with respect to the # defined coordinate", "of vertices that preceed inflection points in a curve. The", "is an 3x1 np.array. ''' coords_on_axis = points.dot(axis) return points[np.argmax(coords_on_axis)]", "the coordinate system. returns: a list of points in space", "the given point. Return a tuple: farthest_point, index_of_farthest_point. ''' absolute_distances", "signalling an inflection point is_inflection_point = [finite_difference_2[i] * finite_difference_2[i +", "If a pair of points has a negative product, then", "of those points, signalling an inflection point is_inflection_point = [finite_difference_2[i]", "curve is differentiated with respect to the coordinate system defined", "of the coordinate system. returns: a list of points in", "with respect to the # defined coordinate system finite_difference_2 =", "numpy as np from blmath.numerics import vx def apex(points, axis):", "points[np.argmax(coords_on_axis)] def inflection_points(points, axis, span): ''' Find the list of", "to the # defined coordinate system finite_difference_2 = np.gradient(np.gradient(coords_on_axis, dx),", "the most extreme point in the direction of the axis", "Find the list of vertices that preceed inflection points in", "the horiztonal axis of the coordinate system. returns: a list", "== 0: # pylint: disable=len-as-condition return [] return points[inflection_point_indices] def", "axis of the coordinate system. returns: a list of points", "# pylint: disable=len-as-condition return [] return points[inflection_point_indices] def farthest(from_point, to_points):", "range(len(finite_difference_2) - 1)] inflection_point_indices = [i for i, b in", "a tuple: farthest_point, index_of_farthest_point. ''' absolute_distances = vx.magnitude(to_points - from_point)", "then the second derivative changes sign # at one of", "to the vertices that immediately preceed inflection points in the", "apex(points, axis): ''' Find the most extreme point in the", "import vx def apex(points, axis): ''' Find the most extreme", "extreme point in the direction of the axis provided. axis:", "second derivative # If a pair of points has a", "0 for i in range(len(finite_difference_2) - 1)] inflection_point_indices = [i", "representing the vertical axis of the coordinate system. span: A", "if b] if len(inflection_point_indices) == 0: # pylint: disable=len-as-condition return", "b] if len(inflection_point_indices) == 0: # pylint: disable=len-as-condition return []", "system defined by axis and span. axis: A vector representing", "= points.dot(axis) return points[np.argmax(coords_on_axis)] def inflection_points(points, axis, span): ''' Find", "# Take the second order finite difference of the curve", "point is_inflection_point = [finite_difference_2[i] * finite_difference_2[i + 1] <= 0", "that preceed inflection points in a curve. The curve is", "1)] inflection_point_indices = [i for i, b in enumerate(is_inflection_point) if", "axis: A vector, which is an 3x1 np.array. ''' coords_on_axis", "horiztonal axis of the coordinate system. returns: a list of", "b in enumerate(is_inflection_point) if b] if len(inflection_point_indices) == 0: #", "inflection point is_inflection_point = [finite_difference_2[i] * finite_difference_2[i + 1] <=", "inputs, to the given point. Return a tuple: farthest_point, index_of_farthest_point.", "derivative changes sign # at one of those points, signalling", "the direction of the axis provided. axis: A vector, which", "inflection points in a curve. The curve is differentiated with", "The curve is differentiated with respect to the coordinate system", "points.dot(axis) # Take the second order finite difference of the", "the inputs, to the given point. Return a tuple: farthest_point,", "order finite difference of the curve with respect to the", "return points[inflection_point_indices] def farthest(from_point, to_points): ''' Find the farthest point", "point in the direction of the axis provided. axis: A", "= np.gradient(coords_on_span) coords_on_axis = points.dot(axis) # Take the second order", "difference of the curve with respect to the # defined", "to the given point. Return a tuple: farthest_point, index_of_farthest_point. '''", "direction of the axis provided. axis: A vector, which is", "vertical axis of the coordinate system. span: A vector representing", "immediately preceed inflection points in the curve ''' coords_on_span =", "0: # pylint: disable=len-as-condition return [] return points[inflection_point_indices] def farthest(from_point,", "''' Find the list of vertices that preceed inflection points", "and span. axis: A vector representing the vertical axis of", "in the curve ''' coords_on_span = points.dot(span) dx = np.gradient(coords_on_span)", "axis, span): ''' Find the list of vertices that preceed", "the vertical axis of the coordinate system. span: A vector", "in enumerate(is_inflection_point) if b] if len(inflection_point_indices) == 0: # pylint:", "among the inputs, to the given point. Return a tuple:", "dx) # Compare the product of all neighboring pairs of", "negative product, then the second derivative changes sign # at", "inflection_point_indices = [i for i, b in enumerate(is_inflection_point) if b]", "coords_on_axis = points.dot(axis) # Take the second order finite difference", "np from blmath.numerics import vx def apex(points, axis): ''' Find", "by axis and span. axis: A vector representing the vertical", "dx), dx) # Compare the product of all neighboring pairs", "vertices that immediately preceed inflection points in the curve '''", "the second order finite difference of the curve with respect", "np.array. ''' coords_on_axis = points.dot(axis) return points[np.argmax(coords_on_axis)] def inflection_points(points, axis,", "respect to the coordinate system defined by axis and span.", "the curve with respect to the # defined coordinate system", "vertices that preceed inflection points in a curve. The curve", "the coordinate system defined by axis and span. axis: A", "curve with respect to the # defined coordinate system finite_difference_2", "points.dot(axis) return points[np.argmax(coords_on_axis)] def inflection_points(points, axis, span): ''' Find the", "one of those points, signalling an inflection point is_inflection_point =", "axis provided. axis: A vector, which is an 3x1 np.array.", "i in range(len(finite_difference_2) - 1)] inflection_point_indices = [i for i,", "pylint: disable=len-as-condition return [] return points[inflection_point_indices] def farthest(from_point, to_points): '''", "* finite_difference_2[i + 1] <= 0 for i in range(len(finite_difference_2)", "an inflection point is_inflection_point = [finite_difference_2[i] * finite_difference_2[i + 1]", "curve. The curve is differentiated with respect to the coordinate", "farthest_point, index_of_farthest_point. ''' absolute_distances = vx.magnitude(to_points - from_point) index_of_farthest_point =", "finite_difference_2 = np.gradient(np.gradient(coords_on_axis, dx), dx) # Compare the product of", "product, then the second derivative changes sign # at one", "''' coords_on_span = points.dot(span) dx = np.gradient(coords_on_span) coords_on_axis = points.dot(axis)", "pairs of points in the second derivative # If a", "is_inflection_point = [finite_difference_2[i] * finite_difference_2[i + 1] <= 0 for", "those points, signalling an inflection point is_inflection_point = [finite_difference_2[i] *", "farthest(from_point, to_points): ''' Find the farthest point among the inputs,", "inflection points in the curve ''' coords_on_span = points.dot(span) dx", "points in the curve ''' coords_on_span = points.dot(span) dx =", "3x1 np.array. ''' coords_on_axis = points.dot(axis) return points[np.argmax(coords_on_axis)] def inflection_points(points,", "to the coordinate system defined by axis and span. axis:", "= [i for i, b in enumerate(is_inflection_point) if b] if", "- from_point) index_of_farthest_point = np.argmax(absolute_distances) farthest_point = to_points[index_of_farthest_point] return farthest_point,", "a pair of points has a negative product, then the", "A vector representing the vertical axis of the coordinate system.", "of points in the second derivative # If a pair", "inflection_points(points, axis, span): ''' Find the list of vertices that", "a curve. The curve is differentiated with respect to the", "of the coordinate system. span: A vector representing the the", "all neighboring pairs of points in the second derivative #", "points has a negative product, then the second derivative changes", "[i for i, b in enumerate(is_inflection_point) if b] if len(inflection_point_indices)", "list of points in space corresponding to the vertices that", "dx = np.gradient(coords_on_span) coords_on_axis = points.dot(axis) # Take the second", "the curve ''' coords_on_span = points.dot(span) dx = np.gradient(coords_on_span) coords_on_axis", "in a curve. The curve is differentiated with respect to", "the second derivative # If a pair of points has", "span: A vector representing the the horiztonal axis of the", "if len(inflection_point_indices) == 0: # pylint: disable=len-as-condition return [] return", "<= 0 for i in range(len(finite_difference_2) - 1)] inflection_point_indices =", "axis: A vector representing the vertical axis of the coordinate", "span. axis: A vector representing the vertical axis of the", "provided. axis: A vector, which is an 3x1 np.array. '''", "in range(len(finite_difference_2) - 1)] inflection_point_indices = [i for i, b", "second order finite difference of the curve with respect to", "i, b in enumerate(is_inflection_point) if b] if len(inflection_point_indices) == 0:", "index_of_farthest_point. ''' absolute_distances = vx.magnitude(to_points - from_point) index_of_farthest_point = np.argmax(absolute_distances)", "second derivative changes sign # at one of those points,", "the second derivative changes sign # at one of those", "def farthest(from_point, to_points): ''' Find the farthest point among the", "[] return points[inflection_point_indices] def farthest(from_point, to_points): ''' Find the farthest", "sign # at one of those points, signalling an inflection", "coordinate system finite_difference_2 = np.gradient(np.gradient(coords_on_axis, dx), dx) # Compare the", "Take the second order finite difference of the curve with", "[finite_difference_2[i] * finite_difference_2[i + 1] <= 0 for i in", "span): ''' Find the list of vertices that preceed inflection", "# Compare the product of all neighboring pairs of points", "product of all neighboring pairs of points in the second", "derivative # If a pair of points has a negative", "of points has a negative product, then the second derivative", "len(inflection_point_indices) == 0: # pylint: disable=len-as-condition return [] return points[inflection_point_indices]", "disable=len-as-condition return [] return points[inflection_point_indices] def farthest(from_point, to_points): ''' Find", "the farthest point among the inputs, to the given point.", "the list of vertices that preceed inflection points in a", "A vector representing the the horiztonal axis of the coordinate", "axis of the coordinate system. span: A vector representing the", "defined coordinate system finite_difference_2 = np.gradient(np.gradient(coords_on_axis, dx), dx) # Compare", "def inflection_points(points, axis, span): ''' Find the list of vertices", "system. span: A vector representing the the horiztonal axis of", "# defined coordinate system finite_difference_2 = np.gradient(np.gradient(coords_on_axis, dx), dx) #", "to_points): ''' Find the farthest point among the inputs, to", "the vertices that immediately preceed inflection points in the curve", "= vx.magnitude(to_points - from_point) index_of_farthest_point = np.argmax(absolute_distances) farthest_point = to_points[index_of_farthest_point]", "finite difference of the curve with respect to the #", "point among the inputs, to the given point. Return a", "vx.magnitude(to_points - from_point) index_of_farthest_point = np.argmax(absolute_distances) farthest_point = to_points[index_of_farthest_point] return", "respect to the # defined coordinate system finite_difference_2 = np.gradient(np.gradient(coords_on_axis,", "np.gradient(coords_on_span) coords_on_axis = points.dot(axis) # Take the second order finite", "at one of those points, signalling an inflection point is_inflection_point", "finite_difference_2[i + 1] <= 0 for i in range(len(finite_difference_2) -", "def apex(points, axis): ''' Find the most extreme point in", "<filename>blmath/geometry/apex.py import numpy as np from blmath.numerics import vx def", "in the direction of the axis provided. axis: A vector,", "points in a curve. The curve is differentiated with respect", "+ 1] <= 0 for i in range(len(finite_difference_2) - 1)]", "a list of points in space corresponding to the vertices", "''' Find the most extreme point in the direction of", "that immediately preceed inflection points in the curve ''' coords_on_span", "the product of all neighboring pairs of points in the", "vector representing the the horiztonal axis of the coordinate system.", "system. returns: a list of points in space corresponding to", "blmath.numerics import vx def apex(points, axis): ''' Find the most", "from_point) index_of_farthest_point = np.argmax(absolute_distances) farthest_point = to_points[index_of_farthest_point] return farthest_point, index_of_farthest_point", "= points.dot(span) dx = np.gradient(coords_on_span) coords_on_axis = points.dot(axis) # Take", "points in the second derivative # If a pair of", "coordinate system. returns: a list of points in space corresponding", "# If a pair of points has a negative product,", "axis): ''' Find the most extreme point in the direction", "tuple: farthest_point, index_of_farthest_point. ''' absolute_distances = vx.magnitude(to_points - from_point) index_of_farthest_point", "from blmath.numerics import vx def apex(points, axis): ''' Find the", "Return a tuple: farthest_point, index_of_farthest_point. ''' absolute_distances = vx.magnitude(to_points -", "has a negative product, then the second derivative changes sign", "most extreme point in the direction of the axis provided.", "coords_on_span = points.dot(span) dx = np.gradient(coords_on_span) coords_on_axis = points.dot(axis) #", "system finite_difference_2 = np.gradient(np.gradient(coords_on_axis, dx), dx) # Compare the product", "Find the most extreme point in the direction of the", "return [] return points[inflection_point_indices] def farthest(from_point, to_points): ''' Find the", "vector representing the vertical axis of the coordinate system. span:", "coordinate system defined by axis and span. axis: A vector", "enumerate(is_inflection_point) if b] if len(inflection_point_indices) == 0: # pylint: disable=len-as-condition", "Find the farthest point among the inputs, to the given", "is differentiated with respect to the coordinate system defined by", "the coordinate system. span: A vector representing the the horiztonal", "for i, b in enumerate(is_inflection_point) if b] if len(inflection_point_indices) ==", "A vector, which is an 3x1 np.array. ''' coords_on_axis =", "point. Return a tuple: farthest_point, index_of_farthest_point. ''' absolute_distances = vx.magnitude(to_points", "in the second derivative # If a pair of points", "the # defined coordinate system finite_difference_2 = np.gradient(np.gradient(coords_on_axis, dx), dx)", "= np.gradient(np.gradient(coords_on_axis, dx), dx) # Compare the product of all", "as np from blmath.numerics import vx def apex(points, axis): '''", "vx def apex(points, axis): ''' Find the most extreme point", "preceed inflection points in a curve. The curve is differentiated", "vector, which is an 3x1 np.array. ''' coords_on_axis = points.dot(axis)", "defined by axis and span. axis: A vector representing the", "axis and span. axis: A vector representing the vertical axis", "points.dot(span) dx = np.gradient(coords_on_span) coords_on_axis = points.dot(axis) # Take the", "changes sign # at one of those points, signalling an", "curve ''' coords_on_span = points.dot(span) dx = np.gradient(coords_on_span) coords_on_axis =", "1] <= 0 for i in range(len(finite_difference_2) - 1)] inflection_point_indices", "in space corresponding to the vertices that immediately preceed inflection", "space corresponding to the vertices that immediately preceed inflection points", "- 1)] inflection_point_indices = [i for i, b in enumerate(is_inflection_point)", "list of vertices that preceed inflection points in a curve.", "np.gradient(np.gradient(coords_on_axis, dx), dx) # Compare the product of all neighboring", "coordinate system. span: A vector representing the the horiztonal axis", "pair of points has a negative product, then the second", "points[inflection_point_indices] def farthest(from_point, to_points): ''' Find the farthest point among", "a negative product, then the second derivative changes sign #", "corresponding to the vertices that immediately preceed inflection points in", "= [finite_difference_2[i] * finite_difference_2[i + 1] <= 0 for i", "absolute_distances = vx.magnitude(to_points - from_point) index_of_farthest_point = np.argmax(absolute_distances) farthest_point =", "an 3x1 np.array. ''' coords_on_axis = points.dot(axis) return points[np.argmax(coords_on_axis)] def", "farthest point among the inputs, to the given point. Return", "coords_on_axis = points.dot(axis) return points[np.argmax(coords_on_axis)] def inflection_points(points, axis, span): '''", "for i in range(len(finite_difference_2) - 1)] inflection_point_indices = [i for", "import numpy as np from blmath.numerics import vx def apex(points,", "preceed inflection points in the curve ''' coords_on_span = points.dot(span)", "''' absolute_distances = vx.magnitude(to_points - from_point) index_of_farthest_point = np.argmax(absolute_distances) farthest_point", "''' coords_on_axis = points.dot(axis) return points[np.argmax(coords_on_axis)] def inflection_points(points, axis, span):", "the the horiztonal axis of the coordinate system. returns: a", "Compare the product of all neighboring pairs of points in", "= points.dot(axis) # Take the second order finite difference of", "returns: a list of points in space corresponding to the", "points, signalling an inflection point is_inflection_point = [finite_difference_2[i] * finite_difference_2[i", "with respect to the coordinate system defined by axis and", "points in space corresponding to the vertices that immediately preceed", "''' Find the farthest point among the inputs, to the", "which is an 3x1 np.array. ''' coords_on_axis = points.dot(axis) return", "the axis provided. axis: A vector, which is an 3x1", "neighboring pairs of points in the second derivative # If", "# at one of those points, signalling an inflection point", "of the axis provided. axis: A vector, which is an", "of all neighboring pairs of points in the second derivative", "representing the the horiztonal axis of the coordinate system. returns:" ]
[ "TOKEN = os.environ.get(\"TOKEN\") # The token from the developer portal.", "discode.Message): msg: str = msg.content if msg.startswith(\"?hi\"): await message.channel.send(\"Hi!!!\") #", "message is sent to any channel that the bot has", "= os.environ.get(\"TOKEN\") # The token from the developer portal. client", "= discode.Client(token=TOKEN, intents=discode.Intents.default()) @client.on_event(\"ready\") async def on_ready(): print(client.user, \"is ready!\")", "for use. @client.on_event(\"message_create\") async def on_message(message: discode.Message): msg: str =", "intents=discode.Intents.default()) @client.on_event(\"ready\") async def on_ready(): print(client.user, \"is ready!\") # The", "listener gets fired when the bot/client is completely ready for", "msg.startswith(\"?hi\"): await message.channel.send(\"Hi!!!\") # The message_create listener is fired whenever", "os.environ.get(\"TOKEN\") # The token from the developer portal. client =", "discode.Client(token=TOKEN, intents=discode.Intents.default()) @client.on_event(\"ready\") async def on_ready(): print(client.user, \"is ready!\") #", "completely ready for use. @client.on_event(\"message_create\") async def on_message(message: discode.Message): msg:", "on_message(message: discode.Message): msg: str = msg.content if msg.startswith(\"?hi\"): await message.channel.send(\"Hi!!!\")", "if msg.startswith(\"?hi\"): await message.channel.send(\"Hi!!!\") # The message_create listener is fired", "gets fired when the bot/client is completely ready for use.", "ready for use. @client.on_event(\"message_create\") async def on_message(message: discode.Message): msg: str", "The token from the developer portal. client = discode.Client(token=TOKEN, intents=discode.Intents.default())", "discode TOKEN = os.environ.get(\"TOKEN\") # The token from the developer", "= msg.content if msg.startswith(\"?hi\"): await message.channel.send(\"Hi!!!\") # The message_create listener", "token from the developer portal. client = discode.Client(token=TOKEN, intents=discode.Intents.default()) @client.on_event(\"ready\")", "msg.content if msg.startswith(\"?hi\"): await message.channel.send(\"Hi!!!\") # The message_create listener is", "portal. client = discode.Client(token=TOKEN, intents=discode.Intents.default()) @client.on_event(\"ready\") async def on_ready(): print(client.user,", "fired whenever a message is sent to any channel that", "developer portal. client = discode.Client(token=TOKEN, intents=discode.Intents.default()) @client.on_event(\"ready\") async def on_ready():", "async def on_message(message: discode.Message): msg: str = msg.content if msg.startswith(\"?hi\"):", "def on_message(message: discode.Message): msg: str = msg.content if msg.startswith(\"?hi\"): await", "is fired whenever a message is sent to any channel", "from the developer portal. client = discode.Client(token=TOKEN, intents=discode.Intents.default()) @client.on_event(\"ready\") async", "<filename>examples/client/main.py<gh_stars>1-10 import os import discode TOKEN = os.environ.get(\"TOKEN\") # The", "message_create listener is fired whenever a message is sent to", "whenever a message is sent to any channel that the", "The ready listener gets fired when the bot/client is completely", "str = msg.content if msg.startswith(\"?hi\"): await message.channel.send(\"Hi!!!\") # The message_create", "fired when the bot/client is completely ready for use. @client.on_event(\"message_create\")", "import os import discode TOKEN = os.environ.get(\"TOKEN\") # The token", "The message_create listener is fired whenever a message is sent", "os import discode TOKEN = os.environ.get(\"TOKEN\") # The token from", "await message.channel.send(\"Hi!!!\") # The message_create listener is fired whenever a", "client = discode.Client(token=TOKEN, intents=discode.Intents.default()) @client.on_event(\"ready\") async def on_ready(): print(client.user, \"is", "# The token from the developer portal. client = discode.Client(token=TOKEN,", "on_ready(): print(client.user, \"is ready!\") # The ready listener gets fired", "msg: str = msg.content if msg.startswith(\"?hi\"): await message.channel.send(\"Hi!!!\") # The", "def on_ready(): print(client.user, \"is ready!\") # The ready listener gets", "# The message_create listener is fired whenever a message is", "message.channel.send(\"Hi!!!\") # The message_create listener is fired whenever a message", "# The ready listener gets fired when the bot/client is", "use. @client.on_event(\"message_create\") async def on_message(message: discode.Message): msg: str = msg.content", "is sent to any channel that the bot has access", "when the bot/client is completely ready for use. @client.on_event(\"message_create\") async", "listener is fired whenever a message is sent to any", "is completely ready for use. @client.on_event(\"message_create\") async def on_message(message: discode.Message):", "\"is ready!\") # The ready listener gets fired when the", "sent to any channel that the bot has access to.", "async def on_ready(): print(client.user, \"is ready!\") # The ready listener", "print(client.user, \"is ready!\") # The ready listener gets fired when", "the developer portal. client = discode.Client(token=TOKEN, intents=discode.Intents.default()) @client.on_event(\"ready\") async def", "ready listener gets fired when the bot/client is completely ready", "bot/client is completely ready for use. @client.on_event(\"message_create\") async def on_message(message:", "import discode TOKEN = os.environ.get(\"TOKEN\") # The token from the", "the bot/client is completely ready for use. @client.on_event(\"message_create\") async def", "ready!\") # The ready listener gets fired when the bot/client", "a message is sent to any channel that the bot", "@client.on_event(\"message_create\") async def on_message(message: discode.Message): msg: str = msg.content if", "@client.on_event(\"ready\") async def on_ready(): print(client.user, \"is ready!\") # The ready" ]
[ "import CondConv2d, get_condconv_initializer from .config import is_exportable, is_scriptable, is_no_jit, set_exportable,", "from .squeeze_excite import SEModule, SqueezeExcite, EffectiveSEModule, EffectiveSqueezeExcite from .selective_kernel import", "Involution from .linear import Linear from .mixed_conv2d import MixedConv2d from", "get_act_layer, get_act_fn from .create_attn import get_attn, create_attn from .create_conv2d import", "DropBlock2d, DropPath, drop_block_2d, drop_path from .eca import EcaModule, CecaModule, EfficientChannelAttn,", "from .blur_pool import BlurPool2d from .classifier import ClassifierHead, create_classifier from", "from .evo_norm import EvoNormBatch2d, EvoNormSample2d from .gather_excite import GatherExcite from", "from .drop import DropBlock2d, DropPath, drop_block_2d, drop_path from .eca import", "SpaceToDepthModule from .split_attn import SplitAttn from .split_batchnorm import SplitBatchNorm2d, convert_splitbn_model", "from .conv_bn_act import ConvBnAct from .create_act import create_act_layer, get_act_layer, get_act_fn", "import EvoNormBatch2d, EvoNormSample2d from .gather_excite import GatherExcite from .global_context import", "from .space_to_depth import SpaceToDepthModule from .split_attn import SplitAttn from .split_batchnorm", "* from .adaptive_avgmax_pool import \\ adaptive_avgmax_pool2d, select_adaptive_pool2d, AdaptiveAvgMaxPool2d, SelectAdaptivePool2d from", "from .eca import EcaModule, CecaModule, EfficientChannelAttn, CircularEfficientChannelAttn from .evo_norm import", ".involution import Involution from .linear import Linear from .mixed_conv2d import", ".helpers import to_ntuple, to_2tuple, to_3tuple, to_4tuple, make_divisible from .inplace_abn import", ".adaptive_avgmax_pool import \\ adaptive_avgmax_pool2d, select_adaptive_pool2d, AdaptiveAvgMaxPool2d, SelectAdaptivePool2d from .blur_pool import", "to_2tuple, to_3tuple, to_4tuple, make_divisible from .inplace_abn import InplaceAbn from .involution", "SelectiveKernel from .separable_conv import SeparableConv2d, SeparableConvBnAct from .space_to_depth import SpaceToDepthModule", "SqueezeExcite, EffectiveSEModule, EffectiveSqueezeExcite from .selective_kernel import SelectiveKernel from .separable_conv import", ".activations import * from .adaptive_avgmax_pool import \\ adaptive_avgmax_pool2d, select_adaptive_pool2d, AdaptiveAvgMaxPool2d,", "import \\ adaptive_avgmax_pool2d, select_adaptive_pool2d, AdaptiveAvgMaxPool2d, SelectAdaptivePool2d from .blur_pool import BlurPool2d", "adaptive_avgmax_pool2d, select_adaptive_pool2d, AdaptiveAvgMaxPool2d, SelectAdaptivePool2d from .blur_pool import BlurPool2d from .classifier", "import Mlp, GluMlp, GatedMlp, ConvMlpGeneral, ConvMlpGeneralv2 from .non_local_attn import NonLocalAttn,", "CondConv2d, get_condconv_initializer from .config import is_exportable, is_scriptable, is_no_jit, set_exportable, set_scriptable,", "import Conv2dSame, conv2d_same from .conv_bn_act import ConvBnAct from .create_act import", "import GroupNorm, LayerNorm2d from .norm_act import BatchNormAct2d, GroupNormAct from .padding", ".space_to_depth import SpaceToDepthModule from .split_attn import SplitAttn from .split_batchnorm import", "from .pool2d_same import AvgPool2dSame, create_pool2d from .squeeze_excite import SEModule, SqueezeExcite,", "import create_act_layer, get_act_layer, get_act_fn from .create_attn import get_attn, create_attn from", "import NonLocalAttn, BatNonLocalAttn from .norm import GroupNorm, LayerNorm2d from .norm_act", "GroupNorm, LayerNorm2d from .norm_act import BatchNormAct2d, GroupNormAct from .padding import", "from .conv2d_same import Conv2dSame, conv2d_same from .conv_bn_act import ConvBnAct from", "import EcaModule, CecaModule, EfficientChannelAttn, CircularEfficientChannelAttn from .evo_norm import EvoNormBatch2d, EvoNormSample2d", "import AvgPool2dSame, create_pool2d from .squeeze_excite import SEModule, SqueezeExcite, EffectiveSEModule, EffectiveSqueezeExcite", ".linear import Linear from .mixed_conv2d import MixedConv2d from .mlp import", "BatNonLocalAttn from .norm import GroupNorm, LayerNorm2d from .norm_act import BatchNormAct2d,", "from .patch_embed import PatchEmbed from .pool2d_same import AvgPool2dSame, create_pool2d from", "make_divisible from .inplace_abn import InplaceAbn from .involution import Involution from", ".mixed_conv2d import MixedConv2d from .mlp import Mlp, GluMlp, GatedMlp, ConvMlpGeneral,", "from .gather_excite import GatherExcite from .global_context import GlobalContext from .helpers", "SplitBatchNorm2d, convert_splitbn_model from .std_conv import StdConv2d, StdConv2dSame, ScaledStdConv2d, ScaledStdConv2dSame from", ".pool2d_same import AvgPool2dSame, create_pool2d from .squeeze_excite import SEModule, SqueezeExcite, EffectiveSEModule,", ".norm_act import BatchNormAct2d, GroupNormAct from .padding import get_padding, get_same_padding, pad_same", "to_4tuple, make_divisible from .inplace_abn import InplaceAbn from .involution import Involution", "get_norm_act_layer, create_norm_act, convert_norm_act from .drop import DropBlock2d, DropPath, drop_block_2d, drop_path", "import to_ntuple, to_2tuple, to_3tuple, to_4tuple, make_divisible from .inplace_abn import InplaceAbn", "StdConv2d, StdConv2dSame, ScaledStdConv2d, ScaledStdConv2dSame from .test_time_pool import TestTimePoolHead, apply_test_time_pool from", "import BlurPool2d from .classifier import ClassifierHead, create_classifier from .cond_conv2d import", "from .selective_kernel import SelectiveKernel from .separable_conv import SeparableConv2d, SeparableConvBnAct from", ".create_act import create_act_layer, get_act_layer, get_act_fn from .create_attn import get_attn, create_attn", "SplitAttn from .split_batchnorm import SplitBatchNorm2d, convert_splitbn_model from .std_conv import StdConv2d,", ".gather_excite import GatherExcite from .global_context import GlobalContext from .helpers import", "is_scriptable, is_no_jit, set_exportable, set_scriptable, set_no_jit,\\ set_layer_config from .conv2d_same import Conv2dSame,", "import DropBlock2d, DropPath, drop_block_2d, drop_path from .eca import EcaModule, CecaModule,", "CecaModule, EfficientChannelAttn, CircularEfficientChannelAttn from .evo_norm import EvoNormBatch2d, EvoNormSample2d from .gather_excite", "get_condconv_initializer from .config import is_exportable, is_scriptable, is_no_jit, set_exportable, set_scriptable, set_no_jit,\\", "select_adaptive_pool2d, AdaptiveAvgMaxPool2d, SelectAdaptivePool2d from .blur_pool import BlurPool2d from .classifier import", "get_attn, create_attn from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer,", "\\ adaptive_avgmax_pool2d, select_adaptive_pool2d, AdaptiveAvgMaxPool2d, SelectAdaptivePool2d from .blur_pool import BlurPool2d from", "from .norm_act import BatchNormAct2d, GroupNormAct from .padding import get_padding, get_same_padding,", "from .mixed_conv2d import MixedConv2d from .mlp import Mlp, GluMlp, GatedMlp,", ".non_local_attn import NonLocalAttn, BatNonLocalAttn from .norm import GroupNorm, LayerNorm2d from", "import BatchNormAct2d, GroupNormAct from .padding import get_padding, get_same_padding, pad_same from", "from .cond_conv2d import CondConv2d, get_condconv_initializer from .config import is_exportable, is_scriptable,", "from .config import is_exportable, is_scriptable, is_no_jit, set_exportable, set_scriptable, set_no_jit,\\ set_layer_config", "import get_norm_act_layer, create_norm_act, convert_norm_act from .drop import DropBlock2d, DropPath, drop_block_2d,", "import SEModule, SqueezeExcite, EffectiveSEModule, EffectiveSqueezeExcite from .selective_kernel import SelectiveKernel from", ".create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer, create_norm_act, convert_norm_act from", "import StdConv2d, StdConv2dSame, ScaledStdConv2d, ScaledStdConv2dSame from .test_time_pool import TestTimePoolHead, apply_test_time_pool", "from .test_time_pool import TestTimePoolHead, apply_test_time_pool from .weight_init import trunc_normal_, variance_scaling_,", "import Involution from .linear import Linear from .mixed_conv2d import MixedConv2d", "get_same_padding, pad_same from .patch_embed import PatchEmbed from .pool2d_same import AvgPool2dSame,", "import create_conv2d from .create_norm_act import get_norm_act_layer, create_norm_act, convert_norm_act from .drop", "to_ntuple, to_2tuple, to_3tuple, to_4tuple, make_divisible from .inplace_abn import InplaceAbn from", ".patch_embed import PatchEmbed from .pool2d_same import AvgPool2dSame, create_pool2d from .squeeze_excite", ".create_norm_act import get_norm_act_layer, create_norm_act, convert_norm_act from .drop import DropBlock2d, DropPath,", "from .separable_conv import SeparableConv2d, SeparableConvBnAct from .space_to_depth import SpaceToDepthModule from", "<reponame>kkahatapitiya/pytorch-image-models<filename>timm/models/layers/__init__.py from .activations import * from .adaptive_avgmax_pool import \\ adaptive_avgmax_pool2d,", "from .create_act import create_act_layer, get_act_layer, get_act_fn from .create_attn import get_attn,", ".inplace_abn import InplaceAbn from .involution import Involution from .linear import", "create_act_layer, get_act_layer, get_act_fn from .create_attn import get_attn, create_attn from .create_conv2d", "import PatchEmbed from .pool2d_same import AvgPool2dSame, create_pool2d from .squeeze_excite import", "EcaModule, CecaModule, EfficientChannelAttn, CircularEfficientChannelAttn from .evo_norm import EvoNormBatch2d, EvoNormSample2d from", ".std_conv import StdConv2d, StdConv2dSame, ScaledStdConv2d, ScaledStdConv2dSame from .test_time_pool import TestTimePoolHead,", ".separable_conv import SeparableConv2d, SeparableConvBnAct from .space_to_depth import SpaceToDepthModule from .split_attn", "import is_exportable, is_scriptable, is_no_jit, set_exportable, set_scriptable, set_no_jit,\\ set_layer_config from .conv2d_same", "EffectiveSqueezeExcite from .selective_kernel import SelectiveKernel from .separable_conv import SeparableConv2d, SeparableConvBnAct", "BatchNormAct2d, GroupNormAct from .padding import get_padding, get_same_padding, pad_same from .patch_embed", "AvgPool2dSame, create_pool2d from .squeeze_excite import SEModule, SqueezeExcite, EffectiveSEModule, EffectiveSqueezeExcite from", ".drop import DropBlock2d, DropPath, drop_block_2d, drop_path from .eca import EcaModule,", "create_conv2d from .create_norm_act import get_norm_act_layer, create_norm_act, convert_norm_act from .drop import", ".classifier import ClassifierHead, create_classifier from .cond_conv2d import CondConv2d, get_condconv_initializer from", "PatchEmbed from .pool2d_same import AvgPool2dSame, create_pool2d from .squeeze_excite import SEModule,", "ConvBnAct from .create_act import create_act_layer, get_act_layer, get_act_fn from .create_attn import", "import SplitBatchNorm2d, convert_splitbn_model from .std_conv import StdConv2d, StdConv2dSame, ScaledStdConv2d, ScaledStdConv2dSame", "ClassifierHead, create_classifier from .cond_conv2d import CondConv2d, get_condconv_initializer from .config import", "is_no_jit, set_exportable, set_scriptable, set_no_jit,\\ set_layer_config from .conv2d_same import Conv2dSame, conv2d_same", "import GlobalContext from .helpers import to_ntuple, to_2tuple, to_3tuple, to_4tuple, make_divisible", "set_exportable, set_scriptable, set_no_jit,\\ set_layer_config from .conv2d_same import Conv2dSame, conv2d_same from", "import MixedConv2d from .mlp import Mlp, GluMlp, GatedMlp, ConvMlpGeneral, ConvMlpGeneralv2", "import get_padding, get_same_padding, pad_same from .patch_embed import PatchEmbed from .pool2d_same", "pad_same from .patch_embed import PatchEmbed from .pool2d_same import AvgPool2dSame, create_pool2d", "set_scriptable, set_no_jit,\\ set_layer_config from .conv2d_same import Conv2dSame, conv2d_same from .conv_bn_act", ".cond_conv2d import CondConv2d, get_condconv_initializer from .config import is_exportable, is_scriptable, is_no_jit,", "InplaceAbn from .involution import Involution from .linear import Linear from", "from .classifier import ClassifierHead, create_classifier from .cond_conv2d import CondConv2d, get_condconv_initializer", "from .create_norm_act import get_norm_act_layer, create_norm_act, convert_norm_act from .drop import DropBlock2d,", "get_act_fn from .create_attn import get_attn, create_attn from .create_conv2d import create_conv2d", "from .norm import GroupNorm, LayerNorm2d from .norm_act import BatchNormAct2d, GroupNormAct", "import get_attn, create_attn from .create_conv2d import create_conv2d from .create_norm_act import", ".global_context import GlobalContext from .helpers import to_ntuple, to_2tuple, to_3tuple, to_4tuple,", "DropPath, drop_block_2d, drop_path from .eca import EcaModule, CecaModule, EfficientChannelAttn, CircularEfficientChannelAttn", "MixedConv2d from .mlp import Mlp, GluMlp, GatedMlp, ConvMlpGeneral, ConvMlpGeneralv2 from", "from .inplace_abn import InplaceAbn from .involution import Involution from .linear", "GatherExcite from .global_context import GlobalContext from .helpers import to_ntuple, to_2tuple,", "from .activations import * from .adaptive_avgmax_pool import \\ adaptive_avgmax_pool2d, select_adaptive_pool2d,", "CircularEfficientChannelAttn from .evo_norm import EvoNormBatch2d, EvoNormSample2d from .gather_excite import GatherExcite", "get_padding, get_same_padding, pad_same from .patch_embed import PatchEmbed from .pool2d_same import", ".conv_bn_act import ConvBnAct from .create_act import create_act_layer, get_act_layer, get_act_fn from", "set_layer_config from .conv2d_same import Conv2dSame, conv2d_same from .conv_bn_act import ConvBnAct", ".create_attn import get_attn, create_attn from .create_conv2d import create_conv2d from .create_norm_act", "create_classifier from .cond_conv2d import CondConv2d, get_condconv_initializer from .config import is_exportable,", "EffectiveSEModule, EffectiveSqueezeExcite from .selective_kernel import SelectiveKernel from .separable_conv import SeparableConv2d,", "create_norm_act, convert_norm_act from .drop import DropBlock2d, DropPath, drop_block_2d, drop_path from", "SEModule, SqueezeExcite, EffectiveSEModule, EffectiveSqueezeExcite from .selective_kernel import SelectiveKernel from .separable_conv", "import Linear from .mixed_conv2d import MixedConv2d from .mlp import Mlp,", "LayerNorm2d from .norm_act import BatchNormAct2d, GroupNormAct from .padding import get_padding,", "import * from .adaptive_avgmax_pool import \\ adaptive_avgmax_pool2d, select_adaptive_pool2d, AdaptiveAvgMaxPool2d, SelectAdaptivePool2d", "set_no_jit,\\ set_layer_config from .conv2d_same import Conv2dSame, conv2d_same from .conv_bn_act import", "from .mlp import Mlp, GluMlp, GatedMlp, ConvMlpGeneral, ConvMlpGeneralv2 from .non_local_attn", ".mlp import Mlp, GluMlp, GatedMlp, ConvMlpGeneral, ConvMlpGeneralv2 from .non_local_attn import", ".split_attn import SplitAttn from .split_batchnorm import SplitBatchNorm2d, convert_splitbn_model from .std_conv", "to_3tuple, to_4tuple, make_divisible from .inplace_abn import InplaceAbn from .involution import", "SeparableConv2d, SeparableConvBnAct from .space_to_depth import SpaceToDepthModule from .split_attn import SplitAttn", "from .helpers import to_ntuple, to_2tuple, to_3tuple, to_4tuple, make_divisible from .inplace_abn", "import ConvBnAct from .create_act import create_act_layer, get_act_layer, get_act_fn from .create_attn", "from .split_batchnorm import SplitBatchNorm2d, convert_splitbn_model from .std_conv import StdConv2d, StdConv2dSame,", "GatedMlp, ConvMlpGeneral, ConvMlpGeneralv2 from .non_local_attn import NonLocalAttn, BatNonLocalAttn from .norm", "from .std_conv import StdConv2d, StdConv2dSame, ScaledStdConv2d, ScaledStdConv2dSame from .test_time_pool import", ".eca import EcaModule, CecaModule, EfficientChannelAttn, CircularEfficientChannelAttn from .evo_norm import EvoNormBatch2d,", "GroupNormAct from .padding import get_padding, get_same_padding, pad_same from .patch_embed import", ".selective_kernel import SelectiveKernel from .separable_conv import SeparableConv2d, SeparableConvBnAct from .space_to_depth", "from .involution import Involution from .linear import Linear from .mixed_conv2d", "from .create_attn import get_attn, create_attn from .create_conv2d import create_conv2d from", "import SplitAttn from .split_batchnorm import SplitBatchNorm2d, convert_splitbn_model from .std_conv import", "import SpaceToDepthModule from .split_attn import SplitAttn from .split_batchnorm import SplitBatchNorm2d,", "Conv2dSame, conv2d_same from .conv_bn_act import ConvBnAct from .create_act import create_act_layer,", "SeparableConvBnAct from .space_to_depth import SpaceToDepthModule from .split_attn import SplitAttn from", ".split_batchnorm import SplitBatchNorm2d, convert_splitbn_model from .std_conv import StdConv2d, StdConv2dSame, ScaledStdConv2d,", ".norm import GroupNorm, LayerNorm2d from .norm_act import BatchNormAct2d, GroupNormAct from", "StdConv2dSame, ScaledStdConv2d, ScaledStdConv2dSame from .test_time_pool import TestTimePoolHead, apply_test_time_pool from .weight_init", ".blur_pool import BlurPool2d from .classifier import ClassifierHead, create_classifier from .cond_conv2d", "import SeparableConv2d, SeparableConvBnAct from .space_to_depth import SpaceToDepthModule from .split_attn import", "convert_splitbn_model from .std_conv import StdConv2d, StdConv2dSame, ScaledStdConv2d, ScaledStdConv2dSame from .test_time_pool", "from .non_local_attn import NonLocalAttn, BatNonLocalAttn from .norm import GroupNorm, LayerNorm2d", "ConvMlpGeneral, ConvMlpGeneralv2 from .non_local_attn import NonLocalAttn, BatNonLocalAttn from .norm import", ".evo_norm import EvoNormBatch2d, EvoNormSample2d from .gather_excite import GatherExcite from .global_context", "from .split_attn import SplitAttn from .split_batchnorm import SplitBatchNorm2d, convert_splitbn_model from", ".conv2d_same import Conv2dSame, conv2d_same from .conv_bn_act import ConvBnAct from .create_act", "create_attn from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer, create_norm_act,", "EvoNormBatch2d, EvoNormSample2d from .gather_excite import GatherExcite from .global_context import GlobalContext", "ScaledStdConv2dSame from .test_time_pool import TestTimePoolHead, apply_test_time_pool from .weight_init import trunc_normal_,", "convert_norm_act from .drop import DropBlock2d, DropPath, drop_block_2d, drop_path from .eca", ".config import is_exportable, is_scriptable, is_no_jit, set_exportable, set_scriptable, set_no_jit,\\ set_layer_config from", "GlobalContext from .helpers import to_ntuple, to_2tuple, to_3tuple, to_4tuple, make_divisible from", "SelectAdaptivePool2d from .blur_pool import BlurPool2d from .classifier import ClassifierHead, create_classifier", "from .linear import Linear from .mixed_conv2d import MixedConv2d from .mlp", ".test_time_pool import TestTimePoolHead, apply_test_time_pool from .weight_init import trunc_normal_, variance_scaling_, lecun_normal_", "conv2d_same from .conv_bn_act import ConvBnAct from .create_act import create_act_layer, get_act_layer,", "from .padding import get_padding, get_same_padding, pad_same from .patch_embed import PatchEmbed", "from .adaptive_avgmax_pool import \\ adaptive_avgmax_pool2d, select_adaptive_pool2d, AdaptiveAvgMaxPool2d, SelectAdaptivePool2d from .blur_pool", "from .global_context import GlobalContext from .helpers import to_ntuple, to_2tuple, to_3tuple,", "NonLocalAttn, BatNonLocalAttn from .norm import GroupNorm, LayerNorm2d from .norm_act import", "drop_block_2d, drop_path from .eca import EcaModule, CecaModule, EfficientChannelAttn, CircularEfficientChannelAttn from", "EvoNormSample2d from .gather_excite import GatherExcite from .global_context import GlobalContext from", "import ClassifierHead, create_classifier from .cond_conv2d import CondConv2d, get_condconv_initializer from .config", "Linear from .mixed_conv2d import MixedConv2d from .mlp import Mlp, GluMlp,", "import InplaceAbn from .involution import Involution from .linear import Linear", "import GatherExcite from .global_context import GlobalContext from .helpers import to_ntuple,", "Mlp, GluMlp, GatedMlp, ConvMlpGeneral, ConvMlpGeneralv2 from .non_local_attn import NonLocalAttn, BatNonLocalAttn", "ConvMlpGeneralv2 from .non_local_attn import NonLocalAttn, BatNonLocalAttn from .norm import GroupNorm,", "BlurPool2d from .classifier import ClassifierHead, create_classifier from .cond_conv2d import CondConv2d,", "is_exportable, is_scriptable, is_no_jit, set_exportable, set_scriptable, set_no_jit,\\ set_layer_config from .conv2d_same import", ".padding import get_padding, get_same_padding, pad_same from .patch_embed import PatchEmbed from", "EfficientChannelAttn, CircularEfficientChannelAttn from .evo_norm import EvoNormBatch2d, EvoNormSample2d from .gather_excite import", "create_pool2d from .squeeze_excite import SEModule, SqueezeExcite, EffectiveSEModule, EffectiveSqueezeExcite from .selective_kernel", "import SelectiveKernel from .separable_conv import SeparableConv2d, SeparableConvBnAct from .space_to_depth import", "GluMlp, GatedMlp, ConvMlpGeneral, ConvMlpGeneralv2 from .non_local_attn import NonLocalAttn, BatNonLocalAttn from", ".squeeze_excite import SEModule, SqueezeExcite, EffectiveSEModule, EffectiveSqueezeExcite from .selective_kernel import SelectiveKernel", "AdaptiveAvgMaxPool2d, SelectAdaptivePool2d from .blur_pool import BlurPool2d from .classifier import ClassifierHead,", "from .create_conv2d import create_conv2d from .create_norm_act import get_norm_act_layer, create_norm_act, convert_norm_act", "drop_path from .eca import EcaModule, CecaModule, EfficientChannelAttn, CircularEfficientChannelAttn from .evo_norm", "ScaledStdConv2d, ScaledStdConv2dSame from .test_time_pool import TestTimePoolHead, apply_test_time_pool from .weight_init import" ]
[ "r ** 2, r ** 2 * sin(th) ** 2)", "/ r), r ** 2, r ** 2 * sin(th)", "Name: Bondi References: Bondi, Proc. Roy. Soc. Lond. A, v282,", "v) / r), r ** 2, r ** 2 *", "th, ph = coords C, M = functions metric =", "** 2, r ** 2 * sin(th) ** 2) metric[0,", "Roy. Soc. Lond. A, v282, p303, (1964) Coordinates: Spherical Symmetry:", "symbols(\"r v theta phi\", real=True) variables = () functions =", "r), r ** 2, r ** 2 * sin(th) **", "diag, sin, symbols coords = symbols(\"r v theta phi\", real=True)", "Soc. Lond. A, v282, p303, (1964) Coordinates: Spherical Symmetry: Spherical", "= functions metric = diag(0, -C(r, v) ** 2 *", "variables = () functions = symbols(\"C M\", cls=Function) r, v,", "(1 - 2 * M(r, v) / r), r **", "C, M = functions metric = diag(0, -C(r, v) **", "from sympy import Function, diag, sin, symbols coords = symbols(\"r", "symbols(\"C M\", cls=Function) r, v, th, ph = coords C,", "v) ** 2 * (1 - 2 * M(r, v)", "real=True) variables = () functions = symbols(\"C M\", cls=Function) r,", "ph = coords C, M = functions metric = diag(0,", "- 2 * M(r, v) / r), r ** 2,", "Symmetry: Spherical Notes: Outgoing Coordinates \"\"\" from sympy import Function,", "functions metric = diag(0, -C(r, v) ** 2 * (1", "functions = symbols(\"C M\", cls=Function) r, v, th, ph =", "M(r, v) / r), r ** 2, r ** 2", "= () functions = symbols(\"C M\", cls=Function) r, v, th,", "Bondi References: Bondi, Proc. Roy. Soc. Lond. A, v282, p303,", "** 2) metric[0, 1] = metric[1, 0] = -C(r, v)", "M\", cls=Function) r, v, th, ph = coords C, M", "-C(r, v) ** 2 * (1 - 2 * M(r,", "** 2 * sin(th) ** 2) metric[0, 1] = metric[1,", "v282, p303, (1964) Coordinates: Spherical Symmetry: Spherical Notes: Outgoing Coordinates", "\"\"\" from sympy import Function, diag, sin, symbols coords =", "** 2 * (1 - 2 * M(r, v) /", "theta phi\", real=True) variables = () functions = symbols(\"C M\",", "() functions = symbols(\"C M\", cls=Function) r, v, th, ph", "r ** 2 * sin(th) ** 2) metric[0, 1] =", "sin(th) ** 2) metric[0, 1] = metric[1, 0] = -C(r,", "\"\"\" Name: Bondi References: Bondi, Proc. Roy. Soc. Lond. A,", "M = functions metric = diag(0, -C(r, v) ** 2", "Notes: Outgoing Coordinates \"\"\" from sympy import Function, diag, sin,", "= diag(0, -C(r, v) ** 2 * (1 - 2", "sympy import Function, diag, sin, symbols coords = symbols(\"r v", "coords C, M = functions metric = diag(0, -C(r, v)", "cls=Function) r, v, th, ph = coords C, M =", "Bondi, Proc. Roy. Soc. Lond. A, v282, p303, (1964) Coordinates:", "metric = diag(0, -C(r, v) ** 2 * (1 -", "v, th, ph = coords C, M = functions metric", "2 * (1 - 2 * M(r, v) / r),", "Spherical Notes: Outgoing Coordinates \"\"\" from sympy import Function, diag,", "Coordinates \"\"\" from sympy import Function, diag, sin, symbols coords", "Coordinates: Spherical Symmetry: Spherical Notes: Outgoing Coordinates \"\"\" from sympy", "Function, diag, sin, symbols coords = symbols(\"r v theta phi\",", "2, r ** 2 * sin(th) ** 2) metric[0, 1]", "Outgoing Coordinates \"\"\" from sympy import Function, diag, sin, symbols", "v theta phi\", real=True) variables = () functions = symbols(\"C", "symbols coords = symbols(\"r v theta phi\", real=True) variables =", "phi\", real=True) variables = () functions = symbols(\"C M\", cls=Function)", "(1964) Coordinates: Spherical Symmetry: Spherical Notes: Outgoing Coordinates \"\"\" from", "sin, symbols coords = symbols(\"r v theta phi\", real=True) variables", "Proc. Roy. Soc. Lond. A, v282, p303, (1964) Coordinates: Spherical", "coords = symbols(\"r v theta phi\", real=True) variables = ()", "diag(0, -C(r, v) ** 2 * (1 - 2 *", "p303, (1964) Coordinates: Spherical Symmetry: Spherical Notes: Outgoing Coordinates \"\"\"", "* M(r, v) / r), r ** 2, r **", "= symbols(\"C M\", cls=Function) r, v, th, ph = coords", "= symbols(\"r v theta phi\", real=True) variables = () functions", "2 * M(r, v) / r), r ** 2, r", "= coords C, M = functions metric = diag(0, -C(r,", "References: Bondi, Proc. Roy. Soc. Lond. A, v282, p303, (1964)", "Lond. A, v282, p303, (1964) Coordinates: Spherical Symmetry: Spherical Notes:", "A, v282, p303, (1964) Coordinates: Spherical Symmetry: Spherical Notes: Outgoing", "import Function, diag, sin, symbols coords = symbols(\"r v theta", "2 * sin(th) ** 2) metric[0, 1] = metric[1, 0]", "* sin(th) ** 2) metric[0, 1] = metric[1, 0] =", "Spherical Symmetry: Spherical Notes: Outgoing Coordinates \"\"\" from sympy import", "* (1 - 2 * M(r, v) / r), r", "r, v, th, ph = coords C, M = functions" ]
[ "get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.english_parent_page, language='en',", "question\" mock_return.text = \"inscisive text\" mock_queryset = mock.Mock() mock_queryset.__iter__ =", "django.utils import timezone from wagtail.wagtailcore.models import Site from wagtailsharing.models import", "request.GET = QueryDict(audience_querystring) result = redirect_ask_search(request) self.assertEqual( result.get('location'), '/ask-cfpb/audience-older-americans/') def", "test_request = HttpRequest() test_request.META['SERVER_NAME'] = 'preview.localhost' test_request.META['SERVER_PORT'] = 8000 view_answer(", "mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 0 mock_sqs_instance", "= 'Mock answer text.' mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return]))", "= annotate_links(mock_answer) self.assertEqual( annotated_answer, '<html><body><p>Answer with a <a href=\"http://fake.com\">fake '", "annotate_links(mock_answer) self.assertEqual(links, []) def test_annotate_links_no_site(self): site = Site.objects.get(is_default_site=True) site.is_default_site =", "HttpRequest() request.GET = QueryDict(tag_querystring) result = redirect_ask_search(request, language='es') self.assertEqual( result.get('location'),", "timezone from wagtail.wagtailcore.models import Site from wagtailsharing.models import SharingSite import", "test_en_search(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page = get_or_create_page( apps,", "mock_return = mock.Mock() mock_return.url = 'url' mock_return.autocomplete = 'question text'", "{'term': ''}) output = json.loads(result.content) self.assertEqual(output, []) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_en(self,", "results page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') mock_return = mock.Mock() mock_return.url =", "1) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_es_search(self, mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock", "= QueryDict(audience_querystring) result = redirect_ask_search(request) self.assertEqual( result.get('location'), '/ask-cfpb/audience-older-americans/') def test_spanish_redirect_search_with_tag(self):", "response.context_data['page'] self.assertEqual(response_page, mock_page) self.assertEqual(response_page.suggestion, 'paydya') self.assertEqual(response_page.result_query, 'payday') self.assertEqual(response_page.query, 'paydya') @mock.patch('ask_cfpb.views.redirect_ask_search')", "text.' mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 0", "= self.test_answer.english_page revision = page.save_revision() revision.publish() test_request = HttpRequest() test_request.META['SERVER_NAME']", "kwargs={'language': 'es'}), {'q': 'hipotecas'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'es') self.assertEqual(page.answers, [])", "200) response_page = response.context_data['page'] self.assertEqual(response_page, mock_page) self.assertEqual(response_page.suggestion, 'paydya') self.assertEqual(response_page.result_query, 'payday')", "context: annotate_links('answer') self.assertIn('no default wagtail site', str(context.exception)) def test_bad_language_search(self): with", "language='es') self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_es_search(self, mock_filter): get_or_create_page( apps, 'ask_cfpb',", "= Site.objects.get(is_default_site=True) site.is_default_site = False site.save() with self.assertRaises(RuntimeError) as context:", "def test_es_search(self, mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock Spanish results", "{'q': 'tuition'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'en') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()),", "self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='en', q='payday')) self.assertEqual(response.status_code, 404)", "setUp(self): from v1.models import HomePage from ask_cfpb.models import Answer self.ROOT_PAGE", "self.assertEqual(output, []) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_en(self, mock_autocomplete): mock_search_result = mock.Mock() mock_search_result.autocomplete", "self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].suggestion, None) self.assertEqual(mock_sqs_instance.filter.call_count, 1) self.assertTrue(mock_sqs_instance.filter.called_with( language='en',", "json.loads(result.content) self.assertEqual(output, []) def test_autocomplete_es_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language':", "self.assertEqual( result.get('location'), '/es/obtener-respuestas/buscar-por-etiqueta/{}/'.format( target_tag)) def test_english_redirect_search_with_tag(self): target_tag = 'englishtag1' tag_querystring", "def test_en_search_no_term(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page = get_or_create_page(", "def test_autocomplete_en(self, mock_autocomplete): mock_search_result = mock.Mock() mock_search_result.autocomplete = 'question' mock_search_result.url", "answer.\", question=\"Test question.\", slug='test-question', update_english_page=True, update_spanish_page=False) self.site = mommy.make( Site,", "self.client.get(reverse( 'ask-autocomplete-en'), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output = json.loads(result.content) self.assertEqual(", "v1.models import HomePage self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page = get_or_create_page( apps,", "HttpRequest() with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_blank_facets(self): request = HttpRequest() request.GET['selected_facets']", "import view_answer page = self.test_answer.english_page page.live = False page.save() test_request", "<a>fake link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer) self.assertEqual(links, []) def test_annotate_links_no_site(self):", "'respuestas', self.spanish_parent_page, language='es', live=True) mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov'", "self.assertEqual(mock_filter.call_count, 1) self.assertEqual(json.loads(response.content)['query'], 'tuition') def test_autocomplete_en_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-en'),", "'/es/obtener-respuestas/buscar-por-etiqueta/{}/'.format( target_tag)) def test_english_redirect_search_with_tag(self): target_tag = 'englishtag1' tag_querystring = (", "self.assertEqual( annotated_answer, '<html><body><p>Answer with a <a href=\"http://fake.com\">fake ' 'link.</a><sup>1</sup></p></body></html>') self.assertEqual(links,", "request.GET = QueryDict(tag_querystring) result = redirect_ask_search(request, language='es') self.assertEqual( result.get('location'), '/es/obtener-respuestas/buscar-por-etiqueta/{}/'.format(", "self.test_answer.english_page page.live = False page.save() test_request = HttpRequest() with self.assertRaises(Http404):", "self.assertEqual(response.status_code, 200) response_page = response.context_data['page'] self.assertEqual(response_page, mock_page) self.assertEqual(response_page.suggestion, 'paydya') self.assertEqual(response_page.result_query,", "{'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output = json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question',", "get_or_create_page now = timezone.now() class AnswerPagePreviewCase(TestCase): def setUp(self): from v1.models", "response = self.client.get(reverse( 'ask-search-en'), {'q': ''}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'],", "mock_return.autocomplete = \"inscisive question\" mock_return.text = \"inscisive text\" mock_queryset =", "'test-question', 'en', self.test_answer.pk) self.assertEqual(mock_serve.call_count, 1) def test_answer_page_not_live(self): from ask_cfpb.views import", "results page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') response = self.client.get(reverse( 'ask-search-en'), {'q':", "test_autocomplete_es_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': ''}) output", "sorted(output[0].keys()), ['question', 'url']) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_es(self, mock_autocomplete): mock_search_result = mock.Mock()", "def test_english_redirect_search_with_tag(self): target_tag = 'englishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:englishtag2'.format(target_tag))", "= QueryDict(tag_querystring) result = redirect_ask_search(request, language='en') self.assertEqual( result.get('location'), '/ask-cfpb/search-by-tag/{}/'.format( target_tag))", "tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:englishtag2'.format(target_tag)) request = HttpRequest() request.GET =", "= mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 0 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value =", "1) @mock.patch('ask_cfpb.views.redirect') def test_redirect_ask_search_passes_query_string(self, mock_redirect): request = HttpRequest() request.GET['q'] =", "'ask-autocomplete-en'), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output = json.loads(result.content) self.assertEqual( sorted(output[0].keys()),", "= self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='en', q='payday')) self.assertEqual(response.status_code,", "= 0 mock_filter.return_value = [mock_queryset] response = self.client.get(reverse( 'ask-search-en'), {'q':", "respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) self.test_answer = mommy.make( Answer, answer=\"Test", "'category_exact:my_categoria' redirect_ask_search(request, language='es') self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_es_search(self, mock_filter): get_or_create_page(", "= 1 mock_filter.return_value = mock_queryset response = self.client.get(reverse( 'ask-search-en-json', kwargs={'as_json':", "'/ask-cfpb/category-my_category/') def test_redirect_search_with_audience(self): audience_querystring = ( 'selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2') request =", "language='en', live=True) self.spanish_parent_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Obtener respuestas',", "= mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 0 mock_sqs_instance =", "override_settings from django.utils import timezone from wagtail.wagtailcore.models import Site from", "mock_return = mock.Mock() mock_return.url = \"inscisive_url.com\" mock_return.autocomplete = \"inscisive question\"", "HttpRequest() request.GET['selected_facets'] = 'category_exact:my_categoria' redirect_ask_search(request, language='es') self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def", "'ask_cfpb', 'AnswerLandingPage', 'Obtener respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) self.test_answer =", "redirect_ask_search(request) self.assertEqual(result.get('location'), '/ask-cfpb/category-my_category/') def test_redirect_search_with_audience(self): audience_querystring = ( 'selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2')", "self.english_parent_page, language='en', live=True) mock_return = mock.Mock() mock_return.url = \"inscisive_url.com\" mock_return.autocomplete", "mock.Mock() mock_queryset.count.return_value = 0 mock_filter.return_value = [mock_queryset] response = self.client.get(reverse(", "'url' mock_autocomplete.return_value = [mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-en'), {'term': 'question'})", "= 'mockcfpb.gov' mock_return.autocomplete = 'A mock question' mock_return.text = 'Mock", "is_default_site=True) self.sharing_site = mommy.make( SharingSite, site=self.site, hostname='preview.localhost', port=8000) @mock.patch('ask_cfpb.views.ServeView.serve_latest_revision') def", "def test_bad_language_search(self): with self.assertRaises(NoReverseMatch): self.client.get(reverse( 'ask-search-en', kwargs={'language': 'zz'}), {'q': 'payday'})", "self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-spanish-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_json_response(self, mock_filter): get_or_create_page( apps, 'ask_cfpb',", "( 'selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2') request = HttpRequest() request.GET = QueryDict(audience_querystring) result", "self.ROOT_PAGE, language='en', live=True) self.spanish_parent_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Obtener", "[mock_queryset] response = self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='en',", "redirect_ask_search(request) def test_redirect_search_no_query(self): request = HttpRequest() request.GET['q'] = ' '", "django.core.urlresolvers import NoReverseMatch, reverse from django.http import Http404, HttpRequest, QueryDict", "mock_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results',", "= ' ' with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_with_category(self): category_querystring =", "output = json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question', 'url']) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_es(self,", "mock_filter): mock_queryset = mock.Mock() mock_queryset.count.return_value = 0 mock_filter.return_value = [mock_queryset]", "test_es_search(self, mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock Spanish results page',", "with self.assertRaises(RuntimeError) as context: annotate_links('answer') self.assertIn('no default wagtail site', str(context.exception))", "result = self.client.get(reverse( 'ask-autocomplete-en'), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output =", "= HttpRequest() request.GET['selected_facets'] = '' with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_no_query(self):", "'' with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_no_query(self): request = HttpRequest() request.GET['q']", "def test_redirect_search_no_query(self): request = HttpRequest() request.GET['q'] = ' ' with", "from ask_cfpb.views import annotate_links, ask_search, redirect_ask_search from v1.util.migrations import get_or_create_page", "= mommy.make( SharingSite, site=self.site, hostname='preview.localhost', port=8000) @mock.patch('ask_cfpb.views.ServeView.serve_latest_revision') def test_preview_page(self, mock_serve):", "question.\", slug='test-question', update_english_page=True, update_spanish_page=False) self.site = mommy.make( Site, root_page=self.ROOT_PAGE, hostname='localhost',", "mock.Mock() mock_search_result.autocomplete = 'question' mock_search_result.url = 'url' mock_autocomplete.return_value = [mock_search_result]", "= get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.english_parent_page,", "def test_redirect_search_with_audience(self): audience_querystring = ( 'selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2') request = HttpRequest()", "apps, 'ask_cfpb', 'AnswerLandingPage', 'Obtener respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) self.test_answer", "= HttpRequest() request.GET = QueryDict(category_querystring) result = redirect_ask_search(request) self.assertEqual(result.get('location'), '/ask-cfpb/category-my_category/')", "'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:spanishtag2'.format(target_tag)) request = HttpRequest() request.GET = QueryDict(tag_querystring) result =", "\"inscisive question\" mock_return.text = \"inscisive text\" mock_queryset = mock.Mock() mock_queryset.__iter__", "= mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_filter.return_value =", "test_search_page_en_selection(self, mock_filter): page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results", "test_search_page_es_selection(self, mock_filter): page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock Spanish", "annotate_links, ask_search, redirect_ask_search from v1.util.migrations import get_or_create_page now = timezone.now()", "= 'hoodoo' redirect_ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_spanish_redirect_ask_search_passes_query_string( self, mock_redirect):", "mommy.make( Answer, answer=\"Test answer.\", question=\"Test question.\", slug='test-question', update_english_page=True, update_spanish_page=False) self.site", "mock_page) self.assertEqual(response_page.suggestion, 'paydya') self.assertEqual(response_page.result_query, 'payday') self.assertEqual(response_page.query, 'paydya') @mock.patch('ask_cfpb.views.redirect_ask_search') def test_ask_search_encounters_facets(self,", "(annotated_answer, links) = annotate_links(mock_answer) self.assertEqual(links, []) def test_annotate_links_no_site(self): site =", "= '' with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_no_query(self): request = HttpRequest()", "response = self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='en', q='payday'))", "'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.english_parent_page, language='en', live=True) mock_return", "= [mock_queryset] response = self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1)", "'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') mock_return = mock.Mock()", "mock_search_result = mock.Mock() mock_search_result.autocomplete = 'question' mock_search_result.url = 'url' mock_autocomplete.return_value", "from v1.models import HomePage self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page = get_or_create_page(", "self.assertEqual( response.context_data['page'].query, '') self.assertEqual( response.context_data['page'].result_query, '') @override_settings(FLAGS={'ASK_SEARCH_TYPOS': {'boolean': True}}) @mock.patch('ask_cfpb.views.SearchQuerySet')", "mock_return.url = \"inscisive_url.com\" mock_return.autocomplete = \"inscisive question\" mock_return.text = \"inscisive", "@mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_en_search_results_page_not_created(self, mock_filter): mock_queryset = mock.Mock() mock_queryset.count.return_value = 0", "'Mock answer text.' mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value", "hostname='localhost', port=8000, is_default_site=True) self.sharing_site = mommy.make( SharingSite, site=self.site, hostname='preview.localhost', port=8000)", "{'boolean': True}}) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_suggestion(self, mock_sqs): from v1.util.migrations import get_or_create_page", "'category_exact:my_category' ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_redirect_ask_search_passes_query_string(self, mock_redirect): request =", "mock_queryset self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='es',", "'url' mock_autocomplete.return_value = [mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}),", "mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset response = self.client.get(reverse(", "revision.publish() test_request = HttpRequest() test_request.META['SERVER_NAME'] = 'preview.localhost' test_request.META['SERVER_PORT'] = 8000", "= self.client.get(reverse( 'ask-autocomplete-en'), {'term': ''}) output = json.loads(result.content) self.assertEqual(output, [])", "self.assertEqual(mock_autocomplete.call_count, 1) output = json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question', 'url']) class", "'<p>Answer with a <a href=\"http://fake.com\">fake link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer)", "target_tag = 'spanishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:spanishtag2'.format(target_tag)) request =", "mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value = mock_queryset mock_sqs_instance.spelling_suggestion.return_value = 'payday' response", "self.spanish_parent_page, language='es', live=True) mock_return = mock.Mock() mock_return.url = 'url' mock_return.autocomplete", "test_redirect_search_no_facets(self): request = HttpRequest() with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_blank_facets(self): request", "self.assertEqual( response.context_data['page'].result_query, '') @override_settings(FLAGS={'ASK_SEARCH_TYPOS': {'boolean': True}}) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_suggestion(self, mock_sqs):", "self.assertEqual( sorted(output[0].keys()), ['question', 'url']) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_es(self, mock_autocomplete): mock_search_result =", "from django.test import TestCase, override_settings from django.utils import timezone from", "with self.assertRaises(Http404): view_answer( test_request, 'test-question', 'en', self.test_answer.pk) class AnswerViewTestCase(TestCase): def", "self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].query, '') self.assertEqual( response.context_data['page'].result_query, '') @override_settings(FLAGS={'ASK_SEARCH_TYPOS':", "@mock.patch('ask_cfpb.views.redirect_ask_search') def test_ask_search_encounters_facets(self, mock_redirect): request = HttpRequest() request.GET['selected_facets'] = 'category_exact:my_category'", "request = HttpRequest() request.GET['selected_facets'] = 'category_exact:my_category' ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect')", "1) self.assertEqual(page.language, 'en') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def", "'ask-search-es', kwargs={'language': 'es'}), {'q': 'hipotecas'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'es') self.assertEqual(page.answers,", "class AnswerPagePreviewCase(TestCase): def setUp(self): from v1.models import HomePage from ask_cfpb.models", "= 'category_exact:my_categoria' redirect_ask_search(request, language='es') self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_es_search(self, mock_filter):", "json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question', 'url']) class RedirectAskSearchTestCase(TestCase): def test_redirect_search_no_facets(self): request", "self.assertEqual( sorted(output[0].keys()), ['question', 'url']) class RedirectAskSearchTestCase(TestCase): def test_redirect_search_no_facets(self): request =", "mommy.make( SharingSite, site=self.site, hostname='preview.localhost', port=8000) @mock.patch('ask_cfpb.views.ServeView.serve_latest_revision') def test_preview_page(self, mock_serve): from", "@mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_es_selection(self, mock_filter): page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage',", "mock_filter.return_value = mock_queryset response = self.client.get(reverse( 'ask-search-en-json', kwargs={'as_json': 'json'}), {'q':", "model_mommy import mommy from ask_cfpb.models import ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG from ask_cfpb.views", "@mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_es_search(self, mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock Spanish", "mock_sqs): from v1.util.migrations import get_or_create_page mock_page = get_or_create_page( apps, 'ask_cfpb',", "result.get('location'), '/ask-cfpb/search-by-tag/{}/'.format( target_tag)) def test_redirect_search_with_unrecognized_facet_raises_404(self): querystring = \\ 'sort=-updated_at&selected_facets=imtkfidycqszgfdb&page=60' request", "redirect_ask_search(request, language='es') self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_es_search(self, mock_filter): get_or_create_page( apps,", "= mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_sqs_instance =", "= [mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': 'question'})", "'&selected_facets=category_exact:my_category2' '&selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2' '&selected_facets=tag_exact:mytag1' '&selected_facets=tag_exact:mytag2') request = HttpRequest() request.GET =", "mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_filter.return_value", "def test_annotate_links_no_href(self): mock_answer = ( '<p>Answer with a <a>fake link.</a></p>')", "mock from model_mommy import mommy from ask_cfpb.models import ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG", "annotated_answer, '<html><body><p>Answer with a <a href=\"http://fake.com\">fake ' 'link.</a><sup>1</sup></p></body></html>') self.assertEqual(links, [(1,", "'ask-cfpb-search-results', self.english_parent_page, language='en', live=True) mock_return = mock.Mock() mock_return.url = 'url'", "= json.loads(result.content) self.assertEqual(output, []) def test_autocomplete_es_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-es',", "'url']) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_es(self, mock_autocomplete): mock_search_result = mock.Mock() mock_search_result.autocomplete =", "= redirect_ask_search(request) self.assertEqual(result.get('location'), '/ask-cfpb/category-my_category/') def test_redirect_search_with_audience(self): audience_querystring = ( 'selected_facets=audience_exact:Older+Americans'", "question=\"Test question.\", slug='test-question', update_english_page=True, update_spanish_page=False) self.site = mommy.make( Site, root_page=self.ROOT_PAGE,", "= ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:englishtag2'.format(target_tag)) request = HttpRequest() request.GET = QueryDict(tag_querystring)", "redirect_ask_search(request, language='en') self.assertEqual( result.get('location'), '/ask-cfpb/search-by-tag/{}/'.format( target_tag)) def test_redirect_search_with_unrecognized_facet_raises_404(self): querystring =", "def test_search_page_es_selection(self, mock_filter): page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock", "self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_blank_facets(self): request = HttpRequest() request.GET['selected_facets'] = ''", "= mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value =", "q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_no_term(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page", "mock_redirect): request = HttpRequest() request.GET['selected_facets'] = 'category_exact:my_categoria' redirect_ask_search(request, language='es') self.assertEqual(mock_redirect.call_count,", "'payday'}) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_en_search_results_page_not_created(self, mock_filter): mock_queryset = mock.Mock() mock_queryset.count.return_value =", "= redirect_ask_search(request, language='es') self.assertEqual( result.get('location'), '/es/obtener-respuestas/buscar-por-etiqueta/{}/'.format( target_tag)) def test_english_redirect_search_with_tag(self): target_tag", "200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].query, '') self.assertEqual( response.context_data['page'].result_query, '')", "Site, root_page=self.ROOT_PAGE, hostname='localhost', port=8000, is_default_site=True) self.sharing_site = mommy.make( SharingSite, site=self.site,", "test_annotate_links_no_href(self): mock_answer = ( '<p>Answer with a <a>fake link.</a></p>') (annotated_answer,", "request.GET['q'] = ' ' with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_with_category(self): category_querystring", "( 'selected_facets=category_exact:my_category' '&selected_facets=category_exact:my_category2' '&selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2' '&selected_facets=tag_exact:mytag1' '&selected_facets=tag_exact:mytag2') request = HttpRequest()", "'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='en', q='payday')) self.assertEqual(response.status_code, 404) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search(self,", "response.context_data['page'].suggestion, None) self.assertEqual(mock_sqs_instance.filter.call_count, 1) self.assertTrue(mock_sqs_instance.filter.called_with( language='en', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_no_term(self,", "kwargs={'as_json': 'json'}), {'q': 'tuition'}) self.assertEqual(response.status_code, 200) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(json.loads(response.content)['query'], 'tuition')", "target_tag = 'englishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:englishtag2'.format(target_tag)) request =", "from v1.util.migrations import get_or_create_page now = timezone.now() class AnswerPagePreviewCase(TestCase): def", "apps, 'ask_cfpb', 'AnswerLandingPage', 'Ask CFPB', ENGLISH_PARENT_SLUG, self.ROOT_PAGE, language='en', live=True) self.spanish_parent_page", "<a href=\"http://fake.com\">fake link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer) self.assertEqual( annotated_answer, '<html><body><p>Answer", "now = timezone.now() class AnswerPagePreviewCase(TestCase): def setUp(self): from v1.models import", "= 'A mock question' mock_return.text = 'Mock answer text.' mock_queryset", "mock_return.text = 'Mock answer text.' mock_queryset = mock.Mock() mock_queryset.__iter__ =", "'ask-search-en'), {'q': ''}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].query,", "request = HttpRequest() request.GET['selected_facets'] = '' with self.assertRaises(Http404): redirect_ask_search(request) def", "request = HttpRequest() request.GET['selected_facets'] = 'category_exact:my_categoria' redirect_ask_search(request, language='es') self.assertEqual(mock_redirect.call_count, 1)", "test_preview_page(self, mock_serve): from ask_cfpb.views import view_answer page = self.test_answer.english_page revision", "['question', 'url']) class RedirectAskSearchTestCase(TestCase): def test_redirect_search_no_facets(self): request = HttpRequest() with", "mock_autocomplete.return_value = [mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term':", "self.assertEqual(mock_autocomplete.call_count, 1) output = json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question', 'url']) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete')", "{'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='en', q='payday')) self.assertEqual(response.status_code, 404) @mock.patch('ask_cfpb.views.SearchQuerySet') def", "def test_search_page_en_selection(self, mock_filter): page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock", "test_request = HttpRequest() with self.assertRaises(Http404): view_answer( test_request, 'test-question', 'en', self.test_answer.pk)", "self.assertRaises(NoReverseMatch): self.client.get(reverse( 'ask-search-en', kwargs={'language': 'zz'}), {'q': 'payday'}) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_en_search_results_page_not_created(self,", "def test_spanish_redirect_ask_search_passes_query_string( self, mock_redirect): request = HttpRequest() request.GET['selected_facets'] = 'category_exact:my_categoria'", "mock_queryset = mock.Mock() mock_queryset.count.return_value = 0 mock_filter.return_value = [mock_queryset] response", "= mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value = mock_queryset mock_sqs_instance.spelling_suggestion.return_value = 'payday' response =", "self.client.get(reverse( 'ask-search-en'), {'q': ''}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual(", "from wagtail.wagtailcore.models import Site from wagtailsharing.models import SharingSite import mock", "mock.Mock() mock_return.url = 'url' mock_return.autocomplete = 'question text' mock_queryset =", "''}) output = json.loads(result.content) self.assertEqual(output, []) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_en(self, mock_autocomplete):", "self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_no_query(self): request = HttpRequest() request.GET['q'] = '", "self.english_parent_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Ask CFPB', ENGLISH_PARENT_SLUG, self.ROOT_PAGE,", "site=self.site, hostname='preview.localhost', port=8000) @mock.patch('ask_cfpb.views.ServeView.serve_latest_revision') def test_preview_page(self, mock_serve): from ask_cfpb.views import", "hostname='preview.localhost', port=8000) @mock.patch('ask_cfpb.views.ServeView.serve_latest_revision') def test_preview_page(self, mock_serve): from ask_cfpb.views import view_answer", "q='payday')) self.assertEqual(response.status_code, 404) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search(self, mock_sqs): from v1.util.migrations import", "False page.save() test_request = HttpRequest() with self.assertRaises(Http404): view_answer( test_request, 'test-question',", "mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 0 mock_sqs_instance = mock_sqs.return_value.models.return_value", "self.assertEqual(response_page.result_query, 'payday') self.assertEqual(response_page.query, 'paydya') @mock.patch('ask_cfpb.views.redirect_ask_search') def test_ask_search_encounters_facets(self, mock_redirect): request =", "= HttpRequest() request.GET['q'] = 'hoodoo' redirect_ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def", "from django.apps import apps from django.core.urlresolvers import NoReverseMatch, reverse from", "= redirect_ask_search(request) self.assertEqual( result.get('location'), '/ask-cfpb/audience-older-americans/') def test_spanish_redirect_search_with_tag(self): target_tag = 'spanishtag1'", "\"inscisive text\" mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value =", "= ( 'selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2') request = HttpRequest() request.GET = QueryDict(audience_querystring)", "HttpRequest() request.GET = QueryDict(audience_querystring) result = redirect_ask_search(request) self.assertEqual( result.get('location'), '/ask-cfpb/audience-older-americans/')", "mock_filter.return_value = [mock_queryset] response = self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(mock_filter.call_count,", "from wagtailsharing.models import SharingSite import mock from model_mommy import mommy", "mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_sqs_instance = mock_sqs.return_value.models.return_value", "'') self.assertEqual( response.context_data['page'].result_query, '') @override_settings(FLAGS={'ASK_SEARCH_TYPOS': {'boolean': True}}) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_suggestion(self,", "= HttpRequest() request.GET['selected_facets'] = 'category_exact:my_categoria' redirect_ask_search(request, language='es') self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.SearchQuerySet.filter')", "Http404, HttpRequest, QueryDict from django.test import TestCase, override_settings from django.utils", "= HttpRequest() with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_blank_facets(self): request = HttpRequest()", "import Http404, HttpRequest, QueryDict from django.test import TestCase, override_settings from", "test_autocomplete_en_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-en'), {'term': ''}) output = json.loads(result.content)", "unicode_literals import json from django.apps import apps from django.core.urlresolvers import", "'ask-cfpb-search-results', self.ROOT_PAGE, language='en') response = self.client.get(reverse( 'ask-search-en'), {'q': ''}) self.assertEqual(response.status_code,", "def test_redirect_search_blank_facets(self): request = HttpRequest() request.GET['selected_facets'] = '' with self.assertRaises(Http404):", "'es'}), {'q': 'hipotecas'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'es') self.assertEqual(page.answers, []) self.assertEqual(", "result = self.client.get(reverse( 'ask-autocomplete-en'), {'term': ''}) output = json.loads(result.content) self.assertEqual(output,", "@mock.patch('ask_cfpb.views.redirect') def test_redirect_ask_search_passes_query_string(self, mock_redirect): request = HttpRequest() request.GET['q'] = 'hoodoo'", "kwargs={'language': 'zz'}), {'q': 'payday'}) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_en_search_results_page_not_created(self, mock_filter): mock_queryset =", "self.assertEqual(links, []) def test_annotate_links_no_site(self): site = Site.objects.get(is_default_site=True) site.is_default_site = False", "ask_cfpb.views import view_answer page = self.test_answer.english_page page.live = False page.save()", "= get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Obtener respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es',", "response = self.client.get(reverse( 'ask-search-en-json', kwargs={'as_json': 'json'}), {'q': 'tuition'}) self.assertEqual(response.status_code, 200)", "mommy.make( Site, root_page=self.ROOT_PAGE, hostname='localhost', port=8000, is_default_site=True) self.sharing_site = mommy.make( SharingSite,", "Site.objects.get(is_default_site=True) site.is_default_site = False site.save() with self.assertRaises(RuntimeError) as context: annotate_links('answer')", "page = self.test_answer.english_page page.live = False page.save() test_request = HttpRequest()", "= json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question', 'url']) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_es(self, mock_autocomplete):", "= QueryDict(category_querystring) result = redirect_ask_search(request) self.assertEqual(result.get('location'), '/ask-cfpb/category-my_category/') def test_redirect_search_with_audience(self): audience_querystring", "mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock Spanish results page', 'respuestas',", "= 1 mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-en'), {'q': 'tuition'}) self.assertEqual(mock_filter.call_count,", "kwargs={'language': 'es'}), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='es', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def", "ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_redirect_ask_search_passes_query_string(self, mock_redirect): request = HttpRequest()", "view_answer( test_request, 'test-question', 'en', self.test_answer.pk) self.assertEqual(mock_serve.call_count, 1) def test_answer_page_not_live(self): from", "HttpRequest() test_request.META['SERVER_NAME'] = 'preview.localhost' test_request.META['SERVER_PORT'] = 8000 view_answer( test_request, 'test-question',", "mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-en'), {'q': 'tuition'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language,", "slug='test-question', update_english_page=True, update_spanish_page=False) self.site = mommy.make( Site, root_page=self.ROOT_PAGE, hostname='localhost', port=8000,", "= redirect_ask_search(request, language='en') self.assertEqual( result.get('location'), '/ask-cfpb/search-by-tag/{}/'.format( target_tag)) def test_redirect_search_with_unrecognized_facet_raises_404(self): querystring", "self.assertEqual(mock_serve.call_count, 1) def test_answer_page_not_live(self): from ask_cfpb.views import view_answer page =", "get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en')", "'ask-cfpb/answer-search-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_es_selection(self, mock_filter): page = get_or_create_page( apps, 'ask_cfpb',", "self.english_parent_page, language='en', live=True) mock_return = mock.Mock() mock_return.url = 'url' mock_return.autocomplete", "answer text.' mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value =", "self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].query, '') self.assertEqual( response.context_data['page'].result_query,", "test_request, 'test-question', 'en', self.test_answer.pk) class AnswerViewTestCase(TestCase): def setUp(self): from v1.models", "1) self.assertTrue(mock_sqs_instance.filter.called_with( language='en', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_no_term(self, mock_sqs): from v1.util.migrations", "result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': ''}) output =", "'&selected_facets=tag_exact:mytag2') request = HttpRequest() request.GET = QueryDict(category_querystring) result = redirect_ask_search(request)", "response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].suggestion, None) self.assertEqual(mock_sqs_instance.filter.call_count, 1) self.assertTrue(mock_sqs_instance.filter.called_with( language='en', q='payday'))", "= \"inscisive text\" mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value", "request = HttpRequest() request.GET = QueryDict(category_querystring) result = redirect_ask_search(request) self.assertEqual(result.get('location'),", "'ask-search-en-json', kwargs={'as_json': 'json'}), {'q': 'tuition'}) self.assertEqual(response.status_code, 200) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(json.loads(response.content)['query'],", "mock_queryset self.client.get(reverse( 'ask-search-en'), {'q': 'tuition'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'en') self.assertEqual(page.answers,", "= ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:spanishtag2'.format(target_tag)) request = HttpRequest() request.GET = QueryDict(tag_querystring)", "'sort=-updated_at&selected_facets=imtkfidycqszgfdb&page=60' request = HttpRequest() request.GET = QueryDict(querystring) with self.assertRaises(Http404): redirect_ask_search(request)", "mock_answer = ( '<p>Answer with a <a>fake link.</a></p>') (annotated_answer, links)", "= annotate_links(mock_answer) self.assertEqual(links, []) def test_annotate_links_no_site(self): site = Site.objects.get(is_default_site=True) site.is_default_site", "HttpRequest() request.GET['selected_facets'] = '' with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_no_query(self): request", "'question text' mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value =", "1) self.assertTrue(mock_filter.called_with(language='en', q='payday')) self.assertEqual(response.status_code, 404) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search(self, mock_sqs): from", "{'term': ''}) output = json.loads(result.content) self.assertEqual(output, []) def test_autocomplete_es_blank_term(self): result", "def test_redirect_ask_search_passes_query_string(self, mock_redirect): request = HttpRequest() request.GET['q'] = 'hoodoo' redirect_ask_search(request)", "@mock.patch('ask_cfpb.views.ServeView.serve_latest_revision') def test_preview_page(self, mock_serve): from ask_cfpb.views import view_answer page =", "output = json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question', 'url']) class RedirectAskSearchTestCase(TestCase): def", "Answer self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage',", "links) = annotate_links(mock_answer) self.assertEqual(links, []) def test_annotate_links_no_site(self): site = Site.objects.get(is_default_site=True)", "self.test_answer = mommy.make( Answer, answer=\"Test answer.\", question=\"Test question.\", slug='test-question', update_english_page=True,", "1 mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}), {'q': 'hipotecas'})", "self.assertEqual( result.get('location'), '/ask-cfpb/audience-older-americans/') def test_spanish_redirect_search_with_tag(self): target_tag = 'spanishtag1' tag_querystring =", "mock_queryset.count.return_value = 0 mock_filter.return_value = [mock_queryset] response = self.client.get(reverse( 'ask-search-en'),", "language='en') response = self.client.get(reverse( 'ask-search-en'), {'q': ''}) self.assertEqual(response.status_code, 200) self.assertEqual(", "self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].suggestion, None) self.assertEqual(mock_sqs_instance.filter.call_count, 1)", "text' mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1", "'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': ''}) output = json.loads(result.content) self.assertEqual(output, [])", "'/ask-cfpb/audience-older-americans/') def test_spanish_redirect_search_with_tag(self): target_tag = 'spanishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}'", "target_tag)) def test_english_redirect_search_with_tag(self): target_tag = 'englishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}'", "ask_cfpb.models import ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG from ask_cfpb.views import annotate_links, ask_search, redirect_ask_search", "a <a>fake link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer) self.assertEqual(links, []) def", "'paydya') @mock.patch('ask_cfpb.views.redirect_ask_search') def test_ask_search_encounters_facets(self, mock_redirect): request = HttpRequest() request.GET['selected_facets'] =", "page.get_template(HttpRequest()), 'ask-cfpb/answer-search-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_es_selection(self, mock_filter): page = get_or_create_page( apps,", "= self.client.get(reverse( 'ask-search-en-json', kwargs={'as_json': 'json'}), {'q': 'tuition'}) self.assertEqual(response.status_code, 200) self.assertEqual(mock_filter.call_count,", "def test_redirect_search_with_unrecognized_facet_raises_404(self): querystring = \\ 'sort=-updated_at&selected_facets=imtkfidycqszgfdb&page=60' request = HttpRequest() request.GET", "1 mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}), {'q': 'payday'})", "def test_en_search(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page = get_or_create_page(", "'ask_cfpb', 'AnswerResultsPage', 'Mock Spanish results page', 'respuestas', self.spanish_parent_page, language='es', live=True)", "view_answer page = self.test_answer.english_page revision = page.save_revision() revision.publish() test_request =", "live=True) def test_annotate_links(self): mock_answer = ( '<p>Answer with a <a", "response = self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'],", "sorted(output[0].keys()), ['question', 'url']) class RedirectAskSearchTestCase(TestCase): def test_redirect_search_no_facets(self): request = HttpRequest()", "language='es', live=True) def test_annotate_links(self): mock_answer = ( '<p>Answer with a", "page', 'respuestas', self.spanish_parent_page, language='es', live=True) mock_return = mock.Mock() mock_return.url =", "NoReverseMatch, reverse from django.http import Http404, HttpRequest, QueryDict from django.test", "'Obtener respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) def test_annotate_links(self): mock_answer =", "get_or_create_page mock_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page',", "'es'}), {'term': ''}) output = json.loads(result.content) self.assertEqual(output, []) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def", "question' mock_return.text = 'Mock answer text.' mock_queryset = mock.Mock() mock_queryset.__iter__", "= 'englishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:englishtag2'.format(target_tag)) request = HttpRequest()", "<a href=\"http://fake.com\">fake ' 'link.</a><sup>1</sup></p></body></html>') self.assertEqual(links, [(1, str('http://fake.com'))]) def test_annotate_links_no_href(self): mock_answer", "self.assertEqual(page.language, 'es') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-spanish-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_json_response(self,", "mock_redirect): request = HttpRequest() request.GET['q'] = 'hoodoo' redirect_ask_search(request) self.assertEqual(mock_redirect.call_count, 1)", "request = HttpRequest() request.GET['q'] = ' ' with self.assertRaises(Http404): redirect_ask_search(request)", "self.ROOT_PAGE, language='en') mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov' mock_return.autocomplete =", "{'q': 'paydya'}) self.assertEqual(response.status_code, 200) response_page = response.context_data['page'] self.assertEqual(response_page, mock_page) self.assertEqual(response_page.suggestion,", "1) self.assertTrue(mock_filter.called_with(language='es', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_en_selection(self, mock_filter): page = get_or_create_page(", "HttpRequest() request.GET = QueryDict(tag_querystring) result = redirect_ask_search(request, language='en') self.assertEqual( result.get('location'),", "AnswerPagePreviewCase(TestCase): def setUp(self): from v1.models import HomePage from ask_cfpb.models import", "= HttpRequest() request.GET = QueryDict(tag_querystring) result = redirect_ask_search(request, language='es') self.assertEqual(", "text.' mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1", "= HttpRequest() with self.assertRaises(Http404): view_answer( test_request, 'test-question', 'en', self.test_answer.pk) class", "'hoodoo' redirect_ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_spanish_redirect_ask_search_passes_query_string( self, mock_redirect): request", "'es') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-spanish-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_json_response(self, mock_filter):", "language='es', live=True) self.test_answer = mommy.make( Answer, answer=\"Test answer.\", question=\"Test question.\",", "request = HttpRequest() with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_blank_facets(self): request =", "HomePage from ask_cfpb.models import Answer self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page =", "ENGLISH_PARENT_SLUG, self.ROOT_PAGE, language='en', live=True) self.spanish_parent_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage',", "wagtailsharing.models import SharingSite import mock from model_mommy import mommy from", "'Obtener respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) self.test_answer = mommy.make( Answer,", "self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output =", "page', 'ask-cfpb-search-results', self.english_parent_page, language='en', live=True) mock_return = mock.Mock() mock_return.url =", "= \"inscisive_url.com\" mock_return.autocomplete = \"inscisive question\" mock_return.text = \"inscisive text\"", "SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) def test_annotate_links(self): mock_answer = ( '<p>Answer", "wagtail.wagtailcore.models import Site from wagtailsharing.models import SharingSite import mock from", "{'q': 'hipotecas'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'es') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()),", "'url' mock_return.autocomplete = 'question text' mock_queryset = mock.Mock() mock_queryset.__iter__ =", "'ask_cfpb', 'AnswerLandingPage', 'Ask CFPB', ENGLISH_PARENT_SLUG, self.ROOT_PAGE, language='en', live=True) self.spanish_parent_page =", "self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'es') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-spanish-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter')", "from model_mommy import mommy from ask_cfpb.models import ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG from", "import HomePage from ask_cfpb.models import Answer self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page", "HomePage.objects.get(slug='cfgov') self.english_parent_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Ask CFPB', ENGLISH_PARENT_SLUG,", "import view_answer page = self.test_answer.english_page revision = page.save_revision() revision.publish() test_request", "'en', self.test_answer.pk) self.assertEqual(mock_serve.call_count, 1) def test_answer_page_not_live(self): from ask_cfpb.views import view_answer", "\"inscisive_url.com\" mock_return.autocomplete = \"inscisive question\" mock_return.text = \"inscisive text\" mock_queryset", "output = json.loads(result.content) self.assertEqual(output, []) def test_autocomplete_es_blank_term(self): result = self.client.get(reverse(", "django.test import TestCase, override_settings from django.utils import timezone from wagtail.wagtailcore.models", "mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset", "page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock Spanish results page',", "mock_sqs_instance.filter.return_value = mock_queryset mock_sqs_instance.spelling_suggestion.return_value = 'payday' response = self.client.get(reverse( 'ask-search-en'),", "mock_search_result.url = 'url' mock_autocomplete.return_value = [mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-en'),", "1) output = json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question', 'url']) class RedirectAskSearchTestCase(TestCase):", "json.loads(result.content) self.assertEqual(output, []) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_en(self, mock_autocomplete): mock_search_result = mock.Mock()", "mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value", "test_redirect_search_with_unrecognized_facet_raises_404(self): querystring = \\ 'sort=-updated_at&selected_facets=imtkfidycqszgfdb&page=60' request = HttpRequest() request.GET =", "test_en_search_suggestion(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page = get_or_create_page( apps,", "' ' with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_with_category(self): category_querystring = (", "= ( '<p>Answer with a <a>fake link.</a></p>') (annotated_answer, links) =", "= QueryDict(tag_querystring) result = redirect_ask_search(request, language='es') self.assertEqual( result.get('location'), '/es/obtener-respuestas/buscar-por-etiqueta/{}/'.format( target_tag))", "link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer) self.assertEqual( annotated_answer, '<html><body><p>Answer with a", "import mommy from ask_cfpb.models import ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG from ask_cfpb.views import", "'paydya'}) self.assertEqual(response.status_code, 200) response_page = response.context_data['page'] self.assertEqual(response_page, mock_page) self.assertEqual(response_page.suggestion, 'paydya')", "'A mock question' mock_return.text = 'Mock answer text.' mock_queryset =", "def test_spanish_redirect_search_with_tag(self): target_tag = 'spanishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:spanishtag2'.format(target_tag))", "request = HttpRequest() request.GET = QueryDict(tag_querystring) result = redirect_ask_search(request, language='es')", "' with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_with_category(self): category_querystring = ( 'selected_facets=category_exact:my_category'", "mock_page) self.assertEqual( response.context_data['page'].suggestion, None) self.assertEqual(mock_sqs_instance.filter.call_count, 1) self.assertTrue(mock_sqs_instance.filter.called_with( language='en', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet')", "self.assertTrue(mock_sqs_instance.filter.called_with( language='en', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_no_term(self, mock_sqs): from v1.util.migrations import", "@mock.patch('ask_cfpb.views.redirect') def test_spanish_redirect_ask_search_passes_query_string( self, mock_redirect): request = HttpRequest() request.GET['selected_facets'] =", "with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_blank_facets(self): request = HttpRequest() request.GET['selected_facets'] =", "= get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock Spanish results page', 'respuestas',", "= mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-en'),", "'hipotecas'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'es') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-spanish-results.html')", "'ask-cfpb-search-results', self.english_parent_page, language='en', live=True) mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov'", "mock_return.url = 'url' mock_return.autocomplete = 'question text' mock_queryset = mock.Mock()", "from v1.models import HomePage from ask_cfpb.models import Answer self.ROOT_PAGE =", "apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.english_parent_page, language='en', live=True)", "page.get_template(HttpRequest()), 'ask-cfpb/answer-search-spanish-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_json_response(self, mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage',", "= self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output", "Answer, answer=\"Test answer.\", question=\"Test question.\", slug='test-question', update_english_page=True, update_spanish_page=False) self.site =", "HomePage self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage',", "self.ROOT_PAGE, language='es', live=True) self.test_answer = mommy.make( Answer, answer=\"Test answer.\", question=\"Test", "ask_cfpb.views import view_answer page = self.test_answer.english_page revision = page.save_revision() revision.publish()", "= 'url' mock_autocomplete.return_value = [mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-en'), {'term':", "from __future__ import unicode_literals import json from django.apps import apps", "self.test_answer.pk) class AnswerViewTestCase(TestCase): def setUp(self): from v1.models import HomePage self.ROOT_PAGE", "language='en', live=True) mock_return = mock.Mock() mock_return.url = 'url' mock_return.autocomplete =", "result = redirect_ask_search(request) self.assertEqual(result.get('location'), '/ask-cfpb/category-my_category/') def test_redirect_search_with_audience(self): audience_querystring = (", "mock.Mock() mock_return.url = \"inscisive_url.com\" mock_return.autocomplete = \"inscisive question\" mock_return.text =", "text\" mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1", "200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].suggestion, None) self.assertEqual(mock_sqs_instance.filter.call_count, 1) self.assertTrue(mock_sqs_instance.filter.called_with(", "'json'}), {'q': 'tuition'}) self.assertEqual(response.status_code, 200) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(json.loads(response.content)['query'], 'tuition') def", "self.client.get(reverse( 'ask-search-en-json', kwargs={'as_json': 'json'}), {'q': 'tuition'}) self.assertEqual(response.status_code, 200) self.assertEqual(mock_filter.call_count, 1)", "respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) def test_annotate_links(self): mock_answer = (", "'AnswerLandingPage', 'Obtener respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) self.test_answer = mommy.make(", "'ask-autocomplete-en'), {'term': ''}) output = json.loads(result.content) self.assertEqual(output, []) def test_autocomplete_es_blank_term(self):", "self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Ask", "result.get('location'), '/ask-cfpb/audience-older-americans/') def test_spanish_redirect_search_with_tag(self): target_tag = 'spanishtag1' tag_querystring = (", "import json from django.apps import apps from django.core.urlresolvers import NoReverseMatch,", "= mock_queryset mock_sqs_instance.spelling_suggestion.return_value = 'payday' response = self.client.get(reverse( 'ask-search-en'), {'q':", "live=True) mock_return = mock.Mock() mock_return.url = \"inscisive_url.com\" mock_return.autocomplete = \"inscisive", "= self.client.get(reverse( 'ask-autocomplete-en'), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output = json.loads(result.content)", "self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_es_selection(self, mock_filter): page", "kwargs={'language': 'es'}), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output = json.loads(result.content) self.assertEqual(", "def test_autocomplete_en_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-en'), {'term': ''}) output =", "{'q': 'tuition'}) self.assertEqual(response.status_code, 200) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(json.loads(response.content)['query'], 'tuition') def test_autocomplete_en_blank_term(self):", "tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:spanishtag2'.format(target_tag)) request = HttpRequest() request.GET =", "( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:spanishtag2'.format(target_tag)) request = HttpRequest() request.GET = QueryDict(tag_querystring) result", "RedirectAskSearchTestCase(TestCase): def test_redirect_search_no_facets(self): request = HttpRequest() with self.assertRaises(Http404): redirect_ask_search(request) def", "category_querystring = ( 'selected_facets=category_exact:my_category' '&selected_facets=category_exact:my_category2' '&selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2' '&selected_facets=tag_exact:mytag1' '&selected_facets=tag_exact:mytag2') request", "self.test_answer.pk) self.assertEqual(mock_serve.call_count, 1) def test_answer_page_not_live(self): from ask_cfpb.views import view_answer page", "= mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-es',", "from django.http import Http404, HttpRequest, QueryDict from django.test import TestCase,", "import SharingSite import mock from model_mommy import mommy from ask_cfpb.models", "= 'category_exact:my_category' ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_redirect_ask_search_passes_query_string(self, mock_redirect): request", "= get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.ROOT_PAGE,", "django.http import Http404, HttpRequest, QueryDict from django.test import TestCase, override_settings", "mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value = mock_queryset", "mock_autocomplete): mock_search_result = mock.Mock() mock_search_result.autocomplete = 'question' mock_search_result.url = 'url'", "wagtail site', str(context.exception)) def test_bad_language_search(self): with self.assertRaises(NoReverseMatch): self.client.get(reverse( 'ask-search-en', kwargs={'language':", "= 8000 view_answer( test_request, 'test-question', 'en', self.test_answer.pk) self.assertEqual(mock_serve.call_count, 1) def", "= json.loads(result.content) self.assertEqual(output, []) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_en(self, mock_autocomplete): mock_search_result =", "str(context.exception)) def test_bad_language_search(self): with self.assertRaises(NoReverseMatch): self.client.get(reverse( 'ask-search-en', kwargs={'language': 'zz'}), {'q':", "test_redirect_search_with_audience(self): audience_querystring = ( 'selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2') request = HttpRequest() request.GET", "True}}) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_suggestion(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page", "'') @override_settings(FLAGS={'ASK_SEARCH_TYPOS': {'boolean': True}}) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_suggestion(self, mock_sqs): from v1.util.migrations", "= HttpRequest() request.GET['q'] = ' ' with self.assertRaises(Http404): redirect_ask_search(request) def", "'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='es', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_en_selection(self, mock_filter): page", "mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-en'), {'q':", "self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='es', q='payday'))", "language='en') mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov' mock_return.autocomplete = 'A", "audience_querystring = ( 'selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2') request = HttpRequest() request.GET =", "Site from wagtailsharing.models import SharingSite import mock from model_mommy import", "def test_en_search_results_page_not_created(self, mock_filter): mock_queryset = mock.Mock() mock_queryset.count.return_value = 0 mock_filter.return_value", "def setUp(self): from v1.models import HomePage from ask_cfpb.models import Answer", "redirect_ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_spanish_redirect_ask_search_passes_query_string( self, mock_redirect): request =", "apps, 'ask_cfpb', 'AnswerLandingPage', 'Obtener respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) def", "Spanish results page', 'respuestas', self.spanish_parent_page, language='es', live=True) mock_return = mock.Mock()", "self.client.get(reverse( 'ask-autocomplete-en'), {'term': ''}) output = json.loads(result.content) self.assertEqual(output, []) def", "= page.save_revision() revision.publish() test_request = HttpRequest() test_request.META['SERVER_NAME'] = 'preview.localhost' test_request.META['SERVER_PORT']", "self.assertEqual(page.language, 'en') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_es_selection(self,", "HttpRequest, QueryDict from django.test import TestCase, override_settings from django.utils import", "= mock.Mock() mock_return.url = 'mockcfpb.gov' mock_return.autocomplete = 'A mock question'", "'es'}), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='es', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_en_selection(self,", "test_ask_search_encounters_facets(self, mock_redirect): request = HttpRequest() request.GET['selected_facets'] = 'category_exact:my_category' ask_search(request) self.assertEqual(mock_redirect.call_count,", "v1.util.migrations import get_or_create_page now = timezone.now() class AnswerPagePreviewCase(TestCase): def setUp(self):", "mock_page) self.assertEqual( response.context_data['page'].query, '') self.assertEqual( response.context_data['page'].result_query, '') @override_settings(FLAGS={'ASK_SEARCH_TYPOS': {'boolean': True}})", "mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset response = self.client.get(reverse( 'ask-search-en-json',", "mock_queryset self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}), {'q': 'hipotecas'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language,", "live=True) self.test_answer = mommy.make( Answer, answer=\"Test answer.\", question=\"Test question.\", slug='test-question',", "import timezone from wagtail.wagtailcore.models import Site from wagtailsharing.models import SharingSite", "'paydya') self.assertEqual(response_page.result_query, 'payday') self.assertEqual(response_page.query, 'paydya') @mock.patch('ask_cfpb.views.redirect_ask_search') def test_ask_search_encounters_facets(self, mock_redirect): request", "import NoReverseMatch, reverse from django.http import Http404, HttpRequest, QueryDict from", "import Site from wagtailsharing.models import SharingSite import mock from model_mommy", "test_en_search_results_page_not_created(self, mock_filter): mock_queryset = mock.Mock() mock_queryset.count.return_value = 0 mock_filter.return_value =", "mock_queryset mock_sqs_instance.spelling_suggestion.return_value = 'payday' response = self.client.get(reverse( 'ask-search-en'), {'q': 'payday'})", "v1.models import HomePage from ask_cfpb.models import Answer self.ROOT_PAGE = HomePage.objects.get(slug='cfgov')", "= 'url' mock_return.autocomplete = 'question text' mock_queryset = mock.Mock() mock_queryset.__iter__", "mock_autocomplete.return_value = [mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-en'), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count,", "result.get('location'), '/es/obtener-respuestas/buscar-por-etiqueta/{}/'.format( target_tag)) def test_english_redirect_search_with_tag(self): target_tag = 'englishtag1' tag_querystring =", "'es'}), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output = json.loads(result.content) self.assertEqual( sorted(output[0].keys()),", "test_request.META['SERVER_NAME'] = 'preview.localhost' test_request.META['SERVER_PORT'] = 8000 view_answer( test_request, 'test-question', 'en',", "HttpRequest() request.GET = QueryDict(category_querystring) result = redirect_ask_search(request) self.assertEqual(result.get('location'), '/ask-cfpb/category-my_category/') def", "QueryDict(audience_querystring) result = redirect_ask_search(request) self.assertEqual( result.get('location'), '/ask-cfpb/audience-older-americans/') def test_spanish_redirect_search_with_tag(self): target_tag", "port=8000) @mock.patch('ask_cfpb.views.ServeView.serve_latest_revision') def test_preview_page(self, mock_serve): from ask_cfpb.views import view_answer page", "= mock_queryset self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}), {'q': 'hipotecas'}) self.assertEqual(mock_filter.call_count, 1)", "output = json.loads(result.content) self.assertEqual(output, []) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_en(self, mock_autocomplete): mock_search_result", "def test_en_search_suggestion(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page = get_or_create_page(", "from ask_cfpb.models import ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG from ask_cfpb.views import annotate_links, ask_search,", "mommy from ask_cfpb.models import ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG from ask_cfpb.views import annotate_links,", "= 1 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value = mock_queryset mock_sqs_instance.spelling_suggestion.return_value =", "'&selected_facets=tag_exact:mytag1' '&selected_facets=tag_exact:mytag2') request = HttpRequest() request.GET = QueryDict(category_querystring) result =", "import get_or_create_page mock_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results", "def test_annotate_links(self): mock_answer = ( '<p>Answer with a <a href=\"http://fake.com\">fake", "'englishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:englishtag2'.format(target_tag)) request = HttpRequest() request.GET", "AnswerViewTestCase(TestCase): def setUp(self): from v1.models import HomePage self.ROOT_PAGE = HomePage.objects.get(slug='cfgov')", "'ask-search-en'), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='en', q='payday')) self.assertEqual(response.status_code, 404) @mock.patch('ask_cfpb.views.SearchQuerySet')", "['question', 'url']) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_es(self, mock_autocomplete): mock_search_result = mock.Mock() mock_search_result.autocomplete", "result = redirect_ask_search(request, language='en') self.assertEqual( result.get('location'), '/ask-cfpb/search-by-tag/{}/'.format( target_tag)) def test_redirect_search_with_unrecognized_facet_raises_404(self):", "( '<p>Answer with a <a>fake link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer)", "= mock.Mock() mock_return.url = 'url' mock_return.autocomplete = 'question text' mock_queryset", "port=8000, is_default_site=True) self.sharing_site = mommy.make( SharingSite, site=self.site, hostname='preview.localhost', port=8000) @mock.patch('ask_cfpb.views.ServeView.serve_latest_revision')", "site', str(context.exception)) def test_bad_language_search(self): with self.assertRaises(NoReverseMatch): self.client.get(reverse( 'ask-search-en', kwargs={'language': 'zz'}),", "None) self.assertEqual(mock_sqs_instance.filter.call_count, 1) self.assertTrue(mock_sqs_instance.filter.called_with( language='en', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_no_term(self, mock_sqs):", "CFPB', ENGLISH_PARENT_SLUG, self.ROOT_PAGE, language='en', live=True) self.spanish_parent_page = get_or_create_page( apps, 'ask_cfpb',", "= timezone.now() class AnswerPagePreviewCase(TestCase): def setUp(self): from v1.models import HomePage", "self.assertRaises(Http404): view_answer( test_request, 'test-question', 'en', self.test_answer.pk) class AnswerViewTestCase(TestCase): def setUp(self):", "= False page.save() test_request = HttpRequest() with self.assertRaises(Http404): view_answer( test_request,", "language='en', live=True) mock_return = mock.Mock() mock_return.url = \"inscisive_url.com\" mock_return.autocomplete =", "0 mock_filter.return_value = [mock_queryset] response = self.client.get(reverse( 'ask-search-en'), {'q': 'payday'})", "redirect_ask_search(request) self.assertEqual( result.get('location'), '/ask-cfpb/audience-older-americans/') def test_spanish_redirect_search_with_tag(self): target_tag = 'spanishtag1' tag_querystring", "self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_spanish_redirect_ask_search_passes_query_string( self, mock_redirect): request = HttpRequest()", "QueryDict from django.test import TestCase, override_settings from django.utils import timezone", "( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:englishtag2'.format(target_tag)) request = HttpRequest() request.GET = QueryDict(tag_querystring) result", "mock_return.text = \"inscisive text\" mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return]))", "= 0 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value = mock_queryset mock_sqs_instance.spelling_suggestion.return_value =", "= ( '<p>Answer with a <a href=\"http://fake.com\">fake link.</a></p>') (annotated_answer, links)", "mock_serve): from ask_cfpb.views import view_answer page = self.test_answer.english_page revision =", "import TestCase, override_settings from django.utils import timezone from wagtail.wagtailcore.models import", "'AnswerResultsPage', 'Mock Spanish results page', 'respuestas', self.spanish_parent_page, language='es', live=True) mock_return", "import HomePage self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page = get_or_create_page( apps, 'ask_cfpb',", "self.sharing_site = mommy.make( SharingSite, site=self.site, hostname='preview.localhost', port=8000) @mock.patch('ask_cfpb.views.ServeView.serve_latest_revision') def test_preview_page(self,", "HttpRequest() request.GET['q'] = ' ' with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_with_category(self):", "'selected_facets=category_exact:my_category' '&selected_facets=category_exact:my_category2' '&selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2' '&selected_facets=tag_exact:mytag1' '&selected_facets=tag_exact:mytag2') request = HttpRequest() request.GET", "= mock.Mock() mock_return.url = \"inscisive_url.com\" mock_return.autocomplete = \"inscisive question\" mock_return.text", "timezone.now() class AnswerPagePreviewCase(TestCase): def setUp(self): from v1.models import HomePage from", "SPANISH_PARENT_SLUG from ask_cfpb.views import annotate_links, ask_search, redirect_ask_search from v1.util.migrations import", "= mommy.make( Answer, answer=\"Test answer.\", question=\"Test question.\", slug='test-question', update_english_page=True, update_spanish_page=False)", "'ask-cfpb/answer-search-spanish-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_json_response(self, mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock", "page = self.test_answer.english_page revision = page.save_revision() revision.publish() test_request = HttpRequest()", "SharingSite import mock from model_mommy import mommy from ask_cfpb.models import", "HttpRequest() with self.assertRaises(Http404): view_answer( test_request, 'test-question', 'en', self.test_answer.pk) class AnswerViewTestCase(TestCase):", "= self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page)", "language='en') self.assertEqual( result.get('location'), '/ask-cfpb/search-by-tag/{}/'.format( target_tag)) def test_redirect_search_with_unrecognized_facet_raises_404(self): querystring = \\", "1) @mock.patch('ask_cfpb.views.redirect') def test_spanish_redirect_ask_search_passes_query_string( self, mock_redirect): request = HttpRequest() request.GET['selected_facets']", "'payday') self.assertEqual(response_page.query, 'paydya') @mock.patch('ask_cfpb.views.redirect_ask_search') def test_ask_search_encounters_facets(self, mock_redirect): request = HttpRequest()", "= mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset response =", "request.GET['q'] = 'hoodoo' redirect_ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_spanish_redirect_ask_search_passes_query_string( self,", "1) def test_answer_page_not_live(self): from ask_cfpb.views import view_answer page = self.test_answer.english_page", "HttpRequest() request.GET['q'] = 'hoodoo' redirect_ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_spanish_redirect_ask_search_passes_query_string(", "= [mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-en'), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1)", "'tuition') def test_autocomplete_en_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-en'), {'term': ''}) output", "mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}),", "language='es', live=True) mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov' mock_return.autocomplete =", "1 mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-en'), {'q': 'tuition'}) self.assertEqual(mock_filter.call_count, 1)", "language='en', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_no_term(self, mock_sqs): from v1.util.migrations import get_or_create_page", "[]) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_en(self, mock_autocomplete): mock_search_result = mock.Mock() mock_search_result.autocomplete =", "= \\ 'sort=-updated_at&selected_facets=imtkfidycqszgfdb&page=60' request = HttpRequest() request.GET = QueryDict(querystring) with", "def test_redirect_search_no_facets(self): request = HttpRequest() with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_blank_facets(self):", "test_autocomplete_en(self, mock_autocomplete): mock_search_result = mock.Mock() mock_search_result.autocomplete = 'question' mock_search_result.url =", "'en', self.test_answer.pk) class AnswerViewTestCase(TestCase): def setUp(self): from v1.models import HomePage", "self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_redirect_ask_search_passes_query_string(self, mock_redirect): request = HttpRequest() request.GET['q']", "self, mock_redirect): request = HttpRequest() request.GET['selected_facets'] = 'category_exact:my_categoria' redirect_ask_search(request, language='es')", "mock_filter): page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page',", "self.assertIn('no default wagtail site', str(context.exception)) def test_bad_language_search(self): with self.assertRaises(NoReverseMatch): self.client.get(reverse(", "1) self.assertEqual(page.language, 'es') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-spanish-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def", "'ask-search-en', kwargs={'language': 'zz'}), {'q': 'payday'}) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_en_search_results_page_not_created(self, mock_filter): mock_queryset", "mock_queryset.count.return_value = 1 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value = mock_queryset mock_sqs_instance.spelling_suggestion.return_value", "'respuestas', self.spanish_parent_page, language='es', live=True) mock_return = mock.Mock() mock_return.url = 'url'", "request.GET['selected_facets'] = 'category_exact:my_categoria' redirect_ask_search(request, language='es') self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_es_search(self,", "self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='es', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_en_selection(self, mock_filter): page =", "test_json_response(self, mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results',", "= mommy.make( Site, root_page=self.ROOT_PAGE, hostname='localhost', port=8000, is_default_site=True) self.sharing_site = mommy.make(", "test_annotate_links_no_site(self): site = Site.objects.get(is_default_site=True) site.is_default_site = False site.save() with self.assertRaises(RuntimeError)", "'en') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_es_selection(self, mock_filter):", "test_en_search_no_term(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page = get_or_create_page( apps,", "= 'payday' response = self.client.get(reverse( 'ask-search-en'), {'q': 'paydya'}) self.assertEqual(response.status_code, 200)", "'question' mock_search_result.url = 'url' mock_autocomplete.return_value = [mock_search_result] result = self.client.get(reverse(", "= 'url' mock_autocomplete.return_value = [mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language':", "[]) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_es_selection(self, mock_filter): page =", "= 'question' mock_search_result.url = 'url' mock_autocomplete.return_value = [mock_search_result] result =", "\\ 'sort=-updated_at&selected_facets=imtkfidycqszgfdb&page=60' request = HttpRequest() request.GET = QueryDict(querystring) with self.assertRaises(Http404):", "self.english_parent_page, language='en', live=True) mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov' mock_return.autocomplete", "mock_return.url = 'mockcfpb.gov' mock_return.autocomplete = 'A mock question' mock_return.text =", "'selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2') request = HttpRequest() request.GET = QueryDict(audience_querystring) result =", "'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output = json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question', 'url'])", "ask_cfpb.views import annotate_links, ask_search, redirect_ask_search from v1.util.migrations import get_or_create_page now", "'AnswerLandingPage', 'Ask CFPB', ENGLISH_PARENT_SLUG, self.ROOT_PAGE, language='en', live=True) self.spanish_parent_page = get_or_create_page(", "with self.assertRaises(NoReverseMatch): self.client.get(reverse( 'ask-search-en', kwargs={'language': 'zz'}), {'q': 'payday'}) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def", "'Mock results page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') mock_return = mock.Mock() mock_return.url", "'ask-search-en'), {'q': 'payday'}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].suggestion,", "get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Ask CFPB', ENGLISH_PARENT_SLUG, self.ROOT_PAGE, language='en', live=True)", "mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-en'), {'q': 'tuition'})", "QueryDict(tag_querystring) result = redirect_ask_search(request, language='es') self.assertEqual( result.get('location'), '/es/obtener-respuestas/buscar-por-etiqueta/{}/'.format( target_tag)) def", "test_annotate_links(self): mock_answer = ( '<p>Answer with a <a href=\"http://fake.com\">fake link.</a></p>')", "'&selected_facets=tag_exact:englishtag2'.format(target_tag)) request = HttpRequest() request.GET = QueryDict(tag_querystring) result = redirect_ask_search(request,", "mock_search_result.autocomplete = 'question' mock_search_result.url = 'url' mock_autocomplete.return_value = [mock_search_result] result", "__future__ import unicode_literals import json from django.apps import apps from", "self.assertTrue(mock_filter.called_with(language='en', q='payday')) self.assertEqual(response.status_code, 404) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search(self, mock_sqs): from v1.util.migrations", "ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG from ask_cfpb.views import annotate_links, ask_search, redirect_ask_search from v1.util.migrations", "language='es') self.assertEqual( result.get('location'), '/es/obtener-respuestas/buscar-por-etiqueta/{}/'.format( target_tag)) def test_english_redirect_search_with_tag(self): target_tag = 'englishtag1'", "mock_sqs_instance.spelling_suggestion.return_value = 'payday' response = self.client.get(reverse( 'ask-search-en'), {'q': 'paydya'}) self.assertEqual(response.status_code,", "class AnswerViewTestCase(TestCase): def setUp(self): from v1.models import HomePage self.ROOT_PAGE =", "json from django.apps import apps from django.core.urlresolvers import NoReverseMatch, reverse", "@mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_en_selection(self, mock_filter): page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage',", "from django.core.urlresolvers import NoReverseMatch, reverse from django.http import Http404, HttpRequest,", "response.context_data['page'].result_query, '') @override_settings(FLAGS={'ASK_SEARCH_TYPOS': {'boolean': True}}) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_suggestion(self, mock_sqs): from", "'test-question', 'en', self.test_answer.pk) class AnswerViewTestCase(TestCase): def setUp(self): from v1.models import", "import ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG from ask_cfpb.views import annotate_links, ask_search, redirect_ask_search from", "request = HttpRequest() request.GET = QueryDict(tag_querystring) result = redirect_ask_search(request, language='en')", "mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 0 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value = mock_queryset", "@mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_json_response(self, mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results", "mock_filter): page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock Spanish results", "def test_preview_page(self, mock_serve): from ask_cfpb.views import view_answer page = self.test_answer.english_page", "= 1 mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}), {'q':", "@mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_suggestion(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page =", "request.GET = QueryDict(tag_querystring) result = redirect_ask_search(request, language='en') self.assertEqual( result.get('location'), '/ask-cfpb/search-by-tag/{}/'.format(", "json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question', 'url']) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_es(self, mock_autocomplete): mock_search_result", "django.apps import apps from django.core.urlresolvers import NoReverseMatch, reverse from django.http", "mock_queryset.count.return_value = 0 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value = mock_queryset mock_sqs_instance.spelling_suggestion.return_value", "'ask_cfpb', 'AnswerLandingPage', 'Obtener respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) def test_annotate_links(self):", "'AnswerLandingPage', 'Obtener respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) def test_annotate_links(self): mock_answer", "with a <a>fake link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer) self.assertEqual(links, [])", "self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual(", "self.client.get(reverse( 'ask-search-en'), {'q': 'paydya'}) self.assertEqual(response.status_code, 200) response_page = response.context_data['page'] self.assertEqual(response_page,", "response_page = response.context_data['page'] self.assertEqual(response_page, mock_page) self.assertEqual(response_page.suggestion, 'paydya') self.assertEqual(response_page.result_query, 'payday') self.assertEqual(response_page.query,", "mock_answer = ( '<p>Answer with a <a href=\"http://fake.com\">fake link.</a></p>') (annotated_answer,", "as context: annotate_links('answer') self.assertIn('no default wagtail site', str(context.exception)) def test_bad_language_search(self):", "self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='en', q='payday')) self.assertEqual(response.status_code, 404) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search(self, mock_sqs):", "= response.context_data['page'] self.assertEqual(response_page, mock_page) self.assertEqual(response_page.suggestion, 'paydya') self.assertEqual(response_page.result_query, 'payday') self.assertEqual(response_page.query, 'paydya')", "self.assertEqual(response_page, mock_page) self.assertEqual(response_page.suggestion, 'paydya') self.assertEqual(response_page.result_query, 'payday') self.assertEqual(response_page.query, 'paydya') @mock.patch('ask_cfpb.views.redirect_ask_search') def", "mock question' mock_return.text = 'Mock answer text.' mock_queryset = mock.Mock()", "'payday' response = self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(response.status_code, 200) self.assertEqual(", "import Answer self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page = get_or_create_page( apps, 'ask_cfpb',", "self.assertEqual(output, []) def test_autocomplete_es_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}),", "annotate_links('answer') self.assertIn('no default wagtail site', str(context.exception)) def test_bad_language_search(self): with self.assertRaises(NoReverseMatch):", "'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output = json.loads(result.content)", "self.assertEqual(result.get('location'), '/ask-cfpb/category-my_category/') def test_redirect_search_with_audience(self): audience_querystring = ( 'selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2') request", "'spanishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:spanishtag2'.format(target_tag)) request = HttpRequest() request.GET", "self.test_answer.english_page revision = page.save_revision() revision.publish() test_request = HttpRequest() test_request.META['SERVER_NAME'] =", "self.assertRaises(RuntimeError) as context: annotate_links('answer') self.assertIn('no default wagtail site', str(context.exception)) def", "ask_cfpb.models import Answer self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page = get_or_create_page( apps,", "= False site.save() with self.assertRaises(RuntimeError) as context: annotate_links('answer') self.assertIn('no default", "'mockcfpb.gov' mock_return.autocomplete = 'A mock question' mock_return.text = 'Mock answer", "'<p>Answer with a <a>fake link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer) self.assertEqual(links,", "= HomePage.objects.get(slug='cfgov') self.english_parent_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Ask CFPB',", "'Mock results page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') response = self.client.get(reverse( 'ask-search-en'),", "mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset self.client.get(reverse(", "language='es', live=True) mock_return = mock.Mock() mock_return.url = 'url' mock_return.autocomplete =", "def test_annotate_links_no_site(self): site = Site.objects.get(is_default_site=True) site.is_default_site = False site.save() with", "kwargs={'language': 'es'}), {'term': ''}) output = json.loads(result.content) self.assertEqual(output, []) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete')", "page.live = False page.save() test_request = HttpRequest() with self.assertRaises(Http404): view_answer(", "test_redirect_search_no_query(self): request = HttpRequest() request.GET['q'] = ' ' with self.assertRaises(Http404):", "'link.</a><sup>1</sup></p></body></html>') self.assertEqual(links, [(1, str('http://fake.com'))]) def test_annotate_links_no_href(self): mock_answer = ( '<p>Answer", "'zz'}), {'q': 'payday'}) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_en_search_results_page_not_created(self, mock_filter): mock_queryset = mock.Mock()", "redirect_ask_search(request) def test_redirect_search_blank_facets(self): request = HttpRequest() request.GET['selected_facets'] = '' with", "with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_no_query(self): request = HttpRequest() request.GET['q'] =", "mock_sqs_instance.spelling_suggestion.return_value = 'payday' response = self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(response.status_code,", "from ask_cfpb.views import view_answer page = self.test_answer.english_page page.live = False", "'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.english_parent_page, language='en', live=True) mock_return =", "= mock_queryset self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1)", "= 'payday' response = self.client.get(reverse( 'ask-search-en'), {'q': 'payday'}) self.assertEqual(response.status_code, 200)", "= HttpRequest() test_request.META['SERVER_NAME'] = 'preview.localhost' test_request.META['SERVER_PORT'] = 8000 view_answer( test_request,", "self.client.get(reverse( 'ask-search-en'), {'q': 'tuition'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'en') self.assertEqual(page.answers, [])", "def setUp(self): from v1.models import HomePage self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page", "live=True) self.spanish_parent_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Obtener respuestas', SPANISH_PARENT_SLUG,", "0 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value = mock_queryset mock_sqs_instance.spelling_suggestion.return_value = 'payday'", "= json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question', 'url']) class RedirectAskSearchTestCase(TestCase): def test_redirect_search_no_facets(self):", "def test_autocomplete_es(self, mock_autocomplete): mock_search_result = mock.Mock() mock_search_result.autocomplete = 'question' mock_search_result.url", "with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_with_category(self): category_querystring = ( 'selected_facets=category_exact:my_category' '&selected_facets=category_exact:my_category2'", "a <a href=\"http://fake.com\">fake link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer) self.assertEqual( annotated_answer,", "update_english_page=True, update_spanish_page=False) self.site = mommy.make( Site, root_page=self.ROOT_PAGE, hostname='localhost', port=8000, is_default_site=True)", "= HttpRequest() request.GET = QueryDict(tag_querystring) result = redirect_ask_search(request, language='en') self.assertEqual(", "{'q': ''}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].query, '')", "404) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page", "root_page=self.ROOT_PAGE, hostname='localhost', port=8000, is_default_site=True) self.sharing_site = mommy.make( SharingSite, site=self.site, hostname='preview.localhost',", "with a <a href=\"http://fake.com\">fake link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer) self.assertEqual(", "test_bad_language_search(self): with self.assertRaises(NoReverseMatch): self.client.get(reverse( 'ask-search-en', kwargs={'language': 'zz'}), {'q': 'payday'}) @mock.patch('ask_cfpb.views.SearchQuerySet.filter')", "= HttpRequest() request.GET['selected_facets'] = 'category_exact:my_category' ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def", "self.assertEqual(json.loads(response.content)['query'], 'tuition') def test_autocomplete_en_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-en'), {'term': ''})", "'tuition'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'en') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-results.html')", "1) output = json.loads(result.content) self.assertEqual( sorted(output[0].keys()), ['question', 'url']) @mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def", "self.assertEqual( response.context_data['page'].suggestion, None) self.assertEqual(mock_sqs_instance.filter.call_count, 1) self.assertTrue(mock_sqs_instance.filter.called_with( language='en', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet') def", "href=\"http://fake.com\">fake ' 'link.</a><sup>1</sup></p></body></html>') self.assertEqual(links, [(1, str('http://fake.com'))]) def test_annotate_links_no_href(self): mock_answer =", "mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov' mock_return.autocomplete = 'A mock", "'ask-search-en'), {'q': 'tuition'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'en') self.assertEqual(page.answers, []) self.assertEqual(", "'&selected_facets=tag_exact:spanishtag2'.format(target_tag)) request = HttpRequest() request.GET = QueryDict(tag_querystring) result = redirect_ask_search(request,", "mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.english_parent_page,", "test_answer_page_not_live(self): from ask_cfpb.views import view_answer page = self.test_answer.english_page page.live =", "a <a href=\"http://fake.com\">fake ' 'link.</a><sup>1</sup></p></body></html>') self.assertEqual(links, [(1, str('http://fake.com'))]) def test_annotate_links_no_href(self):", "self.assertEqual(mock_sqs_instance.filter.call_count, 1) self.assertTrue(mock_sqs_instance.filter.called_with( language='en', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_no_term(self, mock_sqs): from", "= 'preview.localhost' test_request.META['SERVER_PORT'] = 8000 view_answer( test_request, 'test-question', 'en', self.test_answer.pk)", "[]) def test_autocomplete_es_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term':", "= 'question text' mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value", "self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'en') self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter')", "mock.Mock() mock_return.url = 'mockcfpb.gov' mock_return.autocomplete = 'A mock question' mock_return.text", "[]) def test_annotate_links_no_site(self): site = Site.objects.get(is_default_site=True) site.is_default_site = False site.save()", "from ask_cfpb.views import view_answer page = self.test_answer.english_page revision = page.save_revision()", "@override_settings(FLAGS={'ASK_SEARCH_TYPOS': {'boolean': True}}) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_suggestion(self, mock_sqs): from v1.util.migrations import", "' 'link.</a><sup>1</sup></p></body></html>') self.assertEqual(links, [(1, str('http://fake.com'))]) def test_annotate_links_no_href(self): mock_answer = (", "'Ask CFPB', ENGLISH_PARENT_SLUG, self.ROOT_PAGE, language='en', live=True) self.spanish_parent_page = get_or_create_page( apps,", "site = Site.objects.get(is_default_site=True) site.is_default_site = False site.save() with self.assertRaises(RuntimeError) as", "page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results',", "@mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_es(self, mock_autocomplete): mock_search_result = mock.Mock() mock_search_result.autocomplete = 'question'", "test_request, 'test-question', 'en', self.test_answer.pk) self.assertEqual(mock_serve.call_count, 1) def test_answer_page_not_live(self): from ask_cfpb.views", "self.assertEqual( result.get('location'), '/ask-cfpb/search-by-tag/{}/'.format( target_tag)) def test_redirect_search_with_unrecognized_facet_raises_404(self): querystring = \\ 'sort=-updated_at&selected_facets=imtkfidycqszgfdb&page=60'", "default wagtail site', str(context.exception)) def test_bad_language_search(self): with self.assertRaises(NoReverseMatch): self.client.get(reverse( 'ask-search-en',", "'/ask-cfpb/search-by-tag/{}/'.format( target_tag)) def test_redirect_search_with_unrecognized_facet_raises_404(self): querystring = \\ 'sort=-updated_at&selected_facets=imtkfidycqszgfdb&page=60' request =", "q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_en_selection(self, mock_filter): page = get_or_create_page( apps, 'ask_cfpb',", "page.save_revision() revision.publish() test_request = HttpRequest() test_request.META['SERVER_NAME'] = 'preview.localhost' test_request.META['SERVER_PORT'] =", "= mock_queryset self.client.get(reverse( 'ask-search-en'), {'q': 'tuition'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'en')", "= self.client.get(reverse( 'ask-search-en'), {'q': 'paydya'}) self.assertEqual(response.status_code, 200) response_page = response.context_data['page']", "import get_or_create_page now = timezone.now() class AnswerPagePreviewCase(TestCase): def setUp(self): from", "v1.util.migrations import get_or_create_page mock_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock", "request = HttpRequest() request.GET = QueryDict(audience_querystring) result = redirect_ask_search(request) self.assertEqual(", "get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock Spanish results page', 'respuestas', self.spanish_parent_page,", "mock_search_result.url = 'url' mock_autocomplete.return_value = [mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-es',", "test_redirect_search_with_category(self): category_querystring = ( 'selected_facets=category_exact:my_category' '&selected_facets=category_exact:my_category2' '&selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2' '&selected_facets=tag_exact:mytag1' '&selected_facets=tag_exact:mytag2')", "@mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search_no_term(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page =", "import apps from django.core.urlresolvers import NoReverseMatch, reverse from django.http import", "live=True) mock_return = mock.Mock() mock_return.url = 'url' mock_return.autocomplete = 'question", "( '<p>Answer with a <a href=\"http://fake.com\">fake link.</a></p>') (annotated_answer, links) =", "'Mock results page', 'ask-cfpb-search-results', self.english_parent_page, language='en', live=True) mock_return = mock.Mock()", "QueryDict(category_querystring) result = redirect_ask_search(request) self.assertEqual(result.get('location'), '/ask-cfpb/category-my_category/') def test_redirect_search_with_audience(self): audience_querystring =", "def test_answer_page_not_live(self): from ask_cfpb.views import view_answer page = self.test_answer.english_page page.live", "with a <a href=\"http://fake.com\">fake ' 'link.</a><sup>1</sup></p></body></html>') self.assertEqual(links, [(1, str('http://fake.com'))]) def", "self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_es_search(self, mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage',", "'Mock Spanish results page', 'respuestas', self.spanish_parent_page, language='es', live=True) mock_return =", "result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1)", "[mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-en'), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count, 1) output", "view_answer( test_request, 'test-question', 'en', self.test_answer.pk) class AnswerViewTestCase(TestCase): def setUp(self): from", "self.assertEqual(response_page.suggestion, 'paydya') self.assertEqual(response_page.result_query, 'payday') self.assertEqual(response_page.query, 'paydya') @mock.patch('ask_cfpb.views.redirect_ask_search') def test_ask_search_encounters_facets(self, mock_redirect):", "self.assertEqual(response_page.query, 'paydya') @mock.patch('ask_cfpb.views.redirect_ask_search') def test_ask_search_encounters_facets(self, mock_redirect): request = HttpRequest() request.GET['selected_facets']", "= \"inscisive question\" mock_return.text = \"inscisive text\" mock_queryset = mock.Mock()", "results page', 'respuestas', self.spanish_parent_page, language='es', live=True) mock_return = mock.Mock() mock_return.url", "test_redirect_search_blank_facets(self): request = HttpRequest() request.GET['selected_facets'] = '' with self.assertRaises(Http404): redirect_ask_search(request)", "test_redirect_ask_search_passes_query_string(self, mock_redirect): request = HttpRequest() request.GET['q'] = 'hoodoo' redirect_ask_search(request) self.assertEqual(mock_redirect.call_count,", "1 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value = mock_queryset mock_sqs_instance.spelling_suggestion.return_value = 'payday'", "reverse from django.http import Http404, HttpRequest, QueryDict from django.test import", "'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') response =", "apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock Spanish results page', 'respuestas', self.spanish_parent_page, language='es',", "mock_return.autocomplete = 'question text' mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return]))", "{'q': 'payday'}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].suggestion, None)", "{'q': 'payday'}) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_en_search_results_page_not_created(self, mock_filter): mock_queryset = mock.Mock() mock_queryset.count.return_value", "self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_es_selection(self, mock_filter): page = get_or_create_page(", "self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_with_category(self): category_querystring = ( 'selected_facets=category_exact:my_category' '&selected_facets=category_exact:my_category2' '&selected_facets=audience_exact:Older+Americans'", "1 mock_filter.return_value = mock_queryset response = self.client.get(reverse( 'ask-search-en-json', kwargs={'as_json': 'json'}),", "result = redirect_ask_search(request, language='es') self.assertEqual( result.get('location'), '/es/obtener-respuestas/buscar-por-etiqueta/{}/'.format( target_tag)) def test_english_redirect_search_with_tag(self):", "self.assertEqual(response.status_code, 404) @mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search(self, mock_sqs): from v1.util.migrations import get_or_create_page", "live=True) mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov' mock_return.autocomplete = 'A", "[mock_search_result] result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': 'question'}) self.assertEqual(mock_autocomplete.call_count,", "page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov'", "apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') mock_return", "self.assertTrue(mock_filter.called_with(language='es', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_en_selection(self, mock_filter): page = get_or_create_page( apps,", "'payday'}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].suggestion, None) self.assertEqual(mock_sqs_instance.filter.call_count,", "response = self.client.get(reverse( 'ask-search-en'), {'q': 'paydya'}) self.assertEqual(response.status_code, 200) response_page =", "site.save() with self.assertRaises(RuntimeError) as context: annotate_links('answer') self.assertIn('no default wagtail site',", "''}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].query, '') self.assertEqual(", "SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True) self.test_answer = mommy.make( Answer, answer=\"Test answer.\",", "site.is_default_site = False site.save() with self.assertRaises(RuntimeError) as context: annotate_links('answer') self.assertIn('no", "self.client.get(reverse( 'ask-search-en', kwargs={'language': 'zz'}), {'q': 'payday'}) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_en_search_results_page_not_created(self, mock_filter):", "= self.test_answer.english_page page.live = False page.save() test_request = HttpRequest() with", "self.assertEqual(page.answers, []) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-spanish-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_json_response(self, mock_filter): get_or_create_page(", "'&selected_facets=audience_exact:my_audience2') request = HttpRequest() request.GET = QueryDict(audience_querystring) result = redirect_ask_search(request)", "from v1.util.migrations import get_or_create_page mock_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage',", "results page', 'ask-cfpb-search-results', self.english_parent_page, language='en', live=True) mock_return = mock.Mock() mock_return.url", "import mock from model_mommy import mommy from ask_cfpb.models import ENGLISH_PARENT_SLUG,", "= mock_queryset response = self.client.get(reverse( 'ask-search-en-json', kwargs={'as_json': 'json'}), {'q': 'tuition'})", "= get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Ask CFPB', ENGLISH_PARENT_SLUG, self.ROOT_PAGE, language='en',", "from ask_cfpb.models import Answer self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page = get_or_create_page(", "get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Obtener respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE, language='es', live=True)", "request.GET['selected_facets'] = 'category_exact:my_category' ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_redirect_ask_search_passes_query_string(self, mock_redirect):", "SharingSite, site=self.site, hostname='preview.localhost', port=8000) @mock.patch('ask_cfpb.views.ServeView.serve_latest_revision') def test_preview_page(self, mock_serve): from ask_cfpb.views", "links) = annotate_links(mock_answer) self.assertEqual( annotated_answer, '<html><body><p>Answer with a <a href=\"http://fake.com\">fake", "= HttpRequest() request.GET = QueryDict(audience_querystring) result = redirect_ask_search(request) self.assertEqual( result.get('location'),", "update_spanish_page=False) self.site = mommy.make( Site, root_page=self.ROOT_PAGE, hostname='localhost', port=8000, is_default_site=True) self.sharing_site", "test_autocomplete_es(self, mock_autocomplete): mock_search_result = mock.Mock() mock_search_result.autocomplete = 'question' mock_search_result.url =", "ask_search, redirect_ask_search from v1.util.migrations import get_or_create_page now = timezone.now() class", "False site.save() with self.assertRaises(RuntimeError) as context: annotate_links('answer') self.assertIn('no default wagtail", "page.save() test_request = HttpRequest() with self.assertRaises(Http404): view_answer( test_request, 'test-question', 'en',", "test_spanish_redirect_ask_search_passes_query_string( self, mock_redirect): request = HttpRequest() request.GET['selected_facets'] = 'category_exact:my_categoria' redirect_ask_search(request,", "href=\"http://fake.com\">fake link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer) self.assertEqual( annotated_answer, '<html><body><p>Answer with", "HttpRequest() request.GET['selected_facets'] = 'category_exact:my_category' ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect') def test_redirect_ask_search_passes_query_string(self,", "'&selected_facets=audience_exact:my_audience2' '&selected_facets=tag_exact:mytag1' '&selected_facets=tag_exact:mytag2') request = HttpRequest() request.GET = QueryDict(category_querystring) result", "def test_redirect_search_with_category(self): category_querystring = ( 'selected_facets=category_exact:my_category' '&selected_facets=category_exact:my_category2' '&selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2' '&selected_facets=tag_exact:mytag1'", "= mock.Mock() mock_search_result.autocomplete = 'question' mock_search_result.url = 'url' mock_autocomplete.return_value =", "[]) self.assertEqual( page.get_template(HttpRequest()), 'ask-cfpb/answer-search-spanish-results.html') @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_json_response(self, mock_filter): get_or_create_page( apps,", "'ask-cfpb-search-results', self.english_parent_page, language='en', live=True) mock_return = mock.Mock() mock_return.url = \"inscisive_url.com\"", "mock_return.autocomplete = 'A mock question' mock_return.text = 'Mock answer text.'", "mock_redirect): request = HttpRequest() request.GET['selected_facets'] = 'category_exact:my_category' ask_search(request) self.assertEqual(mock_redirect.call_count, 1)", "class RedirectAskSearchTestCase(TestCase): def test_redirect_search_no_facets(self): request = HttpRequest() with self.assertRaises(Http404): redirect_ask_search(request)", "'tuition'}) self.assertEqual(response.status_code, 200) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(json.loads(response.content)['query'], 'tuition') def test_autocomplete_en_blank_term(self): result", "self.spanish_parent_page = get_or_create_page( apps, 'ask_cfpb', 'AnswerLandingPage', 'Obtener respuestas', SPANISH_PARENT_SLUG, self.ROOT_PAGE,", "QueryDict(tag_querystring) result = redirect_ask_search(request, language='en') self.assertEqual( result.get('location'), '/ask-cfpb/search-by-tag/{}/'.format( target_tag)) def", "str('http://fake.com'))]) def test_annotate_links_no_href(self): mock_answer = ( '<p>Answer with a <a>fake", "'ask-search-es', kwargs={'language': 'es'}), {'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='es', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet.filter')", "mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value = mock_queryset mock_sqs_instance.spelling_suggestion.return_value = 'payday' response = self.client.get(reverse(", "mock_queryset mock_sqs_instance.spelling_suggestion.return_value = 'payday' response = self.client.get(reverse( 'ask-search-en'), {'q': 'paydya'})", "{'q': 'payday'}) self.assertEqual(mock_filter.call_count, 1) self.assertTrue(mock_filter.called_with(language='es', q='payday')) @mock.patch('ask_cfpb.views.SearchQuerySet.filter') def test_search_page_en_selection(self, mock_filter):", "response.context_data['page'], mock_page) self.assertEqual( response.context_data['page'].query, '') self.assertEqual( response.context_data['page'].result_query, '') @override_settings(FLAGS={'ASK_SEARCH_TYPOS': {'boolean':", "import unicode_literals import json from django.apps import apps from django.core.urlresolvers", "mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}), {'q': 'payday'}) self.assertEqual(mock_filter.call_count,", "self.ROOT_PAGE, language='es', live=True) def test_annotate_links(self): mock_answer = ( '<p>Answer with", "'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') response = self.client.get(reverse(", "mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}), {'q': 'hipotecas'}) self.assertEqual(mock_filter.call_count,", "link.</a></p>') (annotated_answer, links) = annotate_links(mock_answer) self.assertEqual(links, []) def test_annotate_links_no_site(self): site", "self.client.get(reverse( 'ask-search-es', kwargs={'language': 'es'}), {'q': 'hipotecas'}) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(page.language, 'es')", "mock_queryset = mock.Mock() mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_sqs_instance", "self.spanish_parent_page, language='es', live=True) mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov' mock_return.autocomplete", "request.GET['selected_facets'] = '' with self.assertRaises(Http404): redirect_ask_search(request) def test_redirect_search_no_query(self): request =", "8000 view_answer( test_request, 'test-question', 'en', self.test_answer.pk) self.assertEqual(mock_serve.call_count, 1) def test_answer_page_not_live(self):", "response.context_data['page'].query, '') self.assertEqual( response.context_data['page'].result_query, '') @override_settings(FLAGS={'ASK_SEARCH_TYPOS': {'boolean': True}}) @mock.patch('ask_cfpb.views.SearchQuerySet') def", "mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset self.client.get(reverse( 'ask-search-es', kwargs={'language':", "mock_queryset response = self.client.get(reverse( 'ask-search-en-json', kwargs={'as_json': 'json'}), {'q': 'tuition'}) self.assertEqual(response.status_code,", "def test_autocomplete_es_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': ''})", "'preview.localhost' test_request.META['SERVER_PORT'] = 8000 view_answer( test_request, 'test-question', 'en', self.test_answer.pk) self.assertEqual(mock_serve.call_count,", "[(1, str('http://fake.com'))]) def test_annotate_links_no_href(self): mock_answer = ( '<p>Answer with a", "mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 1 mock_filter.return_value = mock_queryset response", "language='en', live=True) mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov' mock_return.autocomplete =", "200) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(json.loads(response.content)['query'], 'tuition') def test_autocomplete_en_blank_term(self): result = self.client.get(reverse(", "page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') response = self.client.get(reverse( 'ask-search-en'), {'q': ''})", "'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') mock_return =", "''}) output = json.loads(result.content) self.assertEqual(output, []) def test_autocomplete_es_blank_term(self): result =", "TestCase, override_settings from django.utils import timezone from wagtail.wagtailcore.models import Site", "def test_json_response(self, mock_filter): get_or_create_page( apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page',", "redirect_ask_search(request, language='es') self.assertEqual( result.get('location'), '/es/obtener-respuestas/buscar-por-etiqueta/{}/'.format( target_tag)) def test_english_redirect_search_with_tag(self): target_tag =", "request.GET = QueryDict(category_querystring) result = redirect_ask_search(request) self.assertEqual(result.get('location'), '/ask-cfpb/category-my_category/') def test_redirect_search_with_audience(self):", "'ask-search-en'), {'q': 'paydya'}) self.assertEqual(response.status_code, 200) response_page = response.context_data['page'] self.assertEqual(response_page, mock_page)", "self.assertEqual(links, [(1, str('http://fake.com'))]) def test_annotate_links_no_href(self): mock_answer = ( '<p>Answer with", "@mock.patch('ask_cfpb.views.SearchQuerySet.autocomplete') def test_autocomplete_en(self, mock_autocomplete): mock_search_result = mock.Mock() mock_search_result.autocomplete = 'question'", "= 'spanishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:spanishtag2'.format(target_tag)) request = HttpRequest()", "= ( 'selected_facets=category_exact:my_category' '&selected_facets=category_exact:my_category2' '&selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2' '&selected_facets=tag_exact:mytag1' '&selected_facets=tag_exact:mytag2') request =", "redirect_ask_search from v1.util.migrations import get_or_create_page now = timezone.now() class AnswerPagePreviewCase(TestCase):", "test_english_redirect_search_with_tag(self): target_tag = 'englishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:englishtag2'.format(target_tag)) request", "'ask-cfpb-search-results', self.ROOT_PAGE, language='en') mock_return = mock.Mock() mock_return.url = 'mockcfpb.gov' mock_return.autocomplete", "self.assertEqual(response.status_code, 200) self.assertEqual(mock_filter.call_count, 1) self.assertEqual(json.loads(response.content)['query'], 'tuition') def test_autocomplete_en_blank_term(self): result =", "= self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': ''}) output = json.loads(result.content)", "= self.client.get(reverse( 'ask-search-en'), {'q': ''}) self.assertEqual(response.status_code, 200) self.assertEqual( response.context_data['page'], mock_page)", "import annotate_links, ask_search, redirect_ask_search from v1.util.migrations import get_or_create_page now =", "test_request.META['SERVER_PORT'] = 8000 view_answer( test_request, 'test-question', 'en', self.test_answer.pk) self.assertEqual(mock_serve.call_count, 1)", "target_tag)) def test_redirect_search_with_unrecognized_facet_raises_404(self): querystring = \\ 'sort=-updated_at&selected_facets=imtkfidycqszgfdb&page=60' request = HttpRequest()", "self.site = mommy.make( Site, root_page=self.ROOT_PAGE, hostname='localhost', port=8000, is_default_site=True) self.sharing_site =", "querystring = \\ 'sort=-updated_at&selected_facets=imtkfidycqszgfdb&page=60' request = HttpRequest() request.GET = QueryDict(querystring)", "answer=\"Test answer.\", question=\"Test question.\", slug='test-question', update_english_page=True, update_spanish_page=False) self.site = mommy.make(", "view_answer page = self.test_answer.english_page page.live = False page.save() test_request =", "mock_queryset.__iter__ = mock.Mock(return_value=iter([mock_return])) mock_queryset.count.return_value = 0 mock_sqs_instance = mock_sqs.return_value.models.return_value mock_sqs_instance.filter.return_value", "= mock.Mock() mock_queryset.count.return_value = 0 mock_filter.return_value = [mock_queryset] response =", "from django.utils import timezone from wagtail.wagtailcore.models import Site from wagtailsharing.models", "(annotated_answer, links) = annotate_links(mock_answer) self.assertEqual( annotated_answer, '<html><body><p>Answer with a <a", "'payday' response = self.client.get(reverse( 'ask-search-en'), {'q': 'paydya'}) self.assertEqual(response.status_code, 200) response_page", "apps from django.core.urlresolvers import NoReverseMatch, reverse from django.http import Http404,", "1) self.assertEqual(json.loads(response.content)['query'], 'tuition') def test_autocomplete_en_blank_term(self): result = self.client.get(reverse( 'ask-autocomplete-en'), {'term':", "@mock.patch('ask_cfpb.views.SearchQuerySet') def test_en_search(self, mock_sqs): from v1.util.migrations import get_or_create_page mock_page =", "self.ROOT_PAGE, language='en') response = self.client.get(reverse( 'ask-search-en'), {'q': ''}) self.assertEqual(response.status_code, 200)", "revision = page.save_revision() revision.publish() test_request = HttpRequest() test_request.META['SERVER_NAME'] = 'preview.localhost'", "def test_ask_search_encounters_facets(self, mock_redirect): request = HttpRequest() request.GET['selected_facets'] = 'category_exact:my_category' ask_search(request)", "self.client.get(reverse( 'ask-autocomplete-es', kwargs={'language': 'es'}), {'term': ''}) output = json.loads(result.content) self.assertEqual(output,", "'url']) class RedirectAskSearchTestCase(TestCase): def test_redirect_search_no_facets(self): request = HttpRequest() with self.assertRaises(Http404):", "'<html><body><p>Answer with a <a href=\"http://fake.com\">fake ' 'link.</a><sup>1</sup></p></body></html>') self.assertEqual(links, [(1, str('http://fake.com'))])", "redirect_ask_search(request) def test_redirect_search_with_category(self): category_querystring = ( 'selected_facets=category_exact:my_category' '&selected_facets=category_exact:my_category2' '&selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2'", "'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:englishtag2'.format(target_tag)) request = HttpRequest() request.GET = QueryDict(tag_querystring) result =", "apps, 'ask_cfpb', 'AnswerResultsPage', 'Mock results page', 'ask-cfpb-search-results', self.ROOT_PAGE, language='en') response", "result = redirect_ask_search(request) self.assertEqual( result.get('location'), '/ask-cfpb/audience-older-americans/') def test_spanish_redirect_search_with_tag(self): target_tag =", "'&selected_facets=audience_exact:Older+Americans' '&selected_facets=audience_exact:my_audience2' '&selected_facets=tag_exact:mytag1' '&selected_facets=tag_exact:mytag2') request = HttpRequest() request.GET = QueryDict(category_querystring)", "test_spanish_redirect_search_with_tag(self): target_tag = 'spanishtag1' tag_querystring = ( 'selected_facets=tag_exact:{}' '&selected_facets=tag_exact:spanishtag2'.format(target_tag)) request", "request = HttpRequest() request.GET['q'] = 'hoodoo' redirect_ask_search(request) self.assertEqual(mock_redirect.call_count, 1) @mock.patch('ask_cfpb.views.redirect')", "setUp(self): from v1.models import HomePage self.ROOT_PAGE = HomePage.objects.get(slug='cfgov') self.english_parent_page =", "annotate_links(mock_answer) self.assertEqual( annotated_answer, '<html><body><p>Answer with a <a href=\"http://fake.com\">fake ' 'link.</a><sup>1</sup></p></body></html>')" ]
[ ":: Console\", \"Programming Language :: Python :: 3\", \"Programming Language", "return fp.read() setup( name=\"instapaper-to-sqlite\", description=\"Save data from Instapaper to a", "Python :: 3.7\", \"Programming Language :: Python :: 3.8\", \"Topic", "os.path.join(os.path.dirname(os.path.abspath(__file__)), \"README.md\"), encoding=\"utf8\", ) as fp: return fp.read() setup( name=\"instapaper-to-sqlite\",", "Console\", \"Programming Language :: Python :: 3\", \"Programming Language ::", "\"Programming Language :: Python :: 3.7\", \"Programming Language :: Python", "Production/Stable\", \"Environment :: Console\", \"Programming Language :: Python :: 3\",", "fp.read() setup( name=\"instapaper-to-sqlite\", description=\"Save data from Instapaper to a SQLite", "Language :: Python :: 3.6\", \"Programming Language :: Python ::", "url=\"https://github.com/bcongdon/instapaper-to-sqlite\", project_urls={ \"Source\": \"https://github.com/bcongdon/instapaper-to-sqlite\", \"Issues\": \"https://github.com/bcongdon/instapaper-to-sqlite/issues\", }, classifiers=[ \"Development Status", "\"https://github.com/bcongdon/instapaper-to-sqlite\", \"Issues\": \"https://github.com/bcongdon/instapaper-to-sqlite/issues\", }, classifiers=[ \"Development Status :: 5 -", "3.7\", \"Programming Language :: Python :: 3.8\", \"Topic :: Database\",", "Language :: Python :: 3\", \"Programming Language :: Python ::", "\"Programming Language :: Python :: 3.6\", \"Programming Language :: Python", "3.8\", \"Topic :: Database\", ], keywords=\"instapaper sqlite export dogsheep\", version=VERSION,", "description=\"Save data from Instapaper to a SQLite database\", long_description=get_long_description(), long_description_content_type=\"text/markdown\",", "}, classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Environment ::", "\"Issues\": \"https://github.com/bcongdon/instapaper-to-sqlite/issues\", }, classifiers=[ \"Development Status :: 5 - Production/Stable\",", "long_description_content_type=\"text/markdown\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/bcongdon/instapaper-to-sqlite\", project_urls={ \"Source\": \"https://github.com/bcongdon/instapaper-to-sqlite\", \"Issues\": \"https://github.com/bcongdon/instapaper-to-sqlite/issues\", },", "from Instapaper to a SQLite database\", long_description=get_long_description(), long_description_content_type=\"text/markdown\", author=\"<NAME>\", author_email=\"<EMAIL>\",", "\"Programming Language :: Python :: 3.8\", \"Topic :: Database\", ],", "\"0.2\" def get_long_description(): with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), \"README.md\"), encoding=\"utf8\", ) as", "], keywords=\"instapaper sqlite export dogsheep\", version=VERSION, packages=[\"instapaper_to_sqlite\"], entry_points=\"\"\" [console_scripts] instapaper-to-sqlite=instapaper_to_sqlite.cli:cli", "setuptools import setup VERSION = \"0.2\" def get_long_description(): with open(", "entry_points=\"\"\" [console_scripts] instapaper-to-sqlite=instapaper_to_sqlite.cli:cli \"\"\", install_requires=[ \"click\", \"requests\", \"sqlite-utils~=3.17\", \"pyinstapaper @", ":: 3.6\", \"Programming Language :: Python :: 3.7\", \"Programming Language", "classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Environment :: Console\",", ":: Python :: 3\", \"Programming Language :: Python :: 3.6\",", "author_email=\"<EMAIL>\", url=\"https://github.com/bcongdon/instapaper-to-sqlite\", project_urls={ \"Source\": \"https://github.com/bcongdon/instapaper-to-sqlite\", \"Issues\": \"https://github.com/bcongdon/instapaper-to-sqlite/issues\", }, classifiers=[ \"Development", "sqlite export dogsheep\", version=VERSION, packages=[\"instapaper_to_sqlite\"], entry_points=\"\"\" [console_scripts] instapaper-to-sqlite=instapaper_to_sqlite.cli:cli \"\"\", install_requires=[", "setup VERSION = \"0.2\" def get_long_description(): with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), \"README.md\"),", "SQLite database\", long_description=get_long_description(), long_description_content_type=\"text/markdown\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/bcongdon/instapaper-to-sqlite\", project_urls={ \"Source\": \"https://github.com/bcongdon/instapaper-to-sqlite\",", "os from setuptools import setup VERSION = \"0.2\" def get_long_description():", "author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/bcongdon/instapaper-to-sqlite\", project_urls={ \"Source\": \"https://github.com/bcongdon/instapaper-to-sqlite\", \"Issues\": \"https://github.com/bcongdon/instapaper-to-sqlite/issues\", }, classifiers=[", "Language :: Python :: 3.7\", \"Programming Language :: Python ::", ":: 3\", \"Programming Language :: Python :: 3.6\", \"Programming Language", "Status :: 5 - Production/Stable\", \"Environment :: Console\", \"Programming Language", "\"Programming Language :: Python :: 3\", \"Programming Language :: Python", ":: Python :: 3.7\", \"Programming Language :: Python :: 3.8\",", "VERSION = \"0.2\" def get_long_description(): with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), \"README.md\"), encoding=\"utf8\",", ") as fp: return fp.read() setup( name=\"instapaper-to-sqlite\", description=\"Save data from", "\"README.md\"), encoding=\"utf8\", ) as fp: return fp.read() setup( name=\"instapaper-to-sqlite\", description=\"Save", "Python :: 3.8\", \"Topic :: Database\", ], keywords=\"instapaper sqlite export", "Python :: 3\", \"Programming Language :: Python :: 3.6\", \"Programming", "project_urls={ \"Source\": \"https://github.com/bcongdon/instapaper-to-sqlite\", \"Issues\": \"https://github.com/bcongdon/instapaper-to-sqlite/issues\", }, classifiers=[ \"Development Status ::", "\"Topic :: Database\", ], keywords=\"instapaper sqlite export dogsheep\", version=VERSION, packages=[\"instapaper_to_sqlite\"],", ":: Python :: 3.6\", \"Programming Language :: Python :: 3.7\",", "with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), \"README.md\"), encoding=\"utf8\", ) as fp: return fp.read()", "name=\"instapaper-to-sqlite\", description=\"Save data from Instapaper to a SQLite database\", long_description=get_long_description(),", "= \"0.2\" def get_long_description(): with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), \"README.md\"), encoding=\"utf8\", )", "packages=[\"instapaper_to_sqlite\"], entry_points=\"\"\" [console_scripts] instapaper-to-sqlite=instapaper_to_sqlite.cli:cli \"\"\", install_requires=[ \"click\", \"requests\", \"sqlite-utils~=3.17\", \"pyinstapaper", ":: 5 - Production/Stable\", \"Environment :: Console\", \"Programming Language ::", "5 - Production/Stable\", \"Environment :: Console\", \"Programming Language :: Python", "version=VERSION, packages=[\"instapaper_to_sqlite\"], entry_points=\"\"\" [console_scripts] instapaper-to-sqlite=instapaper_to_sqlite.cli:cli \"\"\", install_requires=[ \"click\", \"requests\", \"sqlite-utils~=3.17\",", ":: Python :: 3.8\", \"Topic :: Database\", ], keywords=\"instapaper sqlite", "a SQLite database\", long_description=get_long_description(), long_description_content_type=\"text/markdown\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/bcongdon/instapaper-to-sqlite\", project_urls={ \"Source\":", "Python :: 3.6\", \"Programming Language :: Python :: 3.7\", \"Programming", "\"https://github.com/bcongdon/instapaper-to-sqlite/issues\", }, classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Environment", "as fp: return fp.read() setup( name=\"instapaper-to-sqlite\", description=\"Save data from Instapaper", "- Production/Stable\", \"Environment :: Console\", \"Programming Language :: Python ::", ":: 3.8\", \"Topic :: Database\", ], keywords=\"instapaper sqlite export dogsheep\",", ":: Database\", ], keywords=\"instapaper sqlite export dogsheep\", version=VERSION, packages=[\"instapaper_to_sqlite\"], entry_points=\"\"\"", "\"Environment :: Console\", \"Programming Language :: Python :: 3\", \"Programming", "\"Source\": \"https://github.com/bcongdon/instapaper-to-sqlite\", \"Issues\": \"https://github.com/bcongdon/instapaper-to-sqlite/issues\", }, classifiers=[ \"Development Status :: 5", "fp: return fp.read() setup( name=\"instapaper-to-sqlite\", description=\"Save data from Instapaper to", "def get_long_description(): with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), \"README.md\"), encoding=\"utf8\", ) as fp:", "to a SQLite database\", long_description=get_long_description(), long_description_content_type=\"text/markdown\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/bcongdon/instapaper-to-sqlite\", project_urls={", "import os from setuptools import setup VERSION = \"0.2\" def", "\"Development Status :: 5 - Production/Stable\", \"Environment :: Console\", \"Programming", "data from Instapaper to a SQLite database\", long_description=get_long_description(), long_description_content_type=\"text/markdown\", author=\"<NAME>\",", "Language :: Python :: 3.8\", \"Topic :: Database\", ], keywords=\"instapaper", "open( os.path.join(os.path.dirname(os.path.abspath(__file__)), \"README.md\"), encoding=\"utf8\", ) as fp: return fp.read() setup(", "setup( name=\"instapaper-to-sqlite\", description=\"Save data from Instapaper to a SQLite database\",", "get_long_description(): with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), \"README.md\"), encoding=\"utf8\", ) as fp: return", "install_requires=[ \"click\", \"requests\", \"sqlite-utils~=3.17\", \"pyinstapaper @ git+https://github.com/bcongdon/pyinstapaper#egg=pyinstapaper\", ], extras_require={\"test\": [\"pytest\"]},", "instapaper-to-sqlite=instapaper_to_sqlite.cli:cli \"\"\", install_requires=[ \"click\", \"requests\", \"sqlite-utils~=3.17\", \"pyinstapaper @ git+https://github.com/bcongdon/pyinstapaper#egg=pyinstapaper\", ],", "[console_scripts] instapaper-to-sqlite=instapaper_to_sqlite.cli:cli \"\"\", install_requires=[ \"click\", \"requests\", \"sqlite-utils~=3.17\", \"pyinstapaper @ git+https://github.com/bcongdon/pyinstapaper#egg=pyinstapaper\",", "3.6\", \"Programming Language :: Python :: 3.7\", \"Programming Language ::", "dogsheep\", version=VERSION, packages=[\"instapaper_to_sqlite\"], entry_points=\"\"\" [console_scripts] instapaper-to-sqlite=instapaper_to_sqlite.cli:cli \"\"\", install_requires=[ \"click\", \"requests\",", "3\", \"Programming Language :: Python :: 3.6\", \"Programming Language ::", "\"requests\", \"sqlite-utils~=3.17\", \"pyinstapaper @ git+https://github.com/bcongdon/pyinstapaper#egg=pyinstapaper\", ], extras_require={\"test\": [\"pytest\"]}, tests_require=[\"instapaper-to-sqlite[test]\"], )", "Database\", ], keywords=\"instapaper sqlite export dogsheep\", version=VERSION, packages=[\"instapaper_to_sqlite\"], entry_points=\"\"\" [console_scripts]", "\"\"\", install_requires=[ \"click\", \"requests\", \"sqlite-utils~=3.17\", \"pyinstapaper @ git+https://github.com/bcongdon/pyinstapaper#egg=pyinstapaper\", ], extras_require={\"test\":", "keywords=\"instapaper sqlite export dogsheep\", version=VERSION, packages=[\"instapaper_to_sqlite\"], entry_points=\"\"\" [console_scripts] instapaper-to-sqlite=instapaper_to_sqlite.cli:cli \"\"\",", "import setup VERSION = \"0.2\" def get_long_description(): with open( os.path.join(os.path.dirname(os.path.abspath(__file__)),", "export dogsheep\", version=VERSION, packages=[\"instapaper_to_sqlite\"], entry_points=\"\"\" [console_scripts] instapaper-to-sqlite=instapaper_to_sqlite.cli:cli \"\"\", install_requires=[ \"click\",", "Instapaper to a SQLite database\", long_description=get_long_description(), long_description_content_type=\"text/markdown\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/bcongdon/instapaper-to-sqlite\",", "\"click\", \"requests\", \"sqlite-utils~=3.17\", \"pyinstapaper @ git+https://github.com/bcongdon/pyinstapaper#egg=pyinstapaper\", ], extras_require={\"test\": [\"pytest\"]}, tests_require=[\"instapaper-to-sqlite[test]\"],", "encoding=\"utf8\", ) as fp: return fp.read() setup( name=\"instapaper-to-sqlite\", description=\"Save data", ":: 3.7\", \"Programming Language :: Python :: 3.8\", \"Topic ::", "long_description=get_long_description(), long_description_content_type=\"text/markdown\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/bcongdon/instapaper-to-sqlite\", project_urls={ \"Source\": \"https://github.com/bcongdon/instapaper-to-sqlite\", \"Issues\": \"https://github.com/bcongdon/instapaper-to-sqlite/issues\",", "database\", long_description=get_long_description(), long_description_content_type=\"text/markdown\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/bcongdon/instapaper-to-sqlite\", project_urls={ \"Source\": \"https://github.com/bcongdon/instapaper-to-sqlite\", \"Issues\":", "from setuptools import setup VERSION = \"0.2\" def get_long_description(): with" ]
[ "the \"latest^{n}\" syntax.', ) self.parser.add_argument( \"refs\", nargs=\"+\", metavar=\"<refs>\", help=\"Benchmarked refs", "sources. \"\"\" usage = \"pybm compare <run> <anchor-ref> <compare-refs> [<options>]\\n\"", "'\"latest\" keyword. To report results ' \"of the n-th preceding", "treated as the \" \"anchor ref, relative to which all", "\" 'use the \"latest^{n}\" syntax.', ) self.parser.add_argument( \"refs\", nargs=\"+\", metavar=\"<refs>\",", "first \" \"given ref will be treated as the \"", "from pybm.reporters import BaseReporter from pybm.status_codes import ERROR, SUCCESS from", "return ERROR self.add_arguments() options = self.parser.parse_args(args) reporter: BaseReporter = get_reporter_class(config=self.config)", "def add_arguments(self): self.parser.add_argument( \"run\", type=str, metavar=\"<run>\", help=\"Benchmark run to report", "type=str, metavar=\"<run>\", help=\"Benchmark run to report results for. \" \"To", "run.\", ) reporter: BaseReporter = get_reporter_class(config=self.config) reporter_args = reporter.additional_arguments() if", "get_reporter_class(config=self.config) # TODO: Parse run to fit schema run =", "benchmark results found for the requested run {run!r}.\" ) return", "result_dir = reporter.result_dir # TODO: Make this dynamic to support", "\" \"refs are not present in the run.\", ) reporter:", "args: self.parser.print_help() return ERROR self.add_arguments() options = self.parser.parse_args(args) reporter: BaseReporter", "result_path.exists(): reporter.compare( *refs, result=result, target_filter=options.target_filter, benchmark_filter=options.benchmark_filter, context_filter=options.context_filter, ) else: raise", "__init__(self): super(CompareCommand, self).__init__(name=\"compare\") self.config = PybmConfig.load() def add_arguments(self): self.parser.add_argument( \"run\",", "the \" '\"latest\" keyword. To report results ' \"of the", "reporter.compare( *refs, result=result, target_filter=options.target_filter, benchmark_filter=options.benchmark_filter, context_filter=options.context_filter, ) else: raise PybmError(", "syntax.', ) self.parser.add_argument( \"refs\", nargs=\"+\", metavar=\"<refs>\", help=\"Benchmarked refs to compare.", "( f\"Additional options from configured reporter class {reporter_name!r}\" ) reporter_group", "ref will be treated as the \" \"anchor ref, relative", "raise PybmError( f\"No benchmark results found for the requested run", "The first \" \"given ref will be treated as the", "\"given ref will be treated as the \" \"anchor ref,", "n-th preceding run \" \"(i.e., n runs ago), \" 'use", "not present in the run.\", ) reporter: BaseReporter = get_reporter_class(config=self.config)", "for. \" \"To report the preceding run, use the \"", "\"raised if any of the given \" \"refs are not", "\" '\"latest\" keyword. To report results ' \"of the n-th", ") else: raise PybmError( f\"No benchmark results found for the", "refs to compare. The first \" \"given ref will be", "as the \" \"anchor ref, relative to which all \"", "= PybmConfig.load() def add_arguments(self): self.parser.add_argument( \"run\", type=str, metavar=\"<run>\", help=\"Benchmark run", "preceding run \" \"(i.e., n runs ago), \" 'use the", "context_filter=options.context_filter, ) else: raise PybmError( f\"No benchmark results found for", "run to fit schema run = options.run refs: List[str] =", "from pybm.config import get_reporter_class from pybm.exceptions import PybmError from pybm.reporters", "run(self, args: List[str]) -> int: if not args: self.parser.print_help() return", "from pybm.status_codes import ERROR, SUCCESS from pybm.util.path import get_subdirs class", "add_arguments(self): self.parser.add_argument( \"run\", type=str, metavar=\"<run>\", help=\"Benchmark run to report results", "reporter_args: reporter_name = self.config.get_value(\"reporter.name\") reporter_group_desc = ( f\"Additional options from", "To report results ' \"of the n-th preceding run \"", "TODO: Make this dynamic to support other run identifiers result", "pybm import PybmConfig from pybm.command import CLICommand from pybm.config import", "{reporter_name!r}\" ) reporter_group = self.parser.add_argument_group(reporter_group_desc) # add builder-specific options into", "PybmConfig.load() def add_arguments(self): self.parser.add_argument( \"run\", type=str, metavar=\"<run>\", help=\"Benchmark run to", "report the preceding run, use the \" '\"latest\" keyword. To", "def run(self, args: List[str]) -> int: if not args: self.parser.print_help()", "result_dir / result if result_path.exists(): reporter.compare( *refs, result=result, target_filter=options.target_filter, benchmark_filter=options.benchmark_filter,", "reporter class {reporter_name!r}\" ) reporter_group = self.parser.add_argument_group(reporter_group_desc) # add builder-specific", "identifiers result = sorted(get_subdirs(result_dir))[-1] result_path = result_dir / result if", "\"\"\" usage = \"pybm compare <run> <anchor-ref> <compare-refs> [<options>]\\n\" def", "\" \"given ref will be treated as the \" \"anchor", "BaseReporter = get_reporter_class(config=self.config) reporter_args = reporter.additional_arguments() if reporter_args: reporter_name =", "import PybmConfig from pybm.command import CLICommand from pybm.config import get_reporter_class", "= get_reporter_class(config=self.config) reporter_args = reporter.additional_arguments() if reporter_args: reporter_name = self.config.get_value(\"reporter.name\")", "class {reporter_name!r}\" ) reporter_group = self.parser.add_argument_group(reporter_group_desc) # add builder-specific options", "reporter_group = self.parser.add_argument_group(reporter_group_desc) # add builder-specific options into the group", "self.parser.add_argument_group(reporter_group_desc) # add builder-specific options into the group for arg", "this dynamic to support other run identifiers result = sorted(get_subdirs(result_dir))[-1]", "= result_dir / result if result_path.exists(): reporter.compare( *refs, result=result, target_filter=options.target_filter,", "\"anchor ref, relative to which all \" \"differences are reported.", "are reported. An error is \" \"raised if any of", "options.refs result_dir = reporter.result_dir # TODO: Make this dynamic to", "<compare-refs> [<options>]\\n\" def __init__(self): super(CompareCommand, self).__init__(name=\"compare\") self.config = PybmConfig.load() def", "/ result if result_path.exists(): reporter.compare( *refs, result=result, target_filter=options.target_filter, benchmark_filter=options.benchmark_filter, context_filter=options.context_filter,", "PybmError( f\"No benchmark results found for the requested run {run!r}.\"", "import CLICommand from pybm.config import get_reporter_class from pybm.exceptions import PybmError", "CompareCommand(CLICommand): \"\"\" Report benchmark results from specified sources. \"\"\" usage", "run \" \"(i.e., n runs ago), \" 'use the \"latest^{n}\"", "result_path = result_dir / result if result_path.exists(): reporter.compare( *refs, result=result,", "from pybm import PybmConfig from pybm.command import CLICommand from pybm.config", "pybm.exceptions import PybmError from pybm.reporters import BaseReporter from pybm.status_codes import", "pybm.reporters import BaseReporter from pybm.status_codes import ERROR, SUCCESS from pybm.util.path", "PybmConfig from pybm.command import CLICommand from pybm.config import get_reporter_class from", "to compare. The first \" \"given ref will be treated", "run identifiers result = sorted(get_subdirs(result_dir))[-1] result_path = result_dir / result", "relative to which all \" \"differences are reported. An error", "specified sources. \"\"\" usage = \"pybm compare <run> <anchor-ref> <compare-refs>", "the run.\", ) reporter: BaseReporter = get_reporter_class(config=self.config) reporter_args = reporter.additional_arguments()", "super(CompareCommand, self).__init__(name=\"compare\") self.config = PybmConfig.load() def add_arguments(self): self.parser.add_argument( \"run\", type=str,", "\" \"(i.e., n runs ago), \" 'use the \"latest^{n}\" syntax.',", "in the run.\", ) reporter: BaseReporter = get_reporter_class(config=self.config) reporter_args =", "self.parser.add_argument( \"run\", type=str, metavar=\"<run>\", help=\"Benchmark run to report results for.", "from specified sources. \"\"\" usage = \"pybm compare <run> <anchor-ref>", "builder-specific options into the group for arg in reporter_args: reporter_group.add_argument(arg.pop(\"flags\"),", "metavar=\"<run>\", help=\"Benchmark run to report results for. \" \"To report", "= \"pybm compare <run> <anchor-ref> <compare-refs> [<options>]\\n\" def __init__(self): super(CompareCommand,", "ERROR self.add_arguments() options = self.parser.parse_args(args) reporter: BaseReporter = get_reporter_class(config=self.config) #", "An error is \" \"raised if any of the given", "for arg in reporter_args: reporter_group.add_argument(arg.pop(\"flags\"), **arg) def run(self, args: List[str])", "from pybm.exceptions import PybmError from pybm.reporters import BaseReporter from pybm.status_codes", "benchmark_filter=options.benchmark_filter, context_filter=options.context_filter, ) else: raise PybmError( f\"No benchmark results found", "n runs ago), \" 'use the \"latest^{n}\" syntax.', ) self.parser.add_argument(", ") self.parser.add_argument( \"refs\", nargs=\"+\", metavar=\"<refs>\", help=\"Benchmarked refs to compare. The", "PybmError from pybm.reporters import BaseReporter from pybm.status_codes import ERROR, SUCCESS", "help=\"Benchmark run to report results for. \" \"To report the", "typing import List from pybm import PybmConfig from pybm.command import", "args: List[str]) -> int: if not args: self.parser.print_help() return ERROR", "**arg) def run(self, args: List[str]) -> int: if not args:", "use the \" '\"latest\" keyword. To report results ' \"of", "= self.parser.add_argument_group(reporter_group_desc) # add builder-specific options into the group for", "group for arg in reporter_args: reporter_group.add_argument(arg.pop(\"flags\"), **arg) def run(self, args:", "ref, relative to which all \" \"differences are reported. An", "target_filter=options.target_filter, benchmark_filter=options.benchmark_filter, context_filter=options.context_filter, ) else: raise PybmError( f\"No benchmark results", "is \" \"raised if any of the given \" \"refs", "to support other run identifiers result = sorted(get_subdirs(result_dir))[-1] result_path =", "if reporter_args: reporter_name = self.config.get_value(\"reporter.name\") reporter_group_desc = ( f\"Additional options", "self.config = PybmConfig.load() def add_arguments(self): self.parser.add_argument( \"run\", type=str, metavar=\"<run>\", help=\"Benchmark", "BaseReporter = get_reporter_class(config=self.config) # TODO: Parse run to fit schema", "schema run = options.run refs: List[str] = options.refs result_dir =", "pybm.status_codes import ERROR, SUCCESS from pybm.util.path import get_subdirs class CompareCommand(CLICommand):", "from pybm.util.path import get_subdirs class CompareCommand(CLICommand): \"\"\" Report benchmark results", "f\"Additional options from configured reporter class {reporter_name!r}\" ) reporter_group =", "<run> <anchor-ref> <compare-refs> [<options>]\\n\" def __init__(self): super(CompareCommand, self).__init__(name=\"compare\") self.config =", "\"run\", type=str, metavar=\"<run>\", help=\"Benchmark run to report results for. \"", "\"refs are not present in the run.\", ) reporter: BaseReporter", "reporter_args = reporter.additional_arguments() if reporter_args: reporter_name = self.config.get_value(\"reporter.name\") reporter_group_desc =", "present in the run.\", ) reporter: BaseReporter = get_reporter_class(config=self.config) reporter_args", "results ' \"of the n-th preceding run \" \"(i.e., n", "keyword. To report results ' \"of the n-th preceding run", "import ERROR, SUCCESS from pybm.util.path import get_subdirs class CompareCommand(CLICommand): \"\"\"", "nargs=\"+\", metavar=\"<refs>\", help=\"Benchmarked refs to compare. The first \" \"given", "support other run identifiers result = sorted(get_subdirs(result_dir))[-1] result_path = result_dir", "else: raise PybmError( f\"No benchmark results found for the requested", "pybm.config import get_reporter_class from pybm.exceptions import PybmError from pybm.reporters import", "\"latest^{n}\" syntax.', ) self.parser.add_argument( \"refs\", nargs=\"+\", metavar=\"<refs>\", help=\"Benchmarked refs to", "arg in reporter_args: reporter_group.add_argument(arg.pop(\"flags\"), **arg) def run(self, args: List[str]) ->", "from pybm.command import CLICommand from pybm.config import get_reporter_class from pybm.exceptions", "reported. An error is \" \"raised if any of the", "results found for the requested run {run!r}.\" ) return SUCCESS", "pybm.util.path import get_subdirs class CompareCommand(CLICommand): \"\"\" Report benchmark results from", "to report results for. \" \"To report the preceding run,", "the preceding run, use the \" '\"latest\" keyword. To report", "# TODO: Make this dynamic to support other run identifiers", "the \" \"anchor ref, relative to which all \" \"differences", "\"To report the preceding run, use the \" '\"latest\" keyword.", "metavar=\"<refs>\", help=\"Benchmarked refs to compare. The first \" \"given ref", ") reporter_group = self.parser.add_argument_group(reporter_group_desc) # add builder-specific options into the", "Make this dynamic to support other run identifiers result =", ") reporter: BaseReporter = get_reporter_class(config=self.config) reporter_args = reporter.additional_arguments() if reporter_args:", "TODO: Parse run to fit schema run = options.run refs:", "pybm.command import CLICommand from pybm.config import get_reporter_class from pybm.exceptions import", "to fit schema run = options.run refs: List[str] = options.refs", "*refs, result=result, target_filter=options.target_filter, benchmark_filter=options.benchmark_filter, context_filter=options.context_filter, ) else: raise PybmError( f\"No", "options = self.parser.parse_args(args) reporter: BaseReporter = get_reporter_class(config=self.config) # TODO: Parse", "\" \"differences are reported. An error is \" \"raised if", "from typing import List from pybm import PybmConfig from pybm.command", "reporter: BaseReporter = get_reporter_class(config=self.config) reporter_args = reporter.additional_arguments() if reporter_args: reporter_name", "self.config.get_value(\"reporter.name\") reporter_group_desc = ( f\"Additional options from configured reporter class", "not args: self.parser.print_help() return ERROR self.add_arguments() options = self.parser.parse_args(args) reporter:", "import BaseReporter from pybm.status_codes import ERROR, SUCCESS from pybm.util.path import", "all \" \"differences are reported. An error is \" \"raised", "options.run refs: List[str] = options.refs result_dir = reporter.result_dir # TODO:", "self.parser.add_argument( \"refs\", nargs=\"+\", metavar=\"<refs>\", help=\"Benchmarked refs to compare. The first", "= ( f\"Additional options from configured reporter class {reporter_name!r}\" )", "into the group for arg in reporter_args: reporter_group.add_argument(arg.pop(\"flags\"), **arg) def", "given \" \"refs are not present in the run.\", )", "List[str] = options.refs result_dir = reporter.result_dir # TODO: Make this", "import PybmError from pybm.reporters import BaseReporter from pybm.status_codes import ERROR,", "of the given \" \"refs are not present in the", "report results for. \" \"To report the preceding run, use", "usage = \"pybm compare <run> <anchor-ref> <compare-refs> [<options>]\\n\" def __init__(self):", "get_reporter_class from pybm.exceptions import PybmError from pybm.reporters import BaseReporter from", "ago), \" 'use the \"latest^{n}\" syntax.', ) self.parser.add_argument( \"refs\", nargs=\"+\",", "which all \" \"differences are reported. An error is \"", "configured reporter class {reporter_name!r}\" ) reporter_group = self.parser.add_argument_group(reporter_group_desc) # add", "refs: List[str] = options.refs result_dir = reporter.result_dir # TODO: Make", "compare. The first \" \"given ref will be treated as", "reporter_group.add_argument(arg.pop(\"flags\"), **arg) def run(self, args: List[str]) -> int: if not", "= self.parser.parse_args(args) reporter: BaseReporter = get_reporter_class(config=self.config) # TODO: Parse run", "result=result, target_filter=options.target_filter, benchmark_filter=options.benchmark_filter, context_filter=options.context_filter, ) else: raise PybmError( f\"No benchmark", "sorted(get_subdirs(result_dir))[-1] result_path = result_dir / result if result_path.exists(): reporter.compare( *refs,", "in reporter_args: reporter_group.add_argument(arg.pop(\"flags\"), **arg) def run(self, args: List[str]) -> int:", "reporter.result_dir # TODO: Make this dynamic to support other run", "if result_path.exists(): reporter.compare( *refs, result=result, target_filter=options.target_filter, benchmark_filter=options.benchmark_filter, context_filter=options.context_filter, ) else:", "error is \" \"raised if any of the given \"", "self.add_arguments() options = self.parser.parse_args(args) reporter: BaseReporter = get_reporter_class(config=self.config) # TODO:", "reporter_args: reporter_group.add_argument(arg.pop(\"flags\"), **arg) def run(self, args: List[str]) -> int: if", "\"of the n-th preceding run \" \"(i.e., n runs ago),", "-> int: if not args: self.parser.print_help() return ERROR self.add_arguments() options", "compare <run> <anchor-ref> <compare-refs> [<options>]\\n\" def __init__(self): super(CompareCommand, self).__init__(name=\"compare\") self.config", "reporter_name = self.config.get_value(\"reporter.name\") reporter_group_desc = ( f\"Additional options from configured", "\" \"raised if any of the given \" \"refs are", "will be treated as the \" \"anchor ref, relative to", "results from specified sources. \"\"\" usage = \"pybm compare <run>", "if any of the given \" \"refs are not present", "help=\"Benchmarked refs to compare. The first \" \"given ref will", "\" \"anchor ref, relative to which all \" \"differences are", "'use the \"latest^{n}\" syntax.', ) self.parser.add_argument( \"refs\", nargs=\"+\", metavar=\"<refs>\", help=\"Benchmarked", "reporter.additional_arguments() if reporter_args: reporter_name = self.config.get_value(\"reporter.name\") reporter_group_desc = ( f\"Additional", "runs ago), \" 'use the \"latest^{n}\" syntax.', ) self.parser.add_argument( \"refs\",", "class CompareCommand(CLICommand): \"\"\" Report benchmark results from specified sources. \"\"\"", "# add builder-specific options into the group for arg in", "run = options.run refs: List[str] = options.refs result_dir = reporter.result_dir", "CLICommand from pybm.config import get_reporter_class from pybm.exceptions import PybmError from", "= options.refs result_dir = reporter.result_dir # TODO: Make this dynamic", "other run identifiers result = sorted(get_subdirs(result_dir))[-1] result_path = result_dir /", "\"pybm compare <run> <anchor-ref> <compare-refs> [<options>]\\n\" def __init__(self): super(CompareCommand, self).__init__(name=\"compare\")", "result if result_path.exists(): reporter.compare( *refs, result=result, target_filter=options.target_filter, benchmark_filter=options.benchmark_filter, context_filter=options.context_filter, )", "List from pybm import PybmConfig from pybm.command import CLICommand from", "benchmark results from specified sources. \"\"\" usage = \"pybm compare", "' \"of the n-th preceding run \" \"(i.e., n runs", "be treated as the \" \"anchor ref, relative to which", "fit schema run = options.run refs: List[str] = options.refs result_dir", "self.parser.parse_args(args) reporter: BaseReporter = get_reporter_class(config=self.config) # TODO: Parse run to", "Parse run to fit schema run = options.run refs: List[str]", "self).__init__(name=\"compare\") self.config = PybmConfig.load() def add_arguments(self): self.parser.add_argument( \"run\", type=str, metavar=\"<run>\",", "run, use the \" '\"latest\" keyword. To report results '", "<anchor-ref> <compare-refs> [<options>]\\n\" def __init__(self): super(CompareCommand, self).__init__(name=\"compare\") self.config = PybmConfig.load()", "import List from pybm import PybmConfig from pybm.command import CLICommand", "\"differences are reported. An error is \" \"raised if any", "import get_reporter_class from pybm.exceptions import PybmError from pybm.reporters import BaseReporter", "preceding run, use the \" '\"latest\" keyword. To report results", "SUCCESS from pybm.util.path import get_subdirs class CompareCommand(CLICommand): \"\"\" Report benchmark", "\" \"To report the preceding run, use the \" '\"latest\"", "the given \" \"refs are not present in the run.\",", "get_reporter_class(config=self.config) reporter_args = reporter.additional_arguments() if reporter_args: reporter_name = self.config.get_value(\"reporter.name\") reporter_group_desc", "def __init__(self): super(CompareCommand, self).__init__(name=\"compare\") self.config = PybmConfig.load() def add_arguments(self): self.parser.add_argument(", "= reporter.additional_arguments() if reporter_args: reporter_name = self.config.get_value(\"reporter.name\") reporter_group_desc = (", "\"\"\" Report benchmark results from specified sources. \"\"\" usage =", "= get_reporter_class(config=self.config) # TODO: Parse run to fit schema run", "f\"No benchmark results found for the requested run {run!r}.\" )", "\"(i.e., n runs ago), \" 'use the \"latest^{n}\" syntax.', )", "reporter: BaseReporter = get_reporter_class(config=self.config) # TODO: Parse run to fit", "add builder-specific options into the group for arg in reporter_args:", "dynamic to support other run identifiers result = sorted(get_subdirs(result_dir))[-1] result_path", "int: if not args: self.parser.print_help() return ERROR self.add_arguments() options =", "run to report results for. \" \"To report the preceding", "= reporter.result_dir # TODO: Make this dynamic to support other", "ERROR, SUCCESS from pybm.util.path import get_subdirs class CompareCommand(CLICommand): \"\"\" Report", "options from configured reporter class {reporter_name!r}\" ) reporter_group = self.parser.add_argument_group(reporter_group_desc)", "= sorted(get_subdirs(result_dir))[-1] result_path = result_dir / result if result_path.exists(): reporter.compare(", "any of the given \" \"refs are not present in", "options into the group for arg in reporter_args: reporter_group.add_argument(arg.pop(\"flags\"), **arg)", "result = sorted(get_subdirs(result_dir))[-1] result_path = result_dir / result if result_path.exists():", "results for. \" \"To report the preceding run, use the", "are not present in the run.\", ) reporter: BaseReporter =", "from configured reporter class {reporter_name!r}\" ) reporter_group = self.parser.add_argument_group(reporter_group_desc) #", "= self.config.get_value(\"reporter.name\") reporter_group_desc = ( f\"Additional options from configured reporter", "import get_subdirs class CompareCommand(CLICommand): \"\"\" Report benchmark results from specified", "reporter_group_desc = ( f\"Additional options from configured reporter class {reporter_name!r}\"", "if not args: self.parser.print_help() return ERROR self.add_arguments() options = self.parser.parse_args(args)", "the n-th preceding run \" \"(i.e., n runs ago), \"", "get_subdirs class CompareCommand(CLICommand): \"\"\" Report benchmark results from specified sources.", "report results ' \"of the n-th preceding run \" \"(i.e.,", "to which all \" \"differences are reported. An error is", "# TODO: Parse run to fit schema run = options.run", "List[str]) -> int: if not args: self.parser.print_help() return ERROR self.add_arguments()", "self.parser.print_help() return ERROR self.add_arguments() options = self.parser.parse_args(args) reporter: BaseReporter =", "Report benchmark results from specified sources. \"\"\" usage = \"pybm", "\"refs\", nargs=\"+\", metavar=\"<refs>\", help=\"Benchmarked refs to compare. The first \"", "[<options>]\\n\" def __init__(self): super(CompareCommand, self).__init__(name=\"compare\") self.config = PybmConfig.load() def add_arguments(self):", "the group for arg in reporter_args: reporter_group.add_argument(arg.pop(\"flags\"), **arg) def run(self,", "BaseReporter from pybm.status_codes import ERROR, SUCCESS from pybm.util.path import get_subdirs", "= options.run refs: List[str] = options.refs result_dir = reporter.result_dir #" ]
[ "velocity_dist(self, v, t): \"\"\" Get the velocity distribution in units", "of velocity :return: observed velocity distribution at earth \"\"\" return", "dict( v_0=self.v_0 / (nu.km / nu.s), v_esc=self.v_esc / (nu.km /", "units) The standard halo model also allows variation of v_0", "# Standard Halo Model (shm) return 'shm' def velocity_dist(self, v,", "else v_0 self.v_esc = 544 * nu.km / nu.s if", "the Earth (multiplied by units) The standard halo model also", "Model (shm) return 'shm' def velocity_dist(self, v, t): \"\"\" Get", "/ (nu.GeV / nu.c0 ** 2 / nu.cm ** 3),", "by units) The standard halo model also allows variation of", "self.v_esc = 544 * nu.km / nu.s if v_esc is", "return 'shm' def velocity_dist(self, v, t): \"\"\" Get the velocity", "None else v_0 self.v_esc = 544 * nu.km / nu.s", "wr.observed_speed_dist(v, t, self.v_0, self.v_esc) def parameter_dict(self): \"\"\"Return a dict of", "v_esc is None else v_esc self.rho_dm = (0.3 * nu.GeV", "/ nu.cm ** 3 if rho_dm is None else rho_dm)", "__init__(self, v_0=None, v_esc=None, rho_dm=None): self.v_0 = 230 * nu.km /", "3 if rho_dm is None else rho_dm) def __str__(self): #", "import dddm export, __all__ = dddm.exporter() @export class SHM: \"\"\"", "halo model to the rate computation must contain: :param v_esc", "distribution at earth \"\"\" return wr.observed_speed_dist(v, t, self.v_0, self.v_esc) def", "settings\"\"\" return dict( v_0=self.v_0 / (nu.km / nu.s), v_esc=self.v_esc /", "self.v_0 = 230 * nu.km / nu.s if v_0 is", "as wr import dddm export, __all__ = dddm.exporter() @export class", "WIMPrate for a given detector (not taking into account any", "escape velocity (multiplied by units) :param rho_dm -- density in", "earth rest-frame. \"\"\" def __init__(self, v_0=None, v_esc=None, rho_dm=None): self.v_0 =", "v_esc=None, rho_dm=None): self.v_0 = 230 * nu.km / nu.s if", "is in units of velocity :return: observed velocity distribution at", "self.v_0, self.v_esc) def parameter_dict(self): \"\"\"Return a dict of readable parameters", "a given detector (not taking into account any detector effects", "/ (nu.km / nu.s), v_esc=self.v_esc / (nu.km / nu.s), rho_dm=self.rho_dm", "rho_dm=self.rho_dm / (nu.GeV / nu.c0 ** 2 / nu.cm **", "2 / nu.cm ** 3 if rho_dm is None else", "effects \"\"\" import numericalunits as nu import wimprates as wr", "rho_dm) def __str__(self): # Standard Halo Model (shm) return 'shm'", "v,t giving normalised velocity distribution in earth rest-frame. \"\"\" def", "Earth (multiplied by units) The standard halo model also allows", ":param v_esc -- escape velocity (multiplied by units) :param rho_dm", "density in mass/volume of dark matter at the Earth (multiplied", "v is in units of velocity :return: observed velocity distribution", "544 * nu.km / nu.s if v_esc is None else", "(0.3 * nu.GeV / nu.c0 ** 2 / nu.cm **", "velocity distribution in units of per velocity, :param v: v", "a halo model to the rate computation must contain: :param", "v_esc self.rho_dm = (0.3 * nu.GeV / nu.c0 ** 2", "parameters of the current settings\"\"\" return dict( v_0=self.v_0 / (nu.km", "/ (nu.km / nu.s), rho_dm=self.rho_dm / (nu.GeV / nu.c0 **", "(multiplied by units) :function velocity_dist -- function taking v,t giving", "(nu.GeV / nu.c0 ** 2 / nu.cm ** 3), )", "velocity_dist -- function taking v,t giving normalised velocity distribution in", ":function velocity_dist -- function taking v,t giving normalised velocity distribution", "in mass/volume of dark matter at the Earth (multiplied by", "as nu import wimprates as wr import dddm export, __all__", "to the rate computation must contain: :param v_esc -- escape", "def __init__(self, v_0=None, v_esc=None, rho_dm=None): self.v_0 = 230 * nu.km", "None else v_esc self.rho_dm = (0.3 * nu.GeV / nu.c0", "v, t): \"\"\" Get the velocity distribution in units of", "given detector get a WIMPrate for a given detector (not", "halo model also allows variation of v_0 :param v_0 --", "nu.c0 ** 2 / nu.cm ** 3 if rho_dm is", "is None else v_esc self.rho_dm = (0.3 * nu.GeV /", "Halo Model (shm) return 'shm' def velocity_dist(self, v, t): \"\"\"", "(nu.km / nu.s), rho_dm=self.rho_dm / (nu.GeV / nu.c0 ** 2", "in earth rest-frame. \"\"\" def __init__(self, v_0=None, v_esc=None, rho_dm=None): self.v_0", "self.v_esc) def parameter_dict(self): \"\"\"Return a dict of readable parameters of", "units of velocity :return: observed velocity distribution at earth \"\"\"", "the velocity distribution (multiplied by units) :function velocity_dist -- function", "* nu.GeV / nu.c0 ** 2 / nu.cm ** 3", "= (0.3 * nu.GeV / nu.c0 ** 2 / nu.cm", "nu import wimprates as wr import dddm export, __all__ =", "return dict( v_0=self.v_0 / (nu.km / nu.s), v_esc=self.v_esc / (nu.km", "allows variation of v_0 :param v_0 -- v0 of the", "import numericalunits as nu import wimprates as wr import dddm", "the velocity distribution in units of per velocity, :param v:", "'shm' def velocity_dist(self, v, t): \"\"\" Get the velocity distribution", "must contain: :param v_esc -- escape velocity (multiplied by units)", "if v_0 is None else v_0 self.v_esc = 544 *", "__all__ = dddm.exporter() @export class SHM: \"\"\" class used to", "* nu.km / nu.s if v_0 is None else v_0", "computation must contain: :param v_esc -- escape velocity (multiplied by", "(multiplied by units) :param rho_dm -- density in mass/volume of", "model to the rate computation must contain: :param v_esc --", "rho_dm -- density in mass/volume of dark matter at the", "The standard halo model also allows variation of v_0 :param", "/ nu.s), v_esc=self.v_esc / (nu.km / nu.s), rho_dm=self.rho_dm / (nu.GeV", "given detector (not taking into account any detector effects \"\"\"", "nu.s if v_esc is None else v_esc self.rho_dm = (0.3", "None else rho_dm) def __str__(self): # Standard Halo Model (shm)", "\"\"\" For a given detector get a WIMPrate for a", "detector get a WIMPrate for a given detector (not taking", "at earth \"\"\" return wr.observed_speed_dist(v, t, self.v_0, self.v_esc) def parameter_dict(self):", "mass/volume of dark matter at the Earth (multiplied by units)", "nu.km / nu.s if v_0 is None else v_0 self.v_esc", "/ nu.c0 ** 2 / nu.cm ** 3 if rho_dm", "-- escape velocity (multiplied by units) :param rho_dm -- density", "a dict of readable parameters of the current settings\"\"\" return", "For a given detector get a WIMPrate for a given", "dark matter at the Earth (multiplied by units) The standard", "rate computation must contain: :param v_esc -- escape velocity (multiplied", "= 230 * nu.km / nu.s if v_0 is None", "a WIMPrate for a given detector (not taking into account", "is None else v_0 self.v_esc = 544 * nu.km /", "nu.GeV / nu.c0 ** 2 / nu.cm ** 3 if", "velocity distribution at earth \"\"\" return wr.observed_speed_dist(v, t, self.v_0, self.v_esc)", "of v_0 :param v_0 -- v0 of the velocity distribution", "v_0 :param v_0 -- v0 of the velocity distribution (multiplied", "also allows variation of v_0 :param v_0 -- v0 of", "** 2 / nu.cm ** 3 if rho_dm is None", "= dddm.exporter() @export class SHM: \"\"\" class used to pass", "per velocity, :param v: v is in units of velocity", "\"\"\" return wr.observed_speed_dist(v, t, self.v_0, self.v_esc) def parameter_dict(self): \"\"\"Return a", "v_0 -- v0 of the velocity distribution (multiplied by units)", "variation of v_0 :param v_0 -- v0 of the velocity", "account any detector effects \"\"\" import numericalunits as nu import", "rho_dm=None): self.v_0 = 230 * nu.km / nu.s if v_0", "(multiplied by units) The standard halo model also allows variation", "-- density in mass/volume of dark matter at the Earth", "giving normalised velocity distribution in earth rest-frame. \"\"\" def __init__(self,", "* nu.km / nu.s if v_esc is None else v_esc", "contain: :param v_esc -- escape velocity (multiplied by units) :param", "/ nu.s if v_0 is None else v_0 self.v_esc =", "dddm.exporter() @export class SHM: \"\"\" class used to pass a", ":param rho_dm -- density in mass/volume of dark matter at", "class SHM: \"\"\" class used to pass a halo model", "/ nu.s if v_esc is None else v_esc self.rho_dm =", "Standard Halo Model (shm) return 'shm' def velocity_dist(self, v, t):", "\"\"\" def __init__(self, v_0=None, v_esc=None, rho_dm=None): self.v_0 = 230 *", "any detector effects \"\"\" import numericalunits as nu import wimprates", "nu.s), v_esc=self.v_esc / (nu.km / nu.s), rho_dm=self.rho_dm / (nu.GeV /", ":return: observed velocity distribution at earth \"\"\" return wr.observed_speed_dist(v, t,", "velocity :return: observed velocity distribution at earth \"\"\" return wr.observed_speed_dist(v,", "taking v,t giving normalised velocity distribution in earth rest-frame. \"\"\"", "if rho_dm is None else rho_dm) def __str__(self): # Standard", "-- v0 of the velocity distribution (multiplied by units) :function", "** 3 if rho_dm is None else rho_dm) def __str__(self):", "nu.s if v_0 is None else v_0 self.v_esc = 544", "t): \"\"\" Get the velocity distribution in units of per", "numericalunits as nu import wimprates as wr import dddm export,", "__str__(self): # Standard Halo Model (shm) return 'shm' def velocity_dist(self,", "\"\"\" Get the velocity distribution in units of per velocity,", "(nu.km / nu.s), v_esc=self.v_esc / (nu.km / nu.s), rho_dm=self.rho_dm /", "v_esc=self.v_esc / (nu.km / nu.s), rho_dm=self.rho_dm / (nu.GeV / nu.c0", "used to pass a halo model to the rate computation", "@export class SHM: \"\"\" class used to pass a halo", "\"\"\"Return a dict of readable parameters of the current settings\"\"\"", "of the velocity distribution (multiplied by units) :function velocity_dist --", "wr import dddm export, __all__ = dddm.exporter() @export class SHM:", "the rate computation must contain: :param v_esc -- escape velocity", "SHM: \"\"\" class used to pass a halo model to", "-- function taking v,t giving normalised velocity distribution in earth", "= 544 * nu.km / nu.s if v_esc is None", "def __str__(self): # Standard Halo Model (shm) return 'shm' def", "nu.s), rho_dm=self.rho_dm / (nu.GeV / nu.c0 ** 2 / nu.cm", "of the current settings\"\"\" return dict( v_0=self.v_0 / (nu.km /", "v_0=None, v_esc=None, rho_dm=None): self.v_0 = 230 * nu.km / nu.s", "matter at the Earth (multiplied by units) The standard halo", "else rho_dm) def __str__(self): # Standard Halo Model (shm) return", "distribution in units of per velocity, :param v: v is", "to pass a halo model to the rate computation must", "at the Earth (multiplied by units) The standard halo model", "velocity distribution in earth rest-frame. \"\"\" def __init__(self, v_0=None, v_esc=None,", "units) :param rho_dm -- density in mass/volume of dark matter", "by units) :param rho_dm -- density in mass/volume of dark", "taking into account any detector effects \"\"\" import numericalunits as", "observed velocity distribution at earth \"\"\" return wr.observed_speed_dist(v, t, self.v_0,", "get a WIMPrate for a given detector (not taking into", "velocity (multiplied by units) :param rho_dm -- density in mass/volume", "v_esc -- escape velocity (multiplied by units) :param rho_dm --", "pass a halo model to the rate computation must contain:", "230 * nu.km / nu.s if v_0 is None else", "dddm export, __all__ = dddm.exporter() @export class SHM: \"\"\" class", "else v_esc self.rho_dm = (0.3 * nu.GeV / nu.c0 **", "dict of readable parameters of the current settings\"\"\" return dict(", "model also allows variation of v_0 :param v_0 -- v0", "distribution in earth rest-frame. \"\"\" def __init__(self, v_0=None, v_esc=None, rho_dm=None):", "by units) :function velocity_dist -- function taking v,t giving normalised", "self.rho_dm = (0.3 * nu.GeV / nu.c0 ** 2 /", "class used to pass a halo model to the rate", "current settings\"\"\" return dict( v_0=self.v_0 / (nu.km / nu.s), v_esc=self.v_esc", "\"\"\" import numericalunits as nu import wimprates as wr import", "wimprates as wr import dddm export, __all__ = dddm.exporter() @export", "of dark matter at the Earth (multiplied by units) The", ":param v: v is in units of velocity :return: observed", "in units of per velocity, :param v: v is in", "of readable parameters of the current settings\"\"\" return dict( v_0=self.v_0", "v_0 self.v_esc = 544 * nu.km / nu.s if v_esc", "in units of velocity :return: observed velocity distribution at earth", "v_0 is None else v_0 self.v_esc = 544 * nu.km", "return wr.observed_speed_dist(v, t, self.v_0, self.v_esc) def parameter_dict(self): \"\"\"Return a dict", "for a given detector (not taking into account any detector", "export, __all__ = dddm.exporter() @export class SHM: \"\"\" class used", "def velocity_dist(self, v, t): \"\"\" Get the velocity distribution in", "Get the velocity distribution in units of per velocity, :param", "earth \"\"\" return wr.observed_speed_dist(v, t, self.v_0, self.v_esc) def parameter_dict(self): \"\"\"Return", "(not taking into account any detector effects \"\"\" import numericalunits", "is None else rho_dm) def __str__(self): # Standard Halo Model", "import wimprates as wr import dddm export, __all__ = dddm.exporter()", "parameter_dict(self): \"\"\"Return a dict of readable parameters of the current", "velocity, :param v: v is in units of velocity :return:", "rho_dm is None else rho_dm) def __str__(self): # Standard Halo", "velocity distribution (multiplied by units) :function velocity_dist -- function taking", "into account any detector effects \"\"\" import numericalunits as nu", "\"\"\" class used to pass a halo model to the", "distribution (multiplied by units) :function velocity_dist -- function taking v,t", "readable parameters of the current settings\"\"\" return dict( v_0=self.v_0 /", "function taking v,t giving normalised velocity distribution in earth rest-frame.", "v_0=self.v_0 / (nu.km / nu.s), v_esc=self.v_esc / (nu.km / nu.s),", ":param v_0 -- v0 of the velocity distribution (multiplied by", "(shm) return 'shm' def velocity_dist(self, v, t): \"\"\" Get the", "detector effects \"\"\" import numericalunits as nu import wimprates as", "a given detector get a WIMPrate for a given detector", "rest-frame. \"\"\" def __init__(self, v_0=None, v_esc=None, rho_dm=None): self.v_0 = 230", "nu.cm ** 3 if rho_dm is None else rho_dm) def", "units of per velocity, :param v: v is in units", "/ nu.s), rho_dm=self.rho_dm / (nu.GeV / nu.c0 ** 2 /", "units) :function velocity_dist -- function taking v,t giving normalised velocity", "normalised velocity distribution in earth rest-frame. \"\"\" def __init__(self, v_0=None,", "of per velocity, :param v: v is in units of", "t, self.v_0, self.v_esc) def parameter_dict(self): \"\"\"Return a dict of readable", "def parameter_dict(self): \"\"\"Return a dict of readable parameters of the", "if v_esc is None else v_esc self.rho_dm = (0.3 *", "standard halo model also allows variation of v_0 :param v_0", "nu.km / nu.s if v_esc is None else v_esc self.rho_dm", "v0 of the velocity distribution (multiplied by units) :function velocity_dist", "detector (not taking into account any detector effects \"\"\" import", "v: v is in units of velocity :return: observed velocity", "the current settings\"\"\" return dict( v_0=self.v_0 / (nu.km / nu.s)," ]
[ "else value) for key, value in dict_op.items()} dirty_row_pos = mask.any(dim=1).bool()", "'eval_z_kld_final_clean_cc': vae_z_kld_cc.item()/n_clean_rows, 'eval_w_kld_final_clean_cc':vae_w_kld_cc.item()/n_clean_rows, 'eval_loss_final_clean_all': (vae_loss_cc+vae_loss_dc).item()/eval_data_len, 'eval_nll_final_clean_all':(vae_nll_cc+vae_nll_dc).item()/eval_data_len, 'eval_z_kld_final_clean_all': (vae_z_kld_cc+vae_z_kld_dc).item()/eval_data_len, 'eval_w_kld_final_clean_all':(vae_w_kld_cc+vae_w_kld_dc).item()/eval_data_len, 'mse_lower_bd_dirtycells':", "dirty data if args.inference_type == 'seqvae': p_params_xd, q_params_xd, q_samples_xd =", "clean_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, clean_row_pos) vae_loss_cc, vae_nll_cc, vae_z_kld_cc, vae_w_kld_cc =", "= torch.tensor(0.0) seq_final_w_kld = torch.tensor(0.0) optimizer.step() if batch_idx % args.log_interval", "q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) clean_row_pos = ~dirty_row_pos n_clean_rows = clean_row_pos.sum().item() p_params_xd_sliced", "args, epoch, clean_comp_show=False, data_eval_clean=False, logit_pi_prev=torch.tensor([]), w_conv=False, mask_err=None): # if args.cuda_on:", "p_params_xd, q_params_xd, q_samples_xd = model(data_dirty) if not args.AVI: get_pi_exact_vec(model, data_dirty,", "lambda dict_op, row_pos: {key:(value[row_pos,:] \\ if value.shape[0]==data_dirty.shape[0] else value) for", "torch from torch import optim import torch.nn.functional as F import", "mode, epoch): model.eval() # model params with input: dirty data", "utils.error_computation(model, data_clean, p_params_xd['x'], mask) # x_truth - f_vae(x_dirty) print(\"\\n\\n {}", "error_repair_dc.item(), 'mse_repair_cleancells': error_repair_cc.item(), 'errors_per_feature': [error_lb_dc_per_feat, error_repair_dc_per_feat, error_up_dc_per_feat, error_repair_cc_per_feat]} return losses", "= (p_params, q_params, q_samples) if args.seqvae_two_stage: seq_loss_pack, _, seq_param_pack =", "q_params, q_samples) seq_loss_pack, _, _ = rnn_vae_forward_one_stage(params_in, data_input, model, vae_loss,", "train_nll_vae += vae_nll.item() train_z_kld_vae += vae_z_kld.item() train_w_kld_vae += vae_w_kld.item() if", "= 4*[0] train_loss_seq, train_nll_seq, train_z_kld_seq, train_w_kld_seq = 4*[0] train_total_loss_seq_vae, train_loss_seq_vae,", "if clean_comp_show: loss_clean, nll_clean, z_kld_clean, w_kld_clean = model.loss_function(data_eval, p_params_metric, q_params_metric,", "{:.3f}\\tVAE KLD_Z: {:.3f}\\tVAE KLD_W: {:.3f}'.format( epoch, batch_idx * len(data_input), len(train_loader.dataset),", "# x_truth - f_vae(x_dirty) print(\"\\n\\n {} REPAIR ERROR (DIRTY POS):{}\".format(mode,", "model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _,", "model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll,", "# NOTE: rolls out iterations through time and bprops params_in", "type(None): mask_err = mask_err.bool() model.eval() p_params, q_params, q_samples = model(data_eval)", "vae_w_kld = model.loss_function(data_eval, p_params, q_params, q_samples) eval_data_len = data_eval.shape[0] losses", "{:.3f}\\tFinal Sep NLL: {:.3f}\\tFinal Sep KLD_Z: {:.3f}\\tFinal Sep KLD_W: {:.3f}\\n'.format(", "epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack p_params_final, q_params_final,", "seq_param_pack = rnn_vae_forward_two_stage(params_in, data_eval, model, vae_loss, args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True,", "value in dict_op.items()} dirty_row_pos = mask.any(dim=1).bool() n_dirty_rows = dirty_row_pos.sum().item() p_params_xd_sliced", "q_params_xd, args, logit_ret=True) # get pi # model params with", "error repair, on dirty cell positions only error_repair_dc, error_repair_dc_per_feat =", "positions only (to test impact on dirty cells on clean", "q_params_xc, q_samples_xc) = rnn_vae_forward_one_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps,", "model.loss_function(data_clean[clean_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) eval_data_len = data_dirty.shape[0] losses", "import argparse from sklearn.metrics import mean_squared_error import numpy as np", "as F import argparse from sklearn.metrics import mean_squared_error import numpy", "error_lb_dc, error_lb_dc_per_feat = utils.error_computation(model, data_clean, p_params_xc['x'], mask) # x_truth -", "loss_per_iter=True, epoch_id=epoch) else: # standard 'vae' type inference p_params_xd, q_params_xd,", "(pi's) if w_conv: if logit_pi_prev.nelement() == 0: logit_pi_prev = torch.zeros_like(q_params_metric['w']['logit_pi'])", "losses = {'eval_loss_final_clean_dc': vae_loss_dc.item()/n_dirty_rows, 'eval_nll_final_clean_dc':vae_nll_dc.item()/n_dirty_rows, 'eval_z_kld_final_clean_dc': vae_z_kld_dc.item()/n_dirty_rows, 'eval_w_kld_final_clean_dc':vae_w_kld_dc.item()/n_dirty_rows, 'eval_loss_final_clean_cc': vae_loss_cc.item()/n_clean_rows,", "torch.no_grad(): if args.outlier_model == \"VAE\": # VAE models only (no", "evaluation_phase(model, data_eval, dataset_obj, args, epoch, clean_comp_show=False, data_eval_clean=False, logit_pi_prev=torch.tensor([]), w_conv=False, mask_err=None):", "mask.any(dim=1).bool() n_dirty_rows = dirty_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, dirty_row_pos) q_params_xd_sliced =", "NOTE: rolls out iterations through time and bprops params_in =", "= {**ret, **ret_seq} return ret def evaluation_phase(model, data_eval, dataset_obj, args,", "NLL: {:.3f}\\tVAE KLD_Z: {:.3f}\\tVAE KLD_W: {:.3f}'.format( epoch, batch_idx * len(data_input),", "logit_ret=True) # get pi vae_loss, vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_eval,", "train_w_kld_vae = 4*[0] train_loss_seq, train_nll_seq, train_z_kld_seq, train_w_kld_seq = 4*[0] train_total_loss_seq_vae,", "losses_seq_vae = {'eval_loss_seq': seq_final_loss.item()/eval_data_len, 'eval_nll_seq': seq_final_nll.item()/eval_data_len, 'eval_z_kld_seq': seq_final_z_kld.item()/eval_data_len, 'eval_w_kld_seq': seq_final_w_kld.item()/eval_data_len,", "data if args.inference_type == 'seqvae': p_params_xc, q_params_xc, q_samples_xc = model(data_clean)", "= 4*[0] train_total_loss_seq_vae, train_loss_seq_vae, train_nll_seq_vae, train_z_kld_seq_vae, train_w_kld_seq_vae = 5*[0] for", "component if neededin_aux_samples with torch.no_grad(): if args.outlier_model == \"VAE\": #", "batch_idx / len(train_loader), vae_loss.item()/len(data_input), vae_nll.item()/len(data_input), vae_z_kld.item()/len(data_input), vae_w_kld.item()/len(data_input))) if args.inference_type ==", "in outlier score pi_score_mat = torch.sigmoid(q_params_metric['w']['logit_pi']).clamp(1e-6, 1-1e-6) # -log p(x|z,", "p(x|z, ...) used as outlier score nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval,", "_, (p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_one_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device),", "1-1e-6) # -log p(x|z, ...) used as outlier score nll_score_mat", "'vae' type inference p_params_xc, q_params_xc, q_samples_xc = model(data_clean) # no", "p_params_xd_sliced = dict_slice(p_params_xd, clean_row_pos) q_params_xd_sliced = dict() if args.outlier_model ==", "utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) pi_score_mat = -10 converg_norm_w = -10 else:", "<filename>picket/rvae/train_eval_models.py<gh_stars>1-10 #!/usr/bin/env python3 import torch from torch import optim import", "5*[0] for batch_idx, unpack in enumerate(train_loader): data_input = unpack[0] if", "data_eval.shape[0] losses = {'eval_loss_vae': vae_loss.item()/eval_data_len, 'eval_nll_vae':vae_nll.item()/eval_data_len, 'eval_z_kld_vae': vae_z_kld.item()/eval_data_len, 'eval_w_kld_vae':vae_w_kld.item()/eval_data_len} #", "-log p(x|z, ...) used as outlier score nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric,", "logit_pi_prev=torch.tensor([]), w_conv=False, mask_err=None): # if args.cuda_on: # model.cpu() if type(mask_err)", "seq_final_loss.item() train_nll_seq_vae += seq_final_nll.item() train_z_kld_seq_vae += seq_final_z_kld.item() train_w_kld_seq_vae += seq_final_w_kld.item()", "or pi's) # generative model only p(x|z, ...) nll_score_mat =", "loss_clean.item()/eval_data_len, 'eval_nll_final_clean': nll_clean.item()/eval_data_len, 'eval_z_kld_final_clean': z_kld_clean.item()/eval_data_len, 'eval_w_kld_final_clean': w_kld_clean.item()/eval_data_len } losses =", "pi # model params with input: underlying clean data if", "on dirty cell positions only error_repair_dc, error_repair_dc_per_feat = utils.error_computation(model, data_clean,", "data_input, model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll,", "torch.tensor(0.0) seq_final_z_kld = torch.tensor(0.0) seq_final_w_kld = torch.tensor(0.0) optimizer.step() if batch_idx", "seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack train_total_loss_seq_vae += seq_total_loss.item()", "from sklearn.metrics import mean_squared_error import numpy as np import json", "data if args.inference_type == 'seqvae': p_params_xd, q_params_xd, q_samples_xd = model(data_dirty)", "number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: # standard 'vae' type inference p_params_xd,", "error_repair_dc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'], mask) # x_truth - f_vae(x_dirty)", "1-mask) print(\"\\n\\n {} REPAIR ERROR (CLEAN POS):{}\".format(mode, error_repair_cc)) # Get", "if w_conv: if logit_pi_prev.nelement() == 0: logit_pi_prev = torch.zeros_like(q_params_metric['w']['logit_pi']) converg_norm_w", "x_truth - x_dirty # error on clean cell positions only", "elif args.inference_type == 'seqvae': if args.seqvae_bprop: # NOTE: rolls out", "ce_pi = F.binary_cross_entropy(pi_mtx, pi_mtx_true) print('MSE on pi pred: {}'.format(err_pi)) print('CE", "(p_params_xc, q_params_xc, q_samples_xc) if args.seqvae_two_stage: _, _, (p_params_xc, q_params_xc, q_samples_xc)", "{:.3f}'.format( epoch, batch_idx * len(data_input), len(train_loader.dataset), 100. * batch_idx /", "row_pos: {key:(value[row_pos,:] \\ if value.shape[0]==data_dirty.shape[0] else value) for key, value", "'eval_nll_vae':vae_nll.item()/eval_data_len, 'eval_z_kld_vae': vae_z_kld.item()/eval_data_len, 'eval_w_kld_vae':vae_w_kld.item()/eval_data_len} # SEQ-VAE if args.inference_type == 'seqvae':", "else: # 'vae' type inference p_params_xc, q_params_xc, q_samples_xc = model(data_clean)", "'converg_norm_w': converg_norm_w} return losses, metrics def repair_phase(model, data_dirty, data_clean, dataset_obj,", "p_params_xc['x'], mask) # x_truth - f_vae(x_clean) # error repair, on", "rnn_vae_forward_one_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else:", "vae_z_kld_dc, vae_w_kld_dc = model.loss_function(data_clean[dirty_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) clean_row_pos", "loss_per_iter=True, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack train_total_loss_seq_vae", "args.seqvae_two_stage: _, _, (p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_two_stage(params_xd_in, data_dirty, model,", "= -10 # insert here measurement of calibration of pi's", "data_dirty, mask, x_input_size=True) # x_truth - x_dirty # error on", "vae_nll.item() train_z_kld_seq_vae += vae_z_kld.item() train_w_kld_seq_vae += vae_w_kld.item() seq_total_loss = torch.tensor(0.0)", "# error repair, on dirty cell positions only error_repair_dc, error_repair_dc_per_feat", "approx) under dirty data dict_slice = lambda dict_op, row_pos: {key:(value[row_pos,:]", "'mse_upper_bd_dirtycells': error_up_dc.item() , 'mse_repair_dirtycells': error_repair_dc.item(), 'mse_repair_cleancells': error_repair_cc.item(), 'errors_per_feature': [error_lb_dc_per_feat, error_repair_dc_per_feat,", "training_phase(model, optimizer, train_loader, args, epoch, mute=True): model.train() train_loss_vae, train_nll_vae, train_z_kld_vae,", "_ = rnn_vae_forward_one_stage(params_in, data_input, model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch)", "# get pi, saves to q_params (with no_grad) vae_loss, vae_nll,", "q_samples_metric = p_params_final, q_params_final, q_samples_final else: p_params_metric, q_params_metric, q_samples_metric =", "+= vae_w_kld.item() if args.inference_type == 'vae': vae_loss.backward() elif args.inference_type ==", "+= seq_final_w_kld.item() else: vae_loss.backward() train_total_loss_seq_vae += vae_loss.item() train_loss_seq_vae += vae_loss.item()", "train_nll_vae/dataset_len, 'train_z_kld_vae': train_z_kld_vae/dataset_len, 'train_w_kld_vae': train_w_kld_vae/dataset_len} if args.inference_type == \"seqvae\": ret_seq", "seq_final_w_kld = seq_loss_pack p_params_final, q_params_final, q_samples_final = seq_param_pack losses_seq_vae =", "p_params_final, q_params_final, q_samples_final = seq_param_pack losses_seq_vae = {'eval_loss_seq': seq_final_loss.item()/eval_data_len, 'eval_nll_seq':", "model params with input: dirty data if args.inference_type == 'seqvae':", "-10 # insert here measurement of calibration of pi's using", "epoch): model.eval() # model params with input: dirty data if", "dirty_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, dirty_row_pos) q_params_xd_sliced = dict() if args.outlier_model", "vae_loss.item()/eval_data_len, 'eval_nll_vae':vae_nll.item()/eval_data_len, 'eval_z_kld_vae': vae_z_kld.item()/eval_data_len, 'eval_w_kld_vae':vae_w_kld.item()/eval_data_len} # SEQ-VAE if args.inference_type ==", "w_kld_clean.item()/eval_data_len } losses = {**losses, **losses_add} # q(w|x, ...) param", "= dict_slice(q_params_xd['z'], dirty_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, dirty_row_pos) vae_loss_dc, vae_nll_dc, vae_z_kld_dc,", "q_params (with no_grad) vae_loss, vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_input, p_params,", "not mute: print('\\n\\nTrain Epoch: {} [{}/{} ({:.0f}%)]\\tVAE Loss: {:.3f}\\tVAE NLL:", "dict_slice(p_params_xd, clean_row_pos) q_params_xd_sliced = dict() if args.outlier_model == 'RVAE': q_params_xd_sliced['w']", "+= vae_loss.item() train_nll_vae += vae_nll.item() train_z_kld_vae += vae_z_kld.item() train_w_kld_vae +=", "vae_loss, vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_eval, p_params, q_params, q_samples) eval_data_len", "epoch_id=epoch) else: seq_loss_pack, _, seq_param_pack = rnn_vae_forward_one_stage(params_in, data_eval, model, vae_loss,", "seq_param_pack losses_seq_vae = {'eval_loss_seq': seq_final_loss.item()/eval_data_len, 'eval_nll_seq': seq_final_nll.item()/eval_data_len, 'eval_z_kld_seq': seq_final_z_kld.item()/eval_data_len, 'eval_w_kld_seq':", "else: vae_loss.backward() train_total_loss_seq_vae += vae_loss.item() train_loss_seq_vae += vae_loss.item() train_nll_seq_vae +=", "(pi), used in outlier score pi_score_mat = torch.sigmoid(q_params_metric['w']['logit_pi']).clamp(1e-6, 1-1e-6) #", "numpy as np import json from . import utils from", "mask_err=None): # if args.cuda_on: # model.cpu() if type(mask_err) != type(None):", "seq_final_w_kld = seq_loss_pack train_total_loss_seq_vae += seq_total_loss.item() train_loss_seq_vae += seq_final_loss.item() train_nll_seq_vae", "on dirty cells on clean cells under model) error_repair_cc, error_repair_cc_per_feat", "{**losses, **losses_seq_vae} if args.inference_type == 'seqvae': p_params_metric, q_params_metric, q_samples_metric =", "vae_z_kld.item() train_w_kld_seq_vae += vae_w_kld.item() seq_total_loss = torch.tensor(0.0) seq_final_loss = torch.tensor(0.0)", "data_dirty, p_params_xd, q_params_xd, args, logit_ret=True) # get pi # model", "dirty_row_pos = mask.any(dim=1).bool() n_dirty_rows = dirty_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, dirty_row_pos)", "= model(data_input, n_epoch=epoch-1) if not args.AVI: get_pi_exact_vec(model, data_input, p_params, q_params,", "= dict_slice(q_params_xd['z'], clean_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, clean_row_pos) vae_loss_cc, vae_nll_cc, vae_z_kld_cc,", "data_eval, p_params, q_params, args, logit_ret=True) # get pi vae_loss, vae_nll,", "rnn_vae_forward_one_stage, rnn_vae_forward_two_stage def training_phase(model, optimizer, train_loader, args, epoch, mute=True): model.train()", "{'eval_loss_final_clean': loss_clean.item()/eval_data_len, 'eval_nll_final_clean': nll_clean.item()/eval_data_len, 'eval_z_kld_final_clean': z_kld_clean.item()/eval_data_len, 'eval_w_kld_final_clean': w_kld_clean.item()/eval_data_len } losses", "clean cell positions only (to test impact on dirty cells", "F import argparse from sklearn.metrics import mean_squared_error import numpy as", "q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], clean_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], clean_row_pos) q_samples_xd_sliced =", "nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) # check convergence of weights", "loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack", "z_kld_clean.item()/eval_data_len, 'eval_w_kld_final_clean': w_kld_clean.item()/eval_data_len } losses = {**losses, **losses_add} # q(w|x,", "only error_lb_dc, error_lb_dc_per_feat = utils.error_computation(model, data_clean, p_params_xc['x'], mask) # x_truth", "nll_clean, z_kld_clean, w_kld_clean = model.loss_function(data_eval, p_params_metric, q_params_metric, q_samples_metric, clean_comp_only=True, data_eval_clean=data_eval_clean)", "error (MSE) lower bound, on dirty cell positions only error_lb_dc,", "'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], clean_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], clean_row_pos) q_samples_xd_sliced", "rnn_vae_forward_two_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch)", "data_eval, model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) seq_total_loss, seq_final_loss,", "seq_final_loss.item()/eval_data_len, 'eval_nll_seq': seq_final_nll.item()/eval_data_len, 'eval_z_kld_seq': seq_final_z_kld.item()/eval_data_len, 'eval_w_kld_seq': seq_final_w_kld.item()/eval_data_len, 'eval_total_loss_seq': seq_total_loss.item()/eval_data_len} losses", "q_samples_xc) if args.seqvae_two_stage: _, _, (p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_two_stage(params_xc_in,", "= ~dirty_row_pos n_clean_rows = clean_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, clean_row_pos) q_params_xd_sliced", "seq_total_loss.item()/len(data_input), seq_final_loss.item()/len(data_input), seq_final_nll.item()/len(data_input), seq_final_z_kld.item()/len(data_input), seq_final_w_kld.item()/len(data_input))) dataset_len = float(len(train_loader.dataset)) ret =", "p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) eval_data_len = data_dirty.shape[0] losses =", "not args.AVI: get_pi_exact_vec(model, data_eval, p_params, q_params, args, logit_ret=True) # get", "vae_nll.item()/len(data_input), vae_z_kld.item()/len(data_input), vae_w_kld.item()/len(data_input))) if args.inference_type == 'seqvae': print('\\n') print('\\n\\nAdditional Info:\\tTotal", "data_eval, dataset_obj) pi_score_mat = -10 converg_norm_w = -10 else: if", "json from . import utils from .model_utils import get_pi_exact_vec, rnn_vae_forward_one_stage,", "q_samples #Getting scores and clean component if neededin_aux_samples with torch.no_grad():", "args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _, _, (p_params_xd, q_params_xd,", "pi vae_loss, vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_eval, p_params, q_params, q_samples)", "clean_comp_only=True, data_eval_clean=True) eval_data_len = data_dirty.shape[0] losses = {'eval_loss_final_clean_dc': vae_loss_dc.item()/n_dirty_rows, 'eval_nll_final_clean_dc':vae_nll_dc.item()/n_dirty_rows,", "4*[0] train_total_loss_seq_vae, train_loss_seq_vae, train_nll_seq_vae, train_z_kld_seq_vae, train_w_kld_seq_vae = 5*[0] for batch_idx,", "median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).std())) print('clean pi median: {} std:", "'eval_z_kld_final_clean_dc': vae_z_kld_dc.item()/n_dirty_rows, 'eval_w_kld_final_clean_dc':vae_w_kld_dc.item()/n_dirty_rows, 'eval_loss_final_clean_cc': vae_loss_cc.item()/n_clean_rows, 'eval_nll_final_clean_cc':vae_nll_cc.item()/n_clean_rows, 'eval_z_kld_final_clean_cc': vae_z_kld_cc.item()/n_clean_rows, 'eval_w_kld_final_clean_cc':vae_w_kld_cc.item()/n_clean_rows, 'eval_loss_final_clean_all':", "(p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_two_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args,", "= utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) # check convergence of weights (pi's)", "losses = {'eval_loss_vae': vae_loss.item()/eval_data_len, 'eval_nll_vae':vae_nll.item()/eval_data_len, 'eval_z_kld_vae': vae_z_kld.item()/eval_data_len, 'eval_w_kld_vae':vae_w_kld.item()/eval_data_len} # SEQ-VAE", "dirty data dict_slice = lambda dict_op, row_pos: {key:(value[row_pos,:] \\ if", "loss_per_iter=True, epoch_id=epoch) else: # 'vae' type inference p_params_xc, q_params_xc, q_samples_xc", "error_repair_cc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'], 1-mask) print(\"\\n\\n {} REPAIR ERROR", "q_params_metric, q_samples_metric = p_params_final, q_params_final, q_samples_final else: p_params_metric, q_params_metric, q_samples_metric", "q_samples_metric, clean_comp_only=True, data_eval_clean=data_eval_clean) losses_add = {'eval_loss_final_clean': loss_clean.item()/eval_data_len, 'eval_nll_final_clean': nll_clean.item()/eval_data_len, 'eval_z_kld_final_clean':", "return losses, metrics def repair_phase(model, data_dirty, data_clean, dataset_obj, args, mask,", "metrics def repair_phase(model, data_dirty, data_clean, dataset_obj, args, mask, mode, epoch):", "rnn_vae_forward_two_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch)", "vae_loss_dc.item()/n_dirty_rows, 'eval_nll_final_clean_dc':vae_nll_dc.item()/n_dirty_rows, 'eval_z_kld_final_clean_dc': vae_z_kld_dc.item()/n_dirty_rows, 'eval_w_kld_final_clean_dc':vae_w_kld_dc.item()/n_dirty_rows, 'eval_loss_final_clean_cc': vae_loss_cc.item()/n_clean_rows, 'eval_nll_final_clean_cc':vae_nll_cc.item()/n_clean_rows, 'eval_z_kld_final_clean_cc': vae_z_kld_cc.item()/n_clean_rows,", "{} REPAIR ERROR (CLEAN POS):{}\".format(mode, error_repair_cc)) # Get NLL (predict.", "KLD_W: {:.3f}\\n'.format( seq_total_loss.item()/len(data_input), seq_final_loss.item()/len(data_input), seq_final_nll.item()/len(data_input), seq_final_z_kld.item()/len(data_input), seq_final_w_kld.item()/len(data_input))) dataset_len = float(len(train_loader.dataset))", "logit_ret=True) # get pi, saves to q_params (with no_grad) vae_loss,", "p_params, q_params, q_samples) eval_data_len = data_eval.shape[0] losses = {'eval_loss_vae': vae_loss.item()/eval_data_len,", "p_params_xc, q_params_xc, q_samples_xc = model(data_clean) # no need to get", "print(\"\\n\\n {} REPAIR ERROR (DIRTY POS):{}\".format(mode, error_repair_dc)) # error upper", "inference p_params_xc, q_params_xc, q_samples_xc = model(data_clean) # no need to", "input: dirty data if args.inference_type == 'seqvae': p_params_xd, q_params_xd, q_samples_xd", "w's or pi's) # generative model only p(x|z, ...) nll_score_mat", "torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _, _,", "p(x|z, ...) nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) pi_score_mat = -10", "args.inference_type == 'vae': vae_loss.backward() elif args.inference_type == 'seqvae': if args.seqvae_bprop:", "== 'seqvae': if args.seqvae_bprop: # NOTE: rolls out iterations through", "print('MSE on pi pred: {}'.format(err_pi)) print('CE on pi pred: {}'.format(ce_pi))", "p_params_xd, q_params_xd, args, logit_ret=True) params_xd_in = (p_params_xd, q_params_xd, q_samples_xd) if", "data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: #", "= model.loss_function(data_clean[dirty_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) clean_row_pos = ~dirty_row_pos", "foward-pass p_params, q_params, q_samples = model(data_input, n_epoch=epoch-1) if not args.AVI:", "enumerate(train_loader): data_input = unpack[0] if args.cuda_on: data_input = data_input.cuda() optimizer.zero_grad()", "params_in = (p_params, q_params, q_samples) seq_loss_pack, _, _ = rnn_vae_forward_one_stage(params_in,", "'seqvae': #with torch.no_grad(): params_in = (p_params, q_params, q_samples) if args.seqvae_two_stage:", "q_params, args, logit_ret=True) # get pi, saves to q_params (with", "-10 else: if clean_comp_show: loss_clean, nll_clean, z_kld_clean, w_kld_clean = model.loss_function(data_eval,", "for batch_idx, unpack in enumerate(train_loader): data_input = unpack[0] if args.cuda_on:", "pi_mtx_true)**2).mean() ce_pi = F.binary_cross_entropy(pi_mtx, pi_mtx_true) print('MSE on pi pred: {}'.format(err_pi))", "(~mask_err).float() err_pi = ((pi_mtx - pi_mtx_true)**2).mean() ce_pi = F.binary_cross_entropy(pi_mtx, pi_mtx_true)", "seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack p_params_final, q_params_final, q_samples_final =", "np import json from . import utils from .model_utils import", "else: # standard 'vae' type inference p_params_xd, q_params_xd, q_samples_xd =", "'train_total_loss_seq':train_total_loss_seq_vae/dataset_len} ret = {**ret, **ret_seq} return ret def evaluation_phase(model, data_eval,", "mask_err.bool() model.eval() p_params, q_params, q_samples = model(data_eval) if not args.AVI:", "train_loss_seq_vae, train_nll_seq_vae, train_z_kld_seq_vae, train_w_kld_seq_vae = 5*[0] for batch_idx, unpack in", "logit_pi_prev = q_params_metric['w']['logit_pi'].clone().detach() else: converg_norm_w = -10 # insert here", "positions only error_up_dc, error_up_dc_per_feat = utils.error_computation(model, data_clean, data_dirty, mask, x_input_size=True)", "print('\\n\\nTrain Epoch: {} [{}/{} ({:.0f}%)]\\tVAE Loss: {:.3f}\\tVAE NLL: {:.3f}\\tVAE KLD_Z:", "= -10 converg_norm_w = -10 else: if clean_comp_show: loss_clean, nll_clean,", "p_params_xd['x'], 1-mask) print(\"\\n\\n {} REPAIR ERROR (CLEAN POS):{}\".format(mode, error_repair_cc)) #", "seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack p_params_final, q_params_final, q_samples_final = seq_param_pack", "+= vae_loss.item() train_nll_seq_vae += vae_nll.item() train_z_kld_seq_vae += vae_z_kld.item() train_w_kld_seq_vae +=", "params_xd_in = (p_params_xd, q_params_xd, q_samples_xd) if args.seqvae_two_stage: _, _, (p_params_xd,", "for key, value in dict_op.items()} dirty_row_pos = mask.any(dim=1).bool() n_dirty_rows =", "test impact on dirty cells on clean cells under model)", "# x_truth - f_vae(x_clean) # error repair, on dirty cell", "data_clean, model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else:", "model.loss_function(data_eval, p_params, q_params, q_samples) eval_data_len = data_eval.shape[0] losses = {'eval_loss_vae':", "= rnn_vae_forward_one_stage(params_in, data_eval, model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch)", "...) param (pi), used in outlier score pi_score_mat = torch.sigmoid(q_params_metric['w']['logit_pi']).clamp(1e-6,", "# error upper bound, on dirty cell positions only error_up_dc,", "# standard 'vae' type inference p_params_xd, q_params_xd, q_samples_xd = model(data_dirty)", "underlying clean data if args.inference_type == 'seqvae': p_params_xc, q_params_xc, q_samples_xc", "train_z_kld_vae, train_w_kld_vae = 4*[0] train_loss_seq, train_nll_seq, train_z_kld_seq, train_w_kld_seq = 4*[0]", "p_params_metric, q_params_metric, q_samples_metric = p_params, q_params, q_samples #Getting scores and", "model(data_clean) if not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xc, q_params_xc, args, logit_ret=True)", "import numpy as np import json from . import utils", "= {'train_loss_vae': train_loss_vae/dataset_len, 'train_nll_vae': train_nll_vae/dataset_len, 'train_z_kld_vae': train_z_kld_vae/dataset_len, 'train_w_kld_vae': train_w_kld_vae/dataset_len} if", "= model(data_clean) # no need to get pi, not used", "error on clean cell positions only (to test impact on", "= q_params_metric['w']['logit_pi'].clone().detach() else: converg_norm_w = -10 # insert here measurement", "(MSE) lower bound, on dirty cell positions only error_lb_dc, error_lb_dc_per_feat", "dict_slice(q_params_xd['w'], clean_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], clean_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, clean_row_pos)", "**losses_add} # q(w|x, ...) param (pi), used in outlier score", "= F.binary_cross_entropy(pi_mtx, pi_mtx_true) print('MSE on pi pred: {}'.format(err_pi)) print('CE on", "standard 'vae' type inference p_params_xd, q_params_xd, q_samples_xd = model(data_dirty) if", "error upper bound, on dirty cell positions only error_up_dc, error_up_dc_per_feat", "'eval_loss_final_clean_cc': vae_loss_cc.item()/n_clean_rows, 'eval_nll_final_clean_cc':vae_nll_cc.item()/n_clean_rows, 'eval_z_kld_final_clean_cc': vae_z_kld_cc.item()/n_clean_rows, 'eval_w_kld_final_clean_cc':vae_w_kld_cc.item()/n_clean_rows, 'eval_loss_final_clean_all': (vae_loss_cc+vae_loss_dc).item()/eval_data_len, 'eval_nll_final_clean_all':(vae_nll_cc+vae_nll_dc).item()/eval_data_len, 'eval_z_kld_final_clean_all':", "epoch_id=epoch) else: _, _, (p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_one_stage(params_xc_in, data_clean,", "insert here measurement of calibration of pi's using MSE or", "vae_z_kld.item()/len(data_input), vae_w_kld.item()/len(data_input))) if args.inference_type == 'seqvae': print('\\n') print('\\n\\nAdditional Info:\\tTotal Seq", "x_dirty # error on clean cell positions only (to test", "args, logit_ret=True) # get pi vae_loss, vae_nll, vae_z_kld, vae_w_kld =", "pi, not used after # error (MSE) lower bound, on", "'eval_w_kld_seq': seq_final_w_kld.item()/eval_data_len, 'eval_total_loss_seq': seq_total_loss.item()/eval_data_len} losses = {**losses, **losses_seq_vae} if args.inference_type", "data_eval, dataset_obj) # check convergence of weights (pi's) if w_conv:", "= torch.tensor(0.0) seq_final_loss = torch.tensor(0.0) seq_final_nll = torch.tensor(0.0) seq_final_z_kld =", "100. * batch_idx / len(train_loader), vae_loss.item()/len(data_input), vae_nll.item()/len(data_input), vae_z_kld.item()/len(data_input), vae_w_kld.item()/len(data_input))) if", "= utils.error_computation(model, data_clean, data_dirty, mask, x_input_size=True) # x_truth - x_dirty", "if isinstance(mask_err, torch.Tensor): pi_mtx = pi_score_mat pi_mtx_true = (~mask_err).float() err_pi", "std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).std())) print('clean pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).std()))", "(with no_grad) vae_loss, vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_input, p_params, q_params,", "+= vae_z_kld.item() train_w_kld_seq_vae += vae_w_kld.item() seq_total_loss = torch.tensor(0.0) seq_final_loss =", "isinstance(mask_err, torch.Tensor): pi_mtx = pi_score_mat pi_mtx_true = (~mask_err).float() err_pi =", "pi pred: {}'.format(err_pi)) print('CE on pi pred: {}'.format(ce_pi)) print('dirt pi", "error_lb_dc_per_feat = utils.error_computation(model, data_clean, p_params_xc['x'], mask) # x_truth - f_vae(x_clean)", "to q_params (with no_grad) vae_loss, vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_input,", "and not mute: print('\\n\\nTrain Epoch: {} [{}/{} ({:.0f}%)]\\tVAE Loss: {:.3f}\\tVAE", "q_samples_xd_sliced = dict_slice(q_samples_xd, clean_row_pos) vae_loss_cc, vae_nll_cc, vae_z_kld_cc, vae_w_kld_cc = model.loss_function(data_clean[clean_row_pos,:],", "'eval_w_kld_final_clean_all':(vae_w_kld_cc+vae_w_kld_dc).item()/eval_data_len, 'mse_lower_bd_dirtycells': error_lb_dc.item(), 'mse_upper_bd_dirtycells': error_up_dc.item() , 'mse_repair_dirtycells': error_repair_dc.item(), 'mse_repair_cleancells': error_repair_cc.item(),", "0 and not mute: print('\\n\\nTrain Epoch: {} [{}/{} ({:.0f}%)]\\tVAE Loss:", "vae_loss.backward() elif args.inference_type == 'seqvae': if args.seqvae_bprop: # NOTE: rolls", "{**ret, **ret_seq} return ret def evaluation_phase(model, data_eval, dataset_obj, args, epoch,", "w_conv: if logit_pi_prev.nelement() == 0: logit_pi_prev = torch.zeros_like(q_params_metric['w']['logit_pi']) converg_norm_w =", "'seqvae': p_params_xd, q_params_xd, q_samples_xd = model(data_dirty) if not args.AVI: get_pi_exact_vec(model,", "posterior approx) under dirty data dict_slice = lambda dict_op, row_pos:", "dict_op.items()} dirty_row_pos = mask.any(dim=1).bool() n_dirty_rows = dirty_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd,", "= dict() if args.outlier_model == 'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], dirty_row_pos)", "seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack train_total_loss_seq_vae += seq_total_loss.item() train_loss_seq_vae", "get_pi_exact_vec(model, data_dirty, p_params_xd, q_params_xd, args, logit_ret=True) # get pi #", "vae_z_kld.item() train_w_kld_vae += vae_w_kld.item() if args.inference_type == 'vae': vae_loss.backward() elif", "= utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) pi_score_mat = -10 converg_norm_w = -10", "f_vae(x_dirty) print(\"\\n\\n {} REPAIR ERROR (DIRTY POS):{}\".format(mode, error_repair_dc)) # error", "# insert here measurement of calibration of pi's using MSE", "utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) # check convergence of weights (pi's) if", "'seqvae': if args.seqvae_bprop: # NOTE: rolls out iterations through time", "{}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).std())) print('clean pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).std())) metrics", "args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) else: seq_loss_pack, _, seq_param_pack", "utils.error_computation(model, data_clean, p_params_xc['x'], mask) # x_truth - f_vae(x_clean) # error", "epoch, batch_idx * len(data_input), len(train_loader.dataset), 100. * batch_idx / len(train_loader),", "only (no w's or pi's) # generative model only p(x|z,", "'eval_w_kld_final_clean': w_kld_clean.item()/eval_data_len } losses = {**losses, **losses_add} # q(w|x, ...)", "= dict() if args.outlier_model == 'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], clean_row_pos)", "mask_err=mask_err, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack p_params_final,", "# x_truth - x_dirty # error on clean cell positions", "import optim import torch.nn.functional as F import argparse from sklearn.metrics", "if args.cuda_on: # model.cpu() if type(mask_err) != type(None): mask_err =", "p_params, q_params, args, logit_ret=True) # get pi vae_loss, vae_nll, vae_z_kld,", "**losses_seq_vae} if args.inference_type == 'seqvae': p_params_metric, q_params_metric, q_samples_metric = p_params_final,", "q_samples_final else: p_params_metric, q_params_metric, q_samples_metric = p_params, q_params, q_samples #Getting", "print('dirt pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).std())) print('clean pi median:", "MSE or cross-entropy if isinstance(mask_err, torch.Tensor): pi_mtx = pi_score_mat pi_mtx_true", "losses = {**losses, **losses_seq_vae} if args.inference_type == 'seqvae': p_params_metric, q_params_metric,", "vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_input, p_params, q_params, q_samples) train_loss_vae +=", "mask, mode, epoch): model.eval() # model params with input: dirty", "q_params_xd, q_samples_xd) = rnn_vae_forward_two_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps,", "number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _, _, (p_params_xc, q_params_xc, q_samples_xc) =", "print(\"\\n\\n {} REPAIR ERROR (CLEAN POS):{}\".format(mode, error_repair_cc)) # Get NLL", "error_repair_cc)) # Get NLL (predict. posterior approx) under dirty data", "def training_phase(model, optimizer, train_loader, args, epoch, mute=True): model.train() train_loss_vae, train_nll_vae,", "= p_params, q_params, q_samples #Getting scores and clean component if", "= model(data_dirty) if not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xd, q_params_xd, args,", "error_up_dc.item() , 'mse_repair_dirtycells': error_repair_dc.item(), 'mse_repair_cleancells': error_repair_cc.item(), 'errors_per_feature': [error_lb_dc_per_feat, error_repair_dc_per_feat, error_up_dc_per_feat,", "data_input = unpack[0] if args.cuda_on: data_input = data_input.cuda() optimizer.zero_grad() ##", "== 0 and not mute: print('\\n\\nTrain Epoch: {} [{}/{} ({:.0f}%)]\\tVAE", "model(data_eval) if not args.AVI: get_pi_exact_vec(model, data_eval, p_params, q_params, args, logit_ret=True)", "= (q_params_metric['w']['logit_pi'] - logit_pi_prev).norm().item() logit_pi_prev = q_params_metric['w']['logit_pi'].clone().detach() else: converg_norm_w =", "with input: underlying clean data if args.inference_type == 'seqvae': p_params_xc,", "cross-entropy if isinstance(mask_err, torch.Tensor): pi_mtx = pi_score_mat pi_mtx_true = (~mask_err).float()", "(CLEAN POS):{}\".format(mode, error_repair_cc)) # Get NLL (predict. posterior approx) under", "float(len(train_loader.dataset)) ret = {'train_loss_vae': train_loss_vae/dataset_len, 'train_nll_vae': train_nll_vae/dataset_len, 'train_z_kld_vae': train_z_kld_vae/dataset_len, 'train_w_kld_vae':", "= unpack[0] if args.cuda_on: data_input = data_input.cuda() optimizer.zero_grad() ## first", "p_params, q_params, q_samples) train_loss_vae += vae_loss.item() train_nll_vae += vae_nll.item() train_z_kld_vae", "epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack train_total_loss_seq_vae +=", "seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack p_params_final, q_params_final, q_samples_final", "args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _, _, (p_params_xc, q_params_xc,", "'eval_loss_final_clean_all': (vae_loss_cc+vae_loss_dc).item()/eval_data_len, 'eval_nll_final_clean_all':(vae_nll_cc+vae_nll_dc).item()/eval_data_len, 'eval_z_kld_final_clean_all': (vae_z_kld_cc+vae_z_kld_dc).item()/eval_data_len, 'eval_w_kld_final_clean_all':(vae_w_kld_cc+vae_w_kld_dc).item()/eval_data_len, 'mse_lower_bd_dirtycells': error_lb_dc.item(), 'mse_upper_bd_dirtycells': error_up_dc.item()", "clean_row_pos = ~dirty_row_pos n_clean_rows = clean_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, clean_row_pos)", "+= vae_nll.item() train_z_kld_seq_vae += vae_z_kld.item() train_w_kld_seq_vae += vae_w_kld.item() seq_total_loss =", "{}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).std())) metrics = {'nll_score': nll_score_mat, 'pi_score': pi_score_mat, 'converg_norm_w': converg_norm_w}", "dirty cell positions only error_up_dc, error_up_dc_per_feat = utils.error_computation(model, data_clean, data_dirty,", "torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).std())) print('clean pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).std())) metrics =", "REPAIR ERROR (CLEAN POS):{}\".format(mode, error_repair_cc)) # Get NLL (predict. posterior", "seq_total_loss.item() train_loss_seq_vae += seq_final_loss.item() train_nll_seq_vae += seq_final_nll.item() train_z_kld_seq_vae += seq_final_z_kld.item()", "vae_w_kld = model.loss_function(data_input, p_params, q_params, q_samples) train_loss_vae += vae_loss.item() train_nll_vae", "nll_clean.item()/eval_data_len, 'eval_z_kld_final_clean': z_kld_clean.item()/eval_data_len, 'eval_w_kld_final_clean': w_kld_clean.item()/eval_data_len } losses = {**losses, **losses_add}", "vae_w_kld_dc = model.loss_function(data_clean[dirty_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) clean_row_pos =", "vae_loss.item() train_nll_seq_vae += vae_nll.item() train_z_kld_seq_vae += vae_z_kld.item() train_w_kld_seq_vae += vae_w_kld.item()", "dirty_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, dirty_row_pos) vae_loss_dc, vae_nll_dc, vae_z_kld_dc, vae_w_kld_dc =", "vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld", "check convergence of weights (pi's) if w_conv: if logit_pi_prev.nelement() ==", "model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: # standard", "vae_w_kld.item() if args.inference_type == 'vae': vae_loss.backward() elif args.inference_type == 'seqvae':", "q_params_xd, q_samples_xd) if args.seqvae_two_stage: _, _, (p_params_xd, q_params_xd, q_samples_xd) =", "logit_ret=True) # get pi # model params with input: underlying", "train_nll_vae, train_z_kld_vae, train_w_kld_vae = 4*[0] train_loss_seq, train_nll_seq, train_z_kld_seq, train_w_kld_seq =", "= mask_err.bool() model.eval() p_params, q_params, q_samples = model(data_eval) if not", "== 'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], dirty_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], dirty_row_pos)", "q_params_xd, q_samples_xd) = rnn_vae_forward_one_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps,", "time and bprops params_in = (p_params, q_params, q_samples) seq_loss_pack, _,", "model.loss_function(data_eval, p_params_metric, q_params_metric, q_samples_metric, clean_comp_only=True, data_eval_clean=data_eval_clean) losses_add = {'eval_loss_final_clean': loss_clean.item()/eval_data_len,", "train_loss_seq_vae += vae_loss.item() train_nll_seq_vae += vae_nll.item() train_z_kld_seq_vae += vae_z_kld.item() train_w_kld_seq_vae", "if args.inference_type == 'seqvae': p_params_xc, q_params_xc, q_samples_xc = model(data_clean) if", "q_params_xd, args, logit_ret=True) params_xd_in = (p_params_xd, q_params_xd, q_samples_xd) if args.seqvae_two_stage:", "'train_z_kld_seq': train_z_kld_seq_vae/dataset_len,'train_w_kld_seq': train_w_kld_seq_vae/dataset_len, 'train_total_loss_seq':train_total_loss_seq_vae/dataset_len} ret = {**ret, **ret_seq} return ret", "error_up_dc, error_up_dc_per_feat = utils.error_computation(model, data_clean, data_dirty, mask, x_input_size=True) # x_truth", "cells on clean cells under model) error_repair_cc, error_repair_cc_per_feat = utils.error_computation(model,", "dict() if args.outlier_model == 'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], dirty_row_pos) q_params_xd_sliced['z']", "'seqvae': print('\\n') print('\\n\\nAdditional Info:\\tTotal Seq Loss: {:.3f}\\tFinal Seq Loss: {:.3f}\\tFinal", "seq_loss_pack p_params_final, q_params_final, q_samples_final = seq_param_pack losses_seq_vae = {'eval_loss_seq': seq_final_loss.item()/eval_data_len,", "of calibration of pi's using MSE or cross-entropy if isinstance(mask_err,", "NLL: {:.3f}\\tFinal Sep KLD_Z: {:.3f}\\tFinal Sep KLD_W: {:.3f}\\n'.format( seq_total_loss.item()/len(data_input), seq_final_loss.item()/len(data_input),", "seq_final_w_kld.item()/len(data_input))) dataset_len = float(len(train_loader.dataset)) ret = {'train_loss_vae': train_loss_vae/dataset_len, 'train_nll_vae': train_nll_vae/dataset_len,", "mask, x_input_size=True) # x_truth - x_dirty # error on clean", "and clean component if neededin_aux_samples with torch.no_grad(): if args.outlier_model ==", "q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) eval_data_len = data_dirty.shape[0] losses = {'eval_loss_final_clean_dc': vae_loss_dc.item()/n_dirty_rows,", "params with input: dirty data if args.inference_type == 'seqvae': p_params_xd,", "upper bound, on dirty cell positions only error_up_dc, error_up_dc_per_feat =", "on pi pred: {}'.format(ce_pi)) print('dirt pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).median(),", "data_eval_clean=True) clean_row_pos = ~dirty_row_pos n_clean_rows = clean_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd,", "args.log_interval == 0 and not mute: print('\\n\\nTrain Epoch: {} [{}/{}", "vae_z_kld_dc.item()/n_dirty_rows, 'eval_w_kld_final_clean_dc':vae_w_kld_dc.item()/n_dirty_rows, 'eval_loss_final_clean_cc': vae_loss_cc.item()/n_clean_rows, 'eval_nll_final_clean_cc':vae_nll_cc.item()/n_clean_rows, 'eval_z_kld_final_clean_cc': vae_z_kld_cc.item()/n_clean_rows, 'eval_w_kld_final_clean_cc':vae_w_kld_cc.item()/n_clean_rows, 'eval_loss_final_clean_all': (vae_loss_cc+vae_loss_dc).item()/eval_data_len,", "as outlier score nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) # check", "({:.0f}%)]\\tVAE Loss: {:.3f}\\tVAE NLL: {:.3f}\\tVAE KLD_Z: {:.3f}\\tVAE KLD_W: {:.3f}'.format( epoch,", "Seq Loss: {:.3f}\\tFinal Sep NLL: {:.3f}\\tFinal Sep KLD_Z: {:.3f}\\tFinal Sep", "== 'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], clean_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], clean_row_pos)", "if args.inference_type == 'seqvae': p_params_xd, q_params_xd, q_samples_xd = model(data_dirty) if", "q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], dirty_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], dirty_row_pos) q_samples_xd_sliced =", "vae_loss.item() train_nll_vae += vae_nll.item() train_z_kld_vae += vae_z_kld.item() train_w_kld_vae += vae_w_kld.item()", "{:.3f}\\tVAE KLD_W: {:.3f}'.format( epoch, batch_idx * len(data_input), len(train_loader.dataset), 100. *", "q_params_xc, q_samples_xc = model(data_clean) # no need to get pi,", "torch.Tensor): pi_mtx = pi_score_mat pi_mtx_true = (~mask_err).float() err_pi = ((pi_mtx", "## first foward-pass p_params, q_params, q_samples = model(data_input, n_epoch=epoch-1) if", "args, number_steps=args.seqvae_steps, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld", "args, logit_ret=True) # get pi # model params with input:", "(to test impact on dirty cells on clean cells under", "p_params, q_params, args, logit_ret=True) # get pi, saves to q_params", "inference p_params_xd, q_params_xd, q_samples_xd = model(data_dirty) if not args.AVI: get_pi_exact_vec(model,", "params_in = (p_params, q_params, q_samples) if args.seqvae_two_stage: seq_loss_pack, _, seq_param_pack", "rnn_vae_forward_two_stage(params_in, data_eval, model, vae_loss, args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch)", "mask_err = mask_err.bool() model.eval() p_params, q_params, q_samples = model(data_eval) if", "data_input, p_params, q_params, args, logit_ret=True) # get pi, saves to", "import json from . import utils from .model_utils import get_pi_exact_vec,", "seq_final_loss = torch.tensor(0.0) seq_final_nll = torch.tensor(0.0) seq_final_z_kld = torch.tensor(0.0) seq_final_w_kld", "= data_input.cuda() optimizer.zero_grad() ## first foward-pass p_params, q_params, q_samples =", "* batch_idx / len(train_loader), vae_loss.item()/len(data_input), vae_nll.item()/len(data_input), vae_z_kld.item()/len(data_input), vae_w_kld.item()/len(data_input))) if args.inference_type", "seq_final_z_kld.item()/eval_data_len, 'eval_w_kld_seq': seq_final_w_kld.item()/eval_data_len, 'eval_total_loss_seq': seq_total_loss.item()/eval_data_len} losses = {**losses, **losses_seq_vae} if", "q_params_metric['w']['logit_pi'].clone().detach() else: converg_norm_w = -10 # insert here measurement of", "= utils.error_computation(model, data_clean, p_params_xc['x'], mask) # x_truth - f_vae(x_clean) #", "seq_final_z_kld.item()/len(data_input), seq_final_w_kld.item()/len(data_input))) dataset_len = float(len(train_loader.dataset)) ret = {'train_loss_vae': train_loss_vae/dataset_len, 'train_nll_vae':", "type inference p_params_xd, q_params_xd, q_samples_xd = model(data_dirty) if not args.AVI:", "print('\\n') print('\\n\\nAdditional Info:\\tTotal Seq Loss: {:.3f}\\tFinal Seq Loss: {:.3f}\\tFinal Sep", "(vae_z_kld_cc+vae_z_kld_dc).item()/eval_data_len, 'eval_w_kld_final_clean_all':(vae_w_kld_cc+vae_w_kld_dc).item()/eval_data_len, 'mse_lower_bd_dirtycells': error_lb_dc.item(), 'mse_upper_bd_dirtycells': error_up_dc.item() , 'mse_repair_dirtycells': error_repair_dc.item(), 'mse_repair_cleancells':", "p_params_xd, q_params_xd, args, logit_ret=True) # get pi # model params", "weights (pi's) if w_conv: if logit_pi_prev.nelement() == 0: logit_pi_prev =", "model.train() train_loss_vae, train_nll_vae, train_z_kld_vae, train_w_kld_vae = 4*[0] train_loss_seq, train_nll_seq, train_z_kld_seq,", "= ((pi_mtx - pi_mtx_true)**2).mean() ce_pi = F.binary_cross_entropy(pi_mtx, pi_mtx_true) print('MSE on", "if args.inference_type == 'seqvae': p_params_metric, q_params_metric, q_samples_metric = p_params_final, q_params_final,", "{} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).std())) metrics = {'nll_score': nll_score_mat, 'pi_score': pi_score_mat,", "q_samples_xc) = rnn_vae_forward_one_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, loss_per_iter=True,", "sklearn.metrics import mean_squared_error import numpy as np import json from", "# 'vae' type inference p_params_xc, q_params_xc, q_samples_xc = model(data_clean) #", "p_params_xc, q_params_xc, args, logit_ret=True) params_xc_in = (p_params_xc, q_params_xc, q_samples_xc) if", "torch.no_grad(): params_in = (p_params, q_params, q_samples) if args.seqvae_two_stage: seq_loss_pack, _,", "q_params_xc, args, logit_ret=True) params_xc_in = (p_params_xc, q_params_xc, q_samples_xc) if args.seqvae_two_stage:", "F.binary_cross_entropy(pi_mtx, pi_mtx_true) print('MSE on pi pred: {}'.format(err_pi)) print('CE on pi", "= float(len(train_loader.dataset)) ret = {'train_loss_vae': train_loss_vae/dataset_len, 'train_nll_vae': train_nll_vae/dataset_len, 'train_z_kld_vae': train_z_kld_vae/dataset_len,", "metrics = {'nll_score': nll_score_mat, 'pi_score': pi_score_mat, 'converg_norm_w': converg_norm_w} return losses,", "p_params_xd_sliced = dict_slice(p_params_xd, dirty_row_pos) q_params_xd_sliced = dict() if args.outlier_model ==", "def evaluation_phase(model, data_eval, dataset_obj, args, epoch, clean_comp_show=False, data_eval_clean=False, logit_pi_prev=torch.tensor([]), w_conv=False,", "seq_param_pack = rnn_vae_forward_one_stage(params_in, data_eval, model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, mask_err=mask_err,", "else: if clean_comp_show: loss_clean, nll_clean, z_kld_clean, w_kld_clean = model.loss_function(data_eval, p_params_metric,", "dataset_obj) pi_score_mat = -10 converg_norm_w = -10 else: if clean_comp_show:", "pi pred: {}'.format(ce_pi)) print('dirt pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).std()))", "p_params_metric, q_params_metric, q_samples_metric, clean_comp_only=True, data_eval_clean=data_eval_clean) losses_add = {'eval_loss_final_clean': loss_clean.item()/eval_data_len, 'eval_nll_final_clean':", "vae_z_kld, vae_w_kld = model.loss_function(data_input, p_params, q_params, q_samples) train_loss_vae += vae_loss.item()", "out iterations through time and bprops params_in = (p_params, q_params,", "pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).std())) metrics = {'nll_score': nll_score_mat,", "epoch_id=epoch) else: _, _, (p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_one_stage(params_xd_in, data_dirty,", "seq_loss_pack, _, seq_param_pack = rnn_vae_forward_one_stage(params_in, data_eval, model, vae_loss, args, number_steps=args.seqvae_steps,", "train_z_kld_seq_vae += seq_final_z_kld.item() train_w_kld_seq_vae += seq_final_w_kld.item() else: vae_loss.backward() train_total_loss_seq_vae +=", "model.loss_function(data_input, p_params, q_params, q_samples) train_loss_vae += vae_loss.item() train_nll_vae += vae_nll.item()", "+= seq_final_nll.item() train_z_kld_seq_vae += seq_final_z_kld.item() train_w_kld_seq_vae += seq_final_w_kld.item() else: vae_loss.backward()", "q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], clean_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, clean_row_pos) vae_loss_cc, vae_nll_cc,", "# q(w|x, ...) param (pi), used in outlier score pi_score_mat", "train_w_kld_seq = 4*[0] train_total_loss_seq_vae, train_loss_seq_vae, train_nll_seq_vae, train_z_kld_seq_vae, train_w_kld_seq_vae = 5*[0]", "+= vae_loss.item() train_loss_seq_vae += vae_loss.item() train_nll_seq_vae += vae_nll.item() train_z_kld_seq_vae +=", "= {'nll_score': nll_score_mat, 'pi_score': pi_score_mat, 'converg_norm_w': converg_norm_w} return losses, metrics", "q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) clean_row_pos = ~dirty_row_pos n_clean_rows = clean_row_pos.sum().item()", "= clean_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, clean_row_pos) q_params_xd_sliced = dict() if", "args.inference_type == 'seqvae': p_params_xd, q_params_xd, q_samples_xd = model(data_dirty) if not", "utils from .model_utils import get_pi_exact_vec, rnn_vae_forward_one_stage, rnn_vae_forward_two_stage def training_phase(model, optimizer,", "'eval_nll_seq': seq_final_nll.item()/eval_data_len, 'eval_z_kld_seq': seq_final_z_kld.item()/eval_data_len, 'eval_w_kld_seq': seq_final_w_kld.item()/eval_data_len, 'eval_total_loss_seq': seq_total_loss.item()/eval_data_len} losses =", "= -10 else: if clean_comp_show: loss_clean, nll_clean, z_kld_clean, w_kld_clean =", "pi's using MSE or cross-entropy if isinstance(mask_err, torch.Tensor): pi_mtx =", "data_clean, dataset_obj, args, mask, mode, epoch): model.eval() # model params", "(no w's or pi's) # generative model only p(x|z, ...)", "import torch from torch import optim import torch.nn.functional as F", "on dirty cell positions only error_up_dc, error_up_dc_per_feat = utils.error_computation(model, data_clean,", "in dict_op.items()} dirty_row_pos = mask.any(dim=1).bool() n_dirty_rows = dirty_row_pos.sum().item() p_params_xd_sliced =", "vae_w_kld.item() seq_total_loss = torch.tensor(0.0) seq_final_loss = torch.tensor(0.0) seq_final_nll = torch.tensor(0.0)", "train_loader, args, epoch, mute=True): model.train() train_loss_vae, train_nll_vae, train_z_kld_vae, train_w_kld_vae =", "pi_mtx = pi_score_mat pi_mtx_true = (~mask_err).float() err_pi = ((pi_mtx -", "ret = {**ret, **ret_seq} return ret def evaluation_phase(model, data_eval, dataset_obj,", "args.seqvae_two_stage: seq_loss_pack, _, seq_param_pack = rnn_vae_forward_two_stage(params_in, data_eval, model, vae_loss, args,", "seq_final_nll.item() train_z_kld_seq_vae += seq_final_z_kld.item() train_w_kld_seq_vae += seq_final_w_kld.item() else: vae_loss.backward() train_total_loss_seq_vae", "outlier score nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) # check convergence", "\"VAE\": # VAE models only (no w's or pi's) #", "= torch.sigmoid(q_params_metric['w']['logit_pi']).clamp(1e-6, 1-1e-6) # -log p(x|z, ...) used as outlier", "data_clean, p_params_xc['x'], mask) # x_truth - f_vae(x_clean) # error repair,", "if args.outlier_model == 'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], clean_row_pos) q_params_xd_sliced['z'] =", "as np import json from . import utils from .model_utils", "vae_nll.item() train_z_kld_vae += vae_z_kld.item() train_w_kld_vae += vae_w_kld.item() if args.inference_type ==", "loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) else: seq_loss_pack, _, seq_param_pack = rnn_vae_forward_one_stage(params_in, data_eval,", "q_samples_xd = model(data_dirty) if not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xd, q_params_xd,", "SEQ-VAE if args.inference_type == 'seqvae': #with torch.no_grad(): params_in = (p_params,", "get pi, saves to q_params (with no_grad) vae_loss, vae_nll, vae_z_kld,", "measurement of calibration of pi's using MSE or cross-entropy if", "print('\\n\\nAdditional Info:\\tTotal Seq Loss: {:.3f}\\tFinal Seq Loss: {:.3f}\\tFinal Sep NLL:", "q_samples_xc) = rnn_vae_forward_two_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage,", "if args.outlier_model == 'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], dirty_row_pos) q_params_xd_sliced['z'] =", "seq_final_w_kld.item() else: vae_loss.backward() train_total_loss_seq_vae += vae_loss.item() train_loss_seq_vae += vae_loss.item() train_nll_seq_vae", "_, _, (p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_one_stage(params_xc_in, data_clean, model, torch.tensor(0.0,", "{'eval_loss_vae': vae_loss.item()/eval_data_len, 'eval_nll_vae':vae_nll.item()/eval_data_len, 'eval_z_kld_vae': vae_z_kld.item()/eval_data_len, 'eval_w_kld_vae':vae_w_kld.item()/eval_data_len} # SEQ-VAE if args.inference_type", "torch.tensor(0.0) optimizer.step() if batch_idx % args.log_interval == 0 and not", "_, seq_param_pack = rnn_vae_forward_one_stage(params_in, data_eval, model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True,", "= rnn_vae_forward_one_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch)", "q_samples_final = seq_param_pack losses_seq_vae = {'eval_loss_seq': seq_final_loss.item()/eval_data_len, 'eval_nll_seq': seq_final_nll.item()/eval_data_len, 'eval_z_kld_seq':", "train_z_kld_vae/dataset_len, 'train_w_kld_vae': train_w_kld_vae/dataset_len} if args.inference_type == \"seqvae\": ret_seq = {'train_loss_seq':", "Loss: {:.3f}\\tVAE NLL: {:.3f}\\tVAE KLD_Z: {:.3f}\\tVAE KLD_W: {:.3f}'.format( epoch, batch_idx", "KLD_W: {:.3f}'.format( epoch, batch_idx * len(data_input), len(train_loader.dataset), 100. * batch_idx", "+= seq_total_loss.item() train_loss_seq_vae += seq_final_loss.item() train_nll_seq_vae += seq_final_nll.item() train_z_kld_seq_vae +=", "dirty cell positions only error_repair_dc, error_repair_dc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'],", "= model(data_eval) if not args.AVI: get_pi_exact_vec(model, data_eval, p_params, q_params, args,", "== 'seqvae': #with torch.no_grad(): params_in = (p_params, q_params, q_samples) if", "'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], dirty_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], dirty_row_pos) q_samples_xd_sliced", "torch.tensor(0.0) seq_final_loss = torch.tensor(0.0) seq_final_nll = torch.tensor(0.0) seq_final_z_kld = torch.tensor(0.0)", "param (pi), used in outlier score pi_score_mat = torch.sigmoid(q_params_metric['w']['logit_pi']).clamp(1e-6, 1-1e-6)", "= model.loss_function(data_eval, p_params_metric, q_params_metric, q_samples_metric, clean_comp_only=True, data_eval_clean=data_eval_clean) losses_add = {'eval_loss_final_clean':", "clean_comp_show: loss_clean, nll_clean, z_kld_clean, w_kld_clean = model.loss_function(data_eval, p_params_metric, q_params_metric, q_samples_metric,", "KLD_Z: {:.3f}\\tVAE KLD_W: {:.3f}'.format( epoch, batch_idx * len(data_input), len(train_loader.dataset), 100.", "def repair_phase(model, data_dirty, data_clean, dataset_obj, args, mask, mode, epoch): model.eval()", "= utils.error_computation(model, data_clean, p_params_xd['x'], 1-mask) print(\"\\n\\n {} REPAIR ERROR (CLEAN", "'pi_score': pi_score_mat, 'converg_norm_w': converg_norm_w} return losses, metrics def repair_phase(model, data_dirty,", "x_truth - f_vae(x_clean) # error repair, on dirty cell positions", "'eval_z_kld_seq': seq_final_z_kld.item()/eval_data_len, 'eval_w_kld_seq': seq_final_w_kld.item()/eval_data_len, 'eval_total_loss_seq': seq_total_loss.item()/eval_data_len} losses = {**losses, **losses_seq_vae}", "used in outlier score pi_score_mat = torch.sigmoid(q_params_metric['w']['logit_pi']).clamp(1e-6, 1-1e-6) # -log", "= model(data_clean) if not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xc, q_params_xc, args,", "= rnn_vae_forward_one_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch)", "train_w_kld_seq_vae/dataset_len, 'train_total_loss_seq':train_total_loss_seq_vae/dataset_len} ret = {**ret, **ret_seq} return ret def evaluation_phase(model,", "seq_final_z_kld.item() train_w_kld_seq_vae += seq_final_w_kld.item() else: vae_loss.backward() train_total_loss_seq_vae += vae_loss.item() train_loss_seq_vae", "dict_slice(q_params_xd['z'], clean_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, clean_row_pos) vae_loss_cc, vae_nll_cc, vae_z_kld_cc, vae_w_kld_cc", "== 'vae': vae_loss.backward() elif args.inference_type == 'seqvae': if args.seqvae_bprop: #", "mask) # x_truth - f_vae(x_dirty) print(\"\\n\\n {} REPAIR ERROR (DIRTY", "cell positions only error_repair_dc, error_repair_dc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'], mask)", "} losses = {**losses, **losses_add} # q(w|x, ...) param (pi),", "vae_z_kld, vae_w_kld = model.loss_function(data_eval, p_params, q_params, q_samples) eval_data_len = data_eval.shape[0]", "# if args.cuda_on: # model.cpu() if type(mask_err) != type(None): mask_err", "vae_loss, args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) else: seq_loss_pack, _,", "p_params_xc, q_params_xc, q_samples_xc = model(data_clean) if not args.AVI: get_pi_exact_vec(model, data_dirty,", "q_params_xc, q_samples_xc) = rnn_vae_forward_two_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps,", "only (to test impact on dirty cells on clean cells", "ERROR (CLEAN POS):{}\".format(mode, error_repair_cc)) # Get NLL (predict. posterior approx)", "seq_final_nll.item()/eval_data_len, 'eval_z_kld_seq': seq_final_z_kld.item()/eval_data_len, 'eval_w_kld_seq': seq_final_w_kld.item()/eval_data_len, 'eval_total_loss_seq': seq_total_loss.item()/eval_data_len} losses = {**losses,", "% args.log_interval == 0 and not mute: print('\\n\\nTrain Epoch: {}", "- pi_mtx_true)**2).mean() ce_pi = F.binary_cross_entropy(pi_mtx, pi_mtx_true) print('MSE on pi pred:", "train_loss_seq_vae/dataset_len, 'train_nll_seq': train_nll_seq_vae/dataset_len, 'train_z_kld_seq': train_z_kld_seq_vae/dataset_len,'train_w_kld_seq': train_w_kld_seq_vae/dataset_len, 'train_total_loss_seq':train_total_loss_seq_vae/dataset_len} ret = {**ret,", "Get NLL (predict. posterior approx) under dirty data dict_slice =", "vae_loss_dc, vae_nll_dc, vae_z_kld_dc, vae_w_kld_dc = model.loss_function(data_clean[dirty_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True,", "q_params, q_samples #Getting scores and clean component if neededin_aux_samples with", "args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: # 'vae' type inference p_params_xc,", "data_clean, p_params_xd['x'], 1-mask) print(\"\\n\\n {} REPAIR ERROR (CLEAN POS):{}\".format(mode, error_repair_cc))", "dict_op, row_pos: {key:(value[row_pos,:] \\ if value.shape[0]==data_dirty.shape[0] else value) for key,", "if neededin_aux_samples with torch.no_grad(): if args.outlier_model == \"VAE\": # VAE", "train_z_kld_vae += vae_z_kld.item() train_w_kld_vae += vae_w_kld.item() if args.inference_type == 'vae':", "p_params, q_params, q_samples = model(data_input, n_epoch=epoch-1) if not args.AVI: get_pi_exact_vec(model,", "= (p_params_xd, q_params_xd, q_samples_xd) if args.seqvae_two_stage: _, _, (p_params_xd, q_params_xd,", "args.AVI: get_pi_exact_vec(model, data_eval, p_params, q_params, args, logit_ret=True) # get pi", "scores and clean component if neededin_aux_samples with torch.no_grad(): if args.outlier_model", "cell positions only (to test impact on dirty cells on", "if args.seqvae_two_stage: _, _, (p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_two_stage(params_xc_in, data_clean,", "not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xd, q_params_xd, args, logit_ret=True) params_xd_in =", "logit_ret=True) params_xd_in = (p_params_xd, q_params_xd, q_samples_xd) if args.seqvae_two_stage: _, _,", "seq_final_z_kld, seq_final_w_kld = seq_loss_pack train_total_loss_seq_vae += seq_total_loss.item() train_loss_seq_vae += seq_final_loss.item()", "seq_final_w_kld = torch.tensor(0.0) optimizer.step() if batch_idx % args.log_interval == 0", "pi_score_mat = torch.sigmoid(q_params_metric['w']['logit_pi']).clamp(1e-6, 1-1e-6) # -log p(x|z, ...) used as", "need to get pi, not used after # error (MSE)", "q_params_xd, q_samples_xd = model(data_dirty) if not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xd,", "number_steps_second_stage=args.steps_2stage, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) else: seq_loss_pack, _, seq_param_pack = rnn_vae_forward_one_stage(params_in,", "args.cuda_on: data_input = data_input.cuda() optimizer.zero_grad() ## first foward-pass p_params, q_params,", "q_params_metric, q_samples_metric = p_params, q_params, q_samples #Getting scores and clean", "{'train_loss_vae': train_loss_vae/dataset_len, 'train_nll_vae': train_nll_vae/dataset_len, 'train_z_kld_vae': train_z_kld_vae/dataset_len, 'train_w_kld_vae': train_w_kld_vae/dataset_len} if args.inference_type", "ret_seq = {'train_loss_seq': train_loss_seq_vae/dataset_len, 'train_nll_seq': train_nll_seq_vae/dataset_len, 'train_z_kld_seq': train_z_kld_seq_vae/dataset_len,'train_w_kld_seq': train_w_kld_seq_vae/dataset_len, 'train_total_loss_seq':train_total_loss_seq_vae/dataset_len}", "torch import optim import torch.nn.functional as F import argparse from", "else: _, _, (p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_one_stage(params_xc_in, data_clean, model,", "== 'seqvae': p_params_metric, q_params_metric, q_samples_metric = p_params_final, q_params_final, q_samples_final else:", "converg_norm_w = -10 # insert here measurement of calibration of", "train_nll_seq_vae, train_z_kld_seq_vae, train_w_kld_seq_vae = 5*[0] for batch_idx, unpack in enumerate(train_loader):", "q_params_xc, q_samples_xc = model(data_clean) if not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xc,", "args.seqvae_bprop: # NOTE: rolls out iterations through time and bprops", ", 'mse_repair_dirtycells': error_repair_dc.item(), 'mse_repair_cleancells': error_repair_cc.item(), 'errors_per_feature': [error_lb_dc_per_feat, error_repair_dc_per_feat, error_up_dc_per_feat, error_repair_cc_per_feat]}", "train_loss_seq_vae += seq_final_loss.item() train_nll_seq_vae += seq_final_nll.item() train_z_kld_seq_vae += seq_final_z_kld.item() train_w_kld_seq_vae", "model.eval() # model params with input: dirty data if args.inference_type", "bound, on dirty cell positions only error_up_dc, error_up_dc_per_feat = utils.error_computation(model,", "args.outlier_model == 'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], dirty_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'],", "if type(mask_err) != type(None): mask_err = mask_err.bool() model.eval() p_params, q_params,", "positions only error_repair_dc, error_repair_dc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'], mask) #", "KLD_Z: {:.3f}\\tFinal Sep KLD_W: {:.3f}\\n'.format( seq_total_loss.item()/len(data_input), seq_final_loss.item()/len(data_input), seq_final_nll.item()/len(data_input), seq_final_z_kld.item()/len(data_input), seq_final_w_kld.item()/len(data_input)))", "q_params, q_samples) train_loss_vae += vae_loss.item() train_nll_vae += vae_nll.item() train_z_kld_vae +=", "0: logit_pi_prev = torch.zeros_like(q_params_metric['w']['logit_pi']) converg_norm_w = (q_params_metric['w']['logit_pi'] - logit_pi_prev).norm().item() logit_pi_prev", "# model params with input: underlying clean data if args.inference_type", "torch.nn.functional as F import argparse from sklearn.metrics import mean_squared_error import", "neededin_aux_samples with torch.no_grad(): if args.outlier_model == \"VAE\": # VAE models", "vae_loss_cc.item()/n_clean_rows, 'eval_nll_final_clean_cc':vae_nll_cc.item()/n_clean_rows, 'eval_z_kld_final_clean_cc': vae_z_kld_cc.item()/n_clean_rows, 'eval_w_kld_final_clean_cc':vae_w_kld_cc.item()/n_clean_rows, 'eval_loss_final_clean_all': (vae_loss_cc+vae_loss_dc).item()/eval_data_len, 'eval_nll_final_clean_all':(vae_nll_cc+vae_nll_dc).item()/eval_data_len, 'eval_z_kld_final_clean_all': (vae_z_kld_cc+vae_z_kld_dc).item()/eval_data_len,", "q_samples_xc = model(data_clean) if not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xc, q_params_xc,", "- f_vae(x_dirty) print(\"\\n\\n {} REPAIR ERROR (DIRTY POS):{}\".format(mode, error_repair_dc)) #", "{} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).std())) print('clean pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).median(),", "= {'eval_loss_vae': vae_loss.item()/eval_data_len, 'eval_nll_vae':vae_nll.item()/eval_data_len, 'eval_z_kld_vae': vae_z_kld.item()/eval_data_len, 'eval_w_kld_vae':vae_w_kld.item()/eval_data_len} # SEQ-VAE if", "args, logit_ret=True) params_xd_in = (p_params_xd, q_params_xd, q_samples_xd) if args.seqvae_two_stage: _,", "from . import utils from .model_utils import get_pi_exact_vec, rnn_vae_forward_one_stage, rnn_vae_forward_two_stage", "= dict_slice(p_params_xd, clean_row_pos) q_params_xd_sliced = dict() if args.outlier_model == 'RVAE':", "pi's) # generative model only p(x|z, ...) nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric,", "= rnn_vae_forward_two_stage(params_in, data_eval, model, vae_loss, args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, mask_err=mask_err,", "value) for key, value in dict_op.items()} dirty_row_pos = mask.any(dim=1).bool() n_dirty_rows", "model.eval() p_params, q_params, q_samples = model(data_eval) if not args.AVI: get_pi_exact_vec(model,", "value.shape[0]==data_dirty.shape[0] else value) for key, value in dict_op.items()} dirty_row_pos =", "ret def evaluation_phase(model, data_eval, dataset_obj, args, epoch, clean_comp_show=False, data_eval_clean=False, logit_pi_prev=torch.tensor([]),", "q_samples = model(data_eval) if not args.AVI: get_pi_exact_vec(model, data_eval, p_params, q_params,", "model(data_clean) # no need to get pi, not used after", "'eval_nll_final_clean': nll_clean.item()/eval_data_len, 'eval_z_kld_final_clean': z_kld_clean.item()/eval_data_len, 'eval_w_kld_final_clean': w_kld_clean.item()/eval_data_len } losses = {**losses,", "clean_row_pos) q_params_xd_sliced = dict() if args.outlier_model == 'RVAE': q_params_xd_sliced['w'] =", "only p(x|z, ...) nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) pi_score_mat =", "train_total_loss_seq_vae += seq_total_loss.item() train_loss_seq_vae += seq_final_loss.item() train_nll_seq_vae += seq_final_nll.item() train_z_kld_seq_vae", "model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld,", "= (~mask_err).float() err_pi = ((pi_mtx - pi_mtx_true)**2).mean() ce_pi = F.binary_cross_entropy(pi_mtx,", "model.cpu() if type(mask_err) != type(None): mask_err = mask_err.bool() model.eval() p_params,", "else: p_params_metric, q_params_metric, q_samples_metric = p_params, q_params, q_samples #Getting scores", "train_nll_seq_vae += vae_nll.item() train_z_kld_seq_vae += vae_z_kld.item() train_w_kld_seq_vae += vae_w_kld.item() seq_total_loss", "'seqvae': p_params_metric, q_params_metric, q_samples_metric = p_params_final, q_params_final, q_samples_final else: p_params_metric,", "'mse_lower_bd_dirtycells': error_lb_dc.item(), 'mse_upper_bd_dirtycells': error_up_dc.item() , 'mse_repair_dirtycells': error_repair_dc.item(), 'mse_repair_cleancells': error_repair_cc.item(), 'errors_per_feature':", "args.inference_type == 'seqvae': print('\\n') print('\\n\\nAdditional Info:\\tTotal Seq Loss: {:.3f}\\tFinal Seq", "q_params, q_samples) eval_data_len = data_eval.shape[0] losses = {'eval_loss_vae': vae_loss.item()/eval_data_len, 'eval_nll_vae':vae_nll.item()/eval_data_len,", "((pi_mtx - pi_mtx_true)**2).mean() ce_pi = F.binary_cross_entropy(pi_mtx, pi_mtx_true) print('MSE on pi", "vae_loss, vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_input, p_params, q_params, q_samples) train_loss_vae", "vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_eval, p_params, q_params, q_samples) eval_data_len =", "torch.sigmoid(q_params_metric['w']['logit_pi']).clamp(1e-6, 1-1e-6) # -log p(x|z, ...) used as outlier score", "model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: # 'vae'", "-10 converg_norm_w = -10 else: if clean_comp_show: loss_clean, nll_clean, z_kld_clean,", "train_nll_seq, train_z_kld_seq, train_w_kld_seq = 4*[0] train_total_loss_seq_vae, train_loss_seq_vae, train_nll_seq_vae, train_z_kld_seq_vae, train_w_kld_seq_vae", "get pi vae_loss, vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_eval, p_params, q_params,", "error_up_dc_per_feat = utils.error_computation(model, data_clean, data_dirty, mask, x_input_size=True) # x_truth -", "get_pi_exact_vec(model, data_dirty, p_params_xd, q_params_xd, args, logit_ret=True) params_xd_in = (p_params_xd, q_params_xd,", "losses = {**losses, **losses_add} # q(w|x, ...) param (pi), used", "~dirty_row_pos n_clean_rows = clean_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, clean_row_pos) q_params_xd_sliced =", "'eval_nll_final_clean_all':(vae_nll_cc+vae_nll_dc).item()/eval_data_len, 'eval_z_kld_final_clean_all': (vae_z_kld_cc+vae_z_kld_dc).item()/eval_data_len, 'eval_w_kld_final_clean_all':(vae_w_kld_cc+vae_w_kld_dc).item()/eval_data_len, 'mse_lower_bd_dirtycells': error_lb_dc.item(), 'mse_upper_bd_dirtycells': error_up_dc.item() , 'mse_repair_dirtycells':", "model) error_repair_cc, error_repair_cc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'], 1-mask) print(\"\\n\\n {}", "get_pi_exact_vec(model, data_eval, p_params, q_params, args, logit_ret=True) # get pi vae_loss,", "mean_squared_error import numpy as np import json from . import", "'train_z_kld_vae': train_z_kld_vae/dataset_len, 'train_w_kld_vae': train_w_kld_vae/dataset_len} if args.inference_type == \"seqvae\": ret_seq =", "vae_w_kld_cc = model.loss_function(data_clean[clean_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) eval_data_len =", "dict_slice = lambda dict_op, row_pos: {key:(value[row_pos,:] \\ if value.shape[0]==data_dirty.shape[0] else", "{**losses, **losses_add} # q(w|x, ...) param (pi), used in outlier", "pi_score_mat pi_mtx_true = (~mask_err).float() err_pi = ((pi_mtx - pi_mtx_true)**2).mean() ce_pi", "dirty cells on clean cells under model) error_repair_cc, error_repair_cc_per_feat =", "seq_final_w_kld.item()/eval_data_len, 'eval_total_loss_seq': seq_total_loss.item()/eval_data_len} losses = {**losses, **losses_seq_vae} if args.inference_type ==", "p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) clean_row_pos = ~dirty_row_pos n_clean_rows =", "used as outlier score nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) #", "torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _, _,", "'eval_z_kld_vae': vae_z_kld.item()/eval_data_len, 'eval_w_kld_vae':vae_w_kld.item()/eval_data_len} # SEQ-VAE if args.inference_type == 'seqvae': #with", "train_w_kld_vae/dataset_len} if args.inference_type == \"seqvae\": ret_seq = {'train_loss_seq': train_loss_seq_vae/dataset_len, 'train_nll_seq':", "q_params_xd_sliced = dict() if args.outlier_model == 'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'],", "clean_comp_show=False, data_eval_clean=False, logit_pi_prev=torch.tensor([]), w_conv=False, mask_err=None): # if args.cuda_on: # model.cpu()", "iterations through time and bprops params_in = (p_params, q_params, q_samples)", "data_input.cuda() optimizer.zero_grad() ## first foward-pass p_params, q_params, q_samples = model(data_input,", "# SEQ-VAE if args.inference_type == 'seqvae': #with torch.no_grad(): params_in =", "batch_idx % args.log_interval == 0 and not mute: print('\\n\\nTrain Epoch:", "and bprops params_in = (p_params, q_params, q_samples) seq_loss_pack, _, _", "args, logit_ret=True) # get pi, saves to q_params (with no_grad)", "!= type(None): mask_err = mask_err.bool() model.eval() p_params, q_params, q_samples =", "q(w|x, ...) param (pi), used in outlier score pi_score_mat =", "median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).std())) metrics = {'nll_score': nll_score_mat, 'pi_score':", "device=data_dirty.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: # standard 'vae' type", "epoch_id=epoch) else: # standard 'vae' type inference p_params_xd, q_params_xd, q_samples_xd", "first foward-pass p_params, q_params, q_samples = model(data_input, n_epoch=epoch-1) if not", "= dict_slice(q_params_xd['w'], clean_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], clean_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd,", "w_conv=False, mask_err=None): # if args.cuda_on: # model.cpu() if type(mask_err) !=", "import mean_squared_error import numpy as np import json from .", "on clean cell positions only (to test impact on dirty", "vae_loss.item() train_loss_seq_vae += vae_loss.item() train_nll_seq_vae += vae_nll.item() train_z_kld_seq_vae += vae_z_kld.item()", "= torch.zeros_like(q_params_metric['w']['logit_pi']) converg_norm_w = (q_params_metric['w']['logit_pi'] - logit_pi_prev).norm().item() logit_pi_prev = q_params_metric['w']['logit_pi'].clone().detach()", "clean_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], clean_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, clean_row_pos) vae_loss_cc,", "len(train_loader.dataset), 100. * batch_idx / len(train_loader), vae_loss.item()/len(data_input), vae_nll.item()/len(data_input), vae_z_kld.item()/len(data_input), vae_w_kld.item()/len(data_input)))", "# -log p(x|z, ...) used as outlier score nll_score_mat =", "nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) pi_score_mat = -10 converg_norm_w =", "_, _, (p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_two_stage(params_xd_in, data_dirty, model, torch.tensor(0.0,", "p_params_xd['x'], mask) # x_truth - f_vae(x_dirty) print(\"\\n\\n {} REPAIR ERROR", "n_epoch=epoch-1) if not args.AVI: get_pi_exact_vec(model, data_input, p_params, q_params, args, logit_ret=True)", "q_samples) train_loss_vae += vae_loss.item() train_nll_vae += vae_nll.item() train_z_kld_vae += vae_z_kld.item()", "device=data_clean.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: # 'vae' type inference", "= mask.any(dim=1).bool() n_dirty_rows = dirty_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, dirty_row_pos) q_params_xd_sliced", "q_samples_metric = p_params, q_params, q_samples #Getting scores and clean component", "repair, on dirty cell positions only error_repair_dc, error_repair_dc_per_feat = utils.error_computation(model,", "Info:\\tTotal Seq Loss: {:.3f}\\tFinal Seq Loss: {:.3f}\\tFinal Sep NLL: {:.3f}\\tFinal", "model.loss_function(data_clean[dirty_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) clean_row_pos = ~dirty_row_pos n_clean_rows", "under model) error_repair_cc, error_repair_cc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'], 1-mask) print(\"\\n\\n", "vae_z_kld_cc, vae_w_kld_cc = model.loss_function(data_clean[clean_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) eval_data_len", "of pi's using MSE or cross-entropy if isinstance(mask_err, torch.Tensor): pi_mtx", "train_w_kld_seq_vae = 5*[0] for batch_idx, unpack in enumerate(train_loader): data_input =", "if not args.AVI: get_pi_exact_vec(model, data_eval, p_params, q_params, args, logit_ret=True) #", "device=data_dirty.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _, _, (p_params_xd,", "dict_slice(q_samples_xd, clean_row_pos) vae_loss_cc, vae_nll_cc, vae_z_kld_cc, vae_w_kld_cc = model.loss_function(data_clean[clean_row_pos,:], p_params_xd_sliced, q_params_xd_sliced,", "len(data_input), len(train_loader.dataset), 100. * batch_idx / len(train_loader), vae_loss.item()/len(data_input), vae_nll.item()/len(data_input), vae_z_kld.item()/len(data_input),", "epoch, clean_comp_show=False, data_eval_clean=False, logit_pi_prev=torch.tensor([]), w_conv=False, mask_err=None): # if args.cuda_on: #", "dict_slice(q_params_xd['w'], dirty_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], dirty_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, dirty_row_pos)", "= {'train_loss_seq': train_loss_seq_vae/dataset_len, 'train_nll_seq': train_nll_seq_vae/dataset_len, 'train_z_kld_seq': train_z_kld_seq_vae/dataset_len,'train_w_kld_seq': train_w_kld_seq_vae/dataset_len, 'train_total_loss_seq':train_total_loss_seq_vae/dataset_len} ret", "= {'eval_loss_final_clean': loss_clean.item()/eval_data_len, 'eval_nll_final_clean': nll_clean.item()/eval_data_len, 'eval_z_kld_final_clean': z_kld_clean.item()/eval_data_len, 'eval_w_kld_final_clean': w_kld_clean.item()/eval_data_len }", "model(data_input, n_epoch=epoch-1) if not args.AVI: get_pi_exact_vec(model, data_input, p_params, q_params, args,", "positions only error_lb_dc, error_lb_dc_per_feat = utils.error_computation(model, data_clean, p_params_xc['x'], mask) #", "POS):{}\".format(mode, error_repair_cc)) # Get NLL (predict. posterior approx) under dirty", "'train_w_kld_vae': train_w_kld_vae/dataset_len} if args.inference_type == \"seqvae\": ret_seq = {'train_loss_seq': train_loss_seq_vae/dataset_len,", "# get pi vae_loss, vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_eval, p_params,", "vae_loss.item()/len(data_input), vae_nll.item()/len(data_input), vae_z_kld.item()/len(data_input), vae_w_kld.item()/len(data_input))) if args.inference_type == 'seqvae': print('\\n') print('\\n\\nAdditional", "args.AVI: get_pi_exact_vec(model, data_input, p_params, q_params, args, logit_ret=True) # get pi,", "python3 import torch from torch import optim import torch.nn.functional as", "impact on dirty cells on clean cells under model) error_repair_cc,", "dirty_row_pos) q_params_xd_sliced = dict() if args.outlier_model == 'RVAE': q_params_xd_sliced['w'] =", "z_kld_clean, w_kld_clean = model.loss_function(data_eval, p_params_metric, q_params_metric, q_samples_metric, clean_comp_only=True, data_eval_clean=data_eval_clean) losses_add", "model params with input: underlying clean data if args.inference_type ==", "data_eval_clean=True) eval_data_len = data_dirty.shape[0] losses = {'eval_loss_final_clean_dc': vae_loss_dc.item()/n_dirty_rows, 'eval_nll_final_clean_dc':vae_nll_dc.item()/n_dirty_rows, 'eval_z_kld_final_clean_dc':", ".model_utils import get_pi_exact_vec, rnn_vae_forward_one_stage, rnn_vae_forward_two_stage def training_phase(model, optimizer, train_loader, args,", "rnn_vae_forward_two_stage def training_phase(model, optimizer, train_loader, args, epoch, mute=True): model.train() train_loss_vae,", "args.inference_type == 'seqvae': #with torch.no_grad(): params_in = (p_params, q_params, q_samples)", "'seqvae': p_params_xc, q_params_xc, q_samples_xc = model(data_clean) if not args.AVI: get_pi_exact_vec(model,", "data_clean, p_params_xd['x'], mask) # x_truth - f_vae(x_dirty) print(\"\\n\\n {} REPAIR", "unpack[0] if args.cuda_on: data_input = data_input.cuda() optimizer.zero_grad() ## first foward-pass", "args.seqvae_two_stage: _, _, (p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_two_stage(params_xc_in, data_clean, model,", "number_steps=args.seqvae_steps, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld =", "losses_add = {'eval_loss_final_clean': loss_clean.item()/eval_data_len, 'eval_nll_final_clean': nll_clean.item()/eval_data_len, 'eval_z_kld_final_clean': z_kld_clean.item()/eval_data_len, 'eval_w_kld_final_clean': w_kld_clean.item()/eval_data_len", "vae_z_kld_cc.item()/n_clean_rows, 'eval_w_kld_final_clean_cc':vae_w_kld_cc.item()/n_clean_rows, 'eval_loss_final_clean_all': (vae_loss_cc+vae_loss_dc).item()/eval_data_len, 'eval_nll_final_clean_all':(vae_nll_cc+vae_nll_dc).item()/eval_data_len, 'eval_z_kld_final_clean_all': (vae_z_kld_cc+vae_z_kld_dc).item()/eval_data_len, 'eval_w_kld_final_clean_all':(vae_w_kld_cc+vae_w_kld_dc).item()/eval_data_len, 'mse_lower_bd_dirtycells': error_lb_dc.item(),", "if not args.AVI: get_pi_exact_vec(model, data_input, p_params, q_params, args, logit_ret=True) #", "if args.inference_type == 'vae': vae_loss.backward() elif args.inference_type == 'seqvae': if", "dict_slice(p_params_xd, dirty_row_pos) q_params_xd_sliced = dict() if args.outlier_model == 'RVAE': q_params_xd_sliced['w']", "torch.zeros_like(q_params_metric['w']['logit_pi']) converg_norm_w = (q_params_metric['w']['logit_pi'] - logit_pi_prev).norm().item() logit_pi_prev = q_params_metric['w']['logit_pi'].clone().detach() else:", "Sep KLD_Z: {:.3f}\\tFinal Sep KLD_W: {:.3f}\\n'.format( seq_total_loss.item()/len(data_input), seq_final_loss.item()/len(data_input), seq_final_nll.item()/len(data_input), seq_final_z_kld.item()/len(data_input),", "here measurement of calibration of pi's using MSE or cross-entropy", "(p_params, q_params, q_samples) seq_loss_pack, _, _ = rnn_vae_forward_one_stage(params_in, data_input, model,", "calibration of pi's using MSE or cross-entropy if isinstance(mask_err, torch.Tensor):", "clean cells under model) error_repair_cc, error_repair_cc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'],", "'eval_w_kld_final_clean_dc':vae_w_kld_dc.item()/n_dirty_rows, 'eval_loss_final_clean_cc': vae_loss_cc.item()/n_clean_rows, 'eval_nll_final_clean_cc':vae_nll_cc.item()/n_clean_rows, 'eval_z_kld_final_clean_cc': vae_z_kld_cc.item()/n_clean_rows, 'eval_w_kld_final_clean_cc':vae_w_kld_cc.item()/n_clean_rows, 'eval_loss_final_clean_all': (vae_loss_cc+vae_loss_dc).item()/eval_data_len, 'eval_nll_final_clean_all':(vae_nll_cc+vae_nll_dc).item()/eval_data_len,", "VAE models only (no w's or pi's) # generative model", "cell positions only error_lb_dc, error_lb_dc_per_feat = utils.error_computation(model, data_clean, p_params_xc['x'], mask)", "torch.tensor(0.0) seq_final_w_kld = torch.tensor(0.0) optimizer.step() if batch_idx % args.log_interval ==", "std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).std())) metrics = {'nll_score': nll_score_mat, 'pi_score': pi_score_mat, 'converg_norm_w':", "Sep KLD_W: {:.3f}\\n'.format( seq_total_loss.item()/len(data_input), seq_final_loss.item()/len(data_input), seq_final_nll.item()/len(data_input), seq_final_z_kld.item()/len(data_input), seq_final_w_kld.item()/len(data_input))) dataset_len =", "train_nll_seq_vae/dataset_len, 'train_z_kld_seq': train_z_kld_seq_vae/dataset_len,'train_w_kld_seq': train_w_kld_seq_vae/dataset_len, 'train_total_loss_seq':train_total_loss_seq_vae/dataset_len} ret = {**ret, **ret_seq} return", "(p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_one_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device), args,", "input: underlying clean data if args.inference_type == 'seqvae': p_params_xc, q_params_xc,", "vae_z_kld.item()/eval_data_len, 'eval_w_kld_vae':vae_w_kld.item()/eval_data_len} # SEQ-VAE if args.inference_type == 'seqvae': #with torch.no_grad():", "not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xd, q_params_xd, args, logit_ret=True) # get", "...) used as outlier score nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj)", "#with torch.no_grad(): params_in = (p_params, q_params, q_samples) if args.seqvae_two_stage: seq_loss_pack,", "after # error (MSE) lower bound, on dirty cell positions", "**ret_seq} return ret def evaluation_phase(model, data_eval, dataset_obj, args, epoch, clean_comp_show=False,", "number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _, _, (p_params_xc, q_params_xc, q_samples_xc)", "{} REPAIR ERROR (DIRTY POS):{}\".format(mode, error_repair_dc)) # error upper bound,", "q_params_metric, q_samples_metric, clean_comp_only=True, data_eval_clean=data_eval_clean) losses_add = {'eval_loss_final_clean': loss_clean.item()/eval_data_len, 'eval_nll_final_clean': nll_clean.item()/eval_data_len,", "model(data_dirty) if not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xd, q_params_xd, args, logit_ret=True)", "logit_pi_prev.nelement() == 0: logit_pi_prev = torch.zeros_like(q_params_metric['w']['logit_pi']) converg_norm_w = (q_params_metric['w']['logit_pi'] -", "'eval_nll_final_clean_dc':vae_nll_dc.item()/n_dirty_rows, 'eval_z_kld_final_clean_dc': vae_z_kld_dc.item()/n_dirty_rows, 'eval_w_kld_final_clean_dc':vae_w_kld_dc.item()/n_dirty_rows, 'eval_loss_final_clean_cc': vae_loss_cc.item()/n_clean_rows, 'eval_nll_final_clean_cc':vae_nll_cc.item()/n_clean_rows, 'eval_z_kld_final_clean_cc': vae_z_kld_cc.item()/n_clean_rows, 'eval_w_kld_final_clean_cc':vae_w_kld_cc.item()/n_clean_rows,", "score pi_score_mat = torch.sigmoid(q_params_metric['w']['logit_pi']).clamp(1e-6, 1-1e-6) # -log p(x|z, ...) used", "if args.inference_type == 'seqvae': #with torch.no_grad(): params_in = (p_params, q_params,", "# VAE models only (no w's or pi's) # generative", "dataset_obj, args, mask, mode, epoch): model.eval() # model params with", "under dirty data dict_slice = lambda dict_op, row_pos: {key:(value[row_pos,:] \\", "no_grad) vae_loss, vae_nll, vae_z_kld, vae_w_kld = model.loss_function(data_input, p_params, q_params, q_samples)", "args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld =", "if args.seqvae_two_stage: _, _, (p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_two_stage(params_xd_in, data_dirty,", "type inference p_params_xc, q_params_xc, q_samples_xc = model(data_clean) # no need", "NLL (predict. posterior approx) under dirty data dict_slice = lambda", "saves to q_params (with no_grad) vae_loss, vae_nll, vae_z_kld, vae_w_kld =", "clean data if args.inference_type == 'seqvae': p_params_xc, q_params_xc, q_samples_xc =", "get pi, not used after # error (MSE) lower bound,", "(DIRTY POS):{}\".format(mode, error_repair_dc)) # error upper bound, on dirty cell", "# check convergence of weights (pi's) if w_conv: if logit_pi_prev.nelement()", "ret = {'train_loss_vae': train_loss_vae/dataset_len, 'train_nll_vae': train_nll_vae/dataset_len, 'train_z_kld_vae': train_z_kld_vae/dataset_len, 'train_w_kld_vae': train_w_kld_vae/dataset_len}", "_, _, (p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_one_stage(params_xd_in, data_dirty, model, torch.tensor(0.0,", "data_clean, data_dirty, mask, x_input_size=True) # x_truth - x_dirty # error", "model only p(x|z, ...) nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) pi_score_mat", "batch_idx, unpack in enumerate(train_loader): data_input = unpack[0] if args.cuda_on: data_input", "= torch.tensor(0.0) seq_final_z_kld = torch.tensor(0.0) seq_final_w_kld = torch.tensor(0.0) optimizer.step() if", "q_params, q_samples) if args.seqvae_two_stage: seq_loss_pack, _, seq_param_pack = rnn_vae_forward_two_stage(params_in, data_eval,", "eval_data_len = data_eval.shape[0] losses = {'eval_loss_vae': vae_loss.item()/eval_data_len, 'eval_nll_vae':vae_nll.item()/eval_data_len, 'eval_z_kld_vae': vae_z_kld.item()/eval_data_len,", "to get pi, not used after # error (MSE) lower", "q_samples) seq_loss_pack, _, _ = rnn_vae_forward_one_stage(params_in, data_input, model, vae_loss, args,", "Loss: {:.3f}\\tFinal Seq Loss: {:.3f}\\tFinal Sep NLL: {:.3f}\\tFinal Sep KLD_Z:", "train_loss_vae/dataset_len, 'train_nll_vae': train_nll_vae/dataset_len, 'train_z_kld_vae': train_z_kld_vae/dataset_len, 'train_w_kld_vae': train_w_kld_vae/dataset_len} if args.inference_type ==", "# error on clean cell positions only (to test impact", "return ret def evaluation_phase(model, data_eval, dataset_obj, args, epoch, clean_comp_show=False, data_eval_clean=False,", "= seq_param_pack losses_seq_vae = {'eval_loss_seq': seq_final_loss.item()/eval_data_len, 'eval_nll_seq': seq_final_nll.item()/eval_data_len, 'eval_z_kld_seq': seq_final_z_kld.item()/eval_data_len,", "- logit_pi_prev).norm().item() logit_pi_prev = q_params_metric['w']['logit_pi'].clone().detach() else: converg_norm_w = -10 #", "logit_ret=True) params_xc_in = (p_params_xc, q_params_xc, q_samples_xc) if args.seqvae_two_stage: _, _,", "cells under model) error_repair_cc, error_repair_cc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'], 1-mask)", "train_loss_vae, train_nll_vae, train_z_kld_vae, train_w_kld_vae = 4*[0] train_loss_seq, train_nll_seq, train_z_kld_seq, train_w_kld_seq", "error_repair_cc, error_repair_cc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'], 1-mask) print(\"\\n\\n {} REPAIR", "# model params with input: dirty data if args.inference_type ==", "generative model only p(x|z, ...) nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj)", "if args.inference_type == 'seqvae': print('\\n') print('\\n\\nAdditional Info:\\tTotal Seq Loss: {:.3f}\\tFinal", "from .model_utils import get_pi_exact_vec, rnn_vae_forward_one_stage, rnn_vae_forward_two_stage def training_phase(model, optimizer, train_loader,", "+= vae_nll.item() train_z_kld_vae += vae_z_kld.item() train_w_kld_vae += vae_w_kld.item() if args.inference_type", "ERROR (DIRTY POS):{}\".format(mode, error_repair_dc)) # error upper bound, on dirty", "seq_final_loss.item()/len(data_input), seq_final_nll.item()/len(data_input), seq_final_z_kld.item()/len(data_input), seq_final_w_kld.item()/len(data_input))) dataset_len = float(len(train_loader.dataset)) ret = {'train_loss_vae':", "_, (p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_two_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device),", "{:.3f}\\tFinal Seq Loss: {:.3f}\\tFinal Sep NLL: {:.3f}\\tFinal Sep KLD_Z: {:.3f}\\tFinal", "args.inference_type == 'seqvae': p_params_xc, q_params_xc, q_samples_xc = model(data_clean) if not", "train_z_kld_seq_vae, train_w_kld_seq_vae = 5*[0] for batch_idx, unpack in enumerate(train_loader): data_input", "+= seq_final_loss.item() train_nll_seq_vae += seq_final_nll.item() train_z_kld_seq_vae += seq_final_z_kld.item() train_w_kld_seq_vae +=", "{'train_loss_seq': train_loss_seq_vae/dataset_len, 'train_nll_seq': train_nll_seq_vae/dataset_len, 'train_z_kld_seq': train_z_kld_seq_vae/dataset_len,'train_w_kld_seq': train_w_kld_seq_vae/dataset_len, 'train_total_loss_seq':train_total_loss_seq_vae/dataset_len} ret =", "pred: {}'.format(ce_pi)) print('dirt pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).std())) print('clean", "number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _, _, (p_params_xd, q_params_xd, q_samples_xd)", "'train_nll_vae': train_nll_vae/dataset_len, 'train_z_kld_vae': train_z_kld_vae/dataset_len, 'train_w_kld_vae': train_w_kld_vae/dataset_len} if args.inference_type == \"seqvae\":", "if not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xc, q_params_xc, args, logit_ret=True) params_xc_in", "args, epoch, mute=True): model.train() train_loss_vae, train_nll_vae, train_z_kld_vae, train_w_kld_vae = 4*[0]", "seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack train_total_loss_seq_vae += seq_total_loss.item() train_loss_seq_vae +=", "train_w_kld_seq_vae += seq_final_w_kld.item() else: vae_loss.backward() train_total_loss_seq_vae += vae_loss.item() train_loss_seq_vae +=", "seq_final_z_kld = torch.tensor(0.0) seq_final_w_kld = torch.tensor(0.0) optimizer.step() if batch_idx %", "train_z_kld_seq_vae/dataset_len,'train_w_kld_seq': train_w_kld_seq_vae/dataset_len, 'train_total_loss_seq':train_total_loss_seq_vae/dataset_len} ret = {**ret, **ret_seq} return ret def", "pi_mtx_true = (~mask_err).float() err_pi = ((pi_mtx - pi_mtx_true)**2).mean() ce_pi =", "= model.loss_function(data_eval, p_params, q_params, q_samples) eval_data_len = data_eval.shape[0] losses =", "else: _, _, (p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_one_stage(params_xd_in, data_dirty, model,", "pi_mtx_true) print('MSE on pi pred: {}'.format(err_pi)) print('CE on pi pred:", "train_nll_seq_vae += seq_final_nll.item() train_z_kld_seq_vae += seq_final_z_kld.item() train_w_kld_seq_vae += seq_final_w_kld.item() else:", "n_clean_rows = clean_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, clean_row_pos) q_params_xd_sliced = dict()", "on dirty cell positions only error_lb_dc, error_lb_dc_per_feat = utils.error_computation(model, data_clean,", "4*[0] train_loss_seq, train_nll_seq, train_z_kld_seq, train_w_kld_seq = 4*[0] train_total_loss_seq_vae, train_loss_seq_vae, train_nll_seq_vae,", "{'eval_loss_seq': seq_final_loss.item()/eval_data_len, 'eval_nll_seq': seq_final_nll.item()/eval_data_len, 'eval_z_kld_seq': seq_final_z_kld.item()/eval_data_len, 'eval_w_kld_seq': seq_final_w_kld.item()/eval_data_len, 'eval_total_loss_seq': seq_total_loss.item()/eval_data_len}", "bound, on dirty cell positions only error_lb_dc, error_lb_dc_per_feat = utils.error_computation(model,", "w_kld_clean = model.loss_function(data_eval, p_params_metric, q_params_metric, q_samples_metric, clean_comp_only=True, data_eval_clean=data_eval_clean) losses_add =", "= dict_slice(q_samples_xd, dirty_row_pos) vae_loss_dc, vae_nll_dc, vae_z_kld_dc, vae_w_kld_dc = model.loss_function(data_clean[dirty_row_pos,:], p_params_xd_sliced,", "dict_slice(q_samples_xd, dirty_row_pos) vae_loss_dc, vae_nll_dc, vae_z_kld_dc, vae_w_kld_dc = model.loss_function(data_clean[dirty_row_pos,:], p_params_xd_sliced, q_params_xd_sliced,", "{key:(value[row_pos,:] \\ if value.shape[0]==data_dirty.shape[0] else value) for key, value in", "dataset_obj) # check convergence of weights (pi's) if w_conv: if", "Epoch: {} [{}/{} ({:.0f}%)]\\tVAE Loss: {:.3f}\\tVAE NLL: {:.3f}\\tVAE KLD_Z: {:.3f}\\tVAE", "seq_final_nll = torch.tensor(0.0) seq_final_z_kld = torch.tensor(0.0) seq_final_w_kld = torch.tensor(0.0) optimizer.step()", "data_dirty, p_params_xc, q_params_xc, args, logit_ret=True) params_xc_in = (p_params_xc, q_params_xc, q_samples_xc)", "unpack in enumerate(train_loader): data_input = unpack[0] if args.cuda_on: data_input =", "q_params, q_samples = model(data_input, n_epoch=epoch-1) if not args.AVI: get_pi_exact_vec(model, data_input,", "_, _ = rnn_vae_forward_one_stage(params_in, data_input, model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True,", "torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).std())) metrics = {'nll_score': nll_score_mat, 'pi_score': pi_score_mat, 'converg_norm_w': converg_norm_w} return", "+= vae_z_kld.item() train_w_kld_vae += vae_w_kld.item() if args.inference_type == 'vae': vae_loss.backward()", "_, _, (p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_two_stage(params_xc_in, data_clean, model, torch.tensor(0.0,", "= dict_slice(q_params_xd['w'], dirty_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], dirty_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd,", "seq_final_z_kld, seq_final_w_kld = seq_loss_pack p_params_final, q_params_final, q_samples_final = seq_param_pack losses_seq_vae", "q_samples_xd) if args.seqvae_two_stage: _, _, (p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_two_stage(params_xd_in,", "on pi pred: {}'.format(err_pi)) print('CE on pi pred: {}'.format(ce_pi)) print('dirt", "+= vae_w_kld.item() seq_total_loss = torch.tensor(0.0) seq_final_loss = torch.tensor(0.0) seq_final_nll =", "train_loss_seq, train_nll_seq, train_z_kld_seq, train_w_kld_seq = 4*[0] train_total_loss_seq_vae, train_loss_seq_vae, train_nll_seq_vae, train_z_kld_seq_vae,", "clean_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, clean_row_pos) q_params_xd_sliced = dict() if args.outlier_model", "optimizer.zero_grad() ## first foward-pass p_params, q_params, q_samples = model(data_input, n_epoch=epoch-1)", "p_params_final, q_params_final, q_samples_final else: p_params_metric, q_params_metric, q_samples_metric = p_params, q_params,", "if args.seqvae_bprop: # NOTE: rolls out iterations through time and", "with torch.no_grad(): if args.outlier_model == \"VAE\": # VAE models only", "if args.seqvae_two_stage: seq_loss_pack, _, seq_param_pack = rnn_vae_forward_two_stage(params_in, data_eval, model, vae_loss,", "if logit_pi_prev.nelement() == 0: logit_pi_prev = torch.zeros_like(q_params_metric['w']['logit_pi']) converg_norm_w = (q_params_metric['w']['logit_pi']", "(q_params_metric['w']['logit_pi'] - logit_pi_prev).norm().item() logit_pi_prev = q_params_metric['w']['logit_pi'].clone().detach() else: converg_norm_w = -10", ". import utils from .model_utils import get_pi_exact_vec, rnn_vae_forward_one_stage, rnn_vae_forward_two_stage def", "type(mask_err) != type(None): mask_err = mask_err.bool() model.eval() p_params, q_params, q_samples", "= {**losses, **losses_add} # q(w|x, ...) param (pi), used in", "q_params_final, q_samples_final else: p_params_metric, q_params_metric, q_samples_metric = p_params, q_params, q_samples", "models only (no w's or pi's) # generative model only", "= pi_score_mat pi_mtx_true = (~mask_err).float() err_pi = ((pi_mtx - pi_mtx_true)**2).mean()", "(p_params_xd, q_params_xd, q_samples_xd) if args.seqvae_two_stage: _, _, (p_params_xd, q_params_xd, q_samples_xd)", "'eval_z_kld_final_clean_all': (vae_z_kld_cc+vae_z_kld_dc).item()/eval_data_len, 'eval_w_kld_final_clean_all':(vae_w_kld_cc+vae_w_kld_dc).item()/eval_data_len, 'mse_lower_bd_dirtycells': error_lb_dc.item(), 'mse_upper_bd_dirtycells': error_up_dc.item() , 'mse_repair_dirtycells': error_repair_dc.item(),", "train_w_kld_seq_vae += vae_w_kld.item() seq_total_loss = torch.tensor(0.0) seq_final_loss = torch.tensor(0.0) seq_final_nll", "q_samples_xd) = rnn_vae_forward_one_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, loss_per_iter=True,", "with input: dirty data if args.inference_type == 'seqvae': p_params_xd, q_params_xd,", "number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _, _, (p_params_xd, q_params_xd, q_samples_xd) =", "q_params_xc, q_samples_xc) if args.seqvae_two_stage: _, _, (p_params_xc, q_params_xc, q_samples_xc) =", "(p_params, q_params, q_samples) if args.seqvae_two_stage: seq_loss_pack, _, seq_param_pack = rnn_vae_forward_two_stage(params_in,", "dict() if args.outlier_model == 'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], clean_row_pos) q_params_xd_sliced['z']", "Sep NLL: {:.3f}\\tFinal Sep KLD_Z: {:.3f}\\tFinal Sep KLD_W: {:.3f}\\n'.format( seq_total_loss.item()/len(data_input),", "clean_comp_only=True, data_eval_clean=True) clean_row_pos = ~dirty_row_pos n_clean_rows = clean_row_pos.sum().item() p_params_xd_sliced =", "import get_pi_exact_vec, rnn_vae_forward_one_stage, rnn_vae_forward_two_stage def training_phase(model, optimizer, train_loader, args, epoch,", "\\ if value.shape[0]==data_dirty.shape[0] else value) for key, value in dict_op.items()}", "if args.cuda_on: data_input = data_input.cuda() optimizer.zero_grad() ## first foward-pass p_params,", "dirty_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], dirty_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, dirty_row_pos) vae_loss_dc,", "rnn_vae_forward_one_stage(params_in, data_input, model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) seq_total_loss, seq_final_loss,", "= data_eval.shape[0] losses = {'eval_loss_vae': vae_loss.item()/eval_data_len, 'eval_nll_vae':vae_nll.item()/eval_data_len, 'eval_z_kld_vae': vae_z_kld.item()/eval_data_len, 'eval_w_kld_vae':vae_w_kld.item()/eval_data_len}", "* len(data_input), len(train_loader.dataset), 100. * batch_idx / len(train_loader), vae_loss.item()/len(data_input), vae_nll.item()/len(data_input),", "rolls out iterations through time and bprops params_in = (p_params,", "{:.3f}\\tFinal Sep KLD_W: {:.3f}\\n'.format( seq_total_loss.item()/len(data_input), seq_final_loss.item()/len(data_input), seq_final_nll.item()/len(data_input), seq_final_z_kld.item()/len(data_input), seq_final_w_kld.item()/len(data_input))) dataset_len", "train_loss_vae += vae_loss.item() train_nll_vae += vae_nll.item() train_z_kld_vae += vae_z_kld.item() train_w_kld_vae", "torch.tensor(0.0) seq_final_nll = torch.tensor(0.0) seq_final_z_kld = torch.tensor(0.0) seq_final_w_kld = torch.tensor(0.0)", "get_pi_exact_vec(model, data_input, p_params, q_params, args, logit_ret=True) # get pi, saves", "data_dirty, p_params_xd, q_params_xd, args, logit_ret=True) params_xd_in = (p_params_xd, q_params_xd, q_samples_xd)", "{'eval_loss_final_clean_dc': vae_loss_dc.item()/n_dirty_rows, 'eval_nll_final_clean_dc':vae_nll_dc.item()/n_dirty_rows, 'eval_z_kld_final_clean_dc': vae_z_kld_dc.item()/n_dirty_rows, 'eval_w_kld_final_clean_dc':vae_w_kld_dc.item()/n_dirty_rows, 'eval_loss_final_clean_cc': vae_loss_cc.item()/n_clean_rows, 'eval_nll_final_clean_cc':vae_nll_cc.item()/n_clean_rows, 'eval_z_kld_final_clean_cc':", "get_pi_exact_vec, rnn_vae_forward_one_stage, rnn_vae_forward_two_stage def training_phase(model, optimizer, train_loader, args, epoch, mute=True):", "{}'.format(err_pi)) print('CE on pi pred: {}'.format(ce_pi)) print('dirt pi median: {}", "loss_per_iter=True, epoch_id=epoch) else: _, _, (p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_one_stage(params_xd_in,", "'eval_z_kld_final_clean': z_kld_clean.item()/eval_data_len, 'eval_w_kld_final_clean': w_kld_clean.item()/eval_data_len } losses = {**losses, **losses_add} #", "seq_total_loss = torch.tensor(0.0) seq_final_loss = torch.tensor(0.0) seq_final_nll = torch.tensor(0.0) seq_final_z_kld", "= model.loss_function(data_clean[clean_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) eval_data_len = data_dirty.shape[0]", "score nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) # check convergence of", "q_samples) eval_data_len = data_eval.shape[0] losses = {'eval_loss_vae': vae_loss.item()/eval_data_len, 'eval_nll_vae':vae_nll.item()/eval_data_len, 'eval_z_kld_vae':", "converg_norm_w = -10 else: if clean_comp_show: loss_clean, nll_clean, z_kld_clean, w_kld_clean", "# error (MSE) lower bound, on dirty cell positions only", "/ len(train_loader), vae_loss.item()/len(data_input), vae_nll.item()/len(data_input), vae_z_kld.item()/len(data_input), vae_w_kld.item()/len(data_input))) if args.inference_type == 'seqvae':", "clean_comp_only=True, data_eval_clean=data_eval_clean) losses_add = {'eval_loss_final_clean': loss_clean.item()/eval_data_len, 'eval_nll_final_clean': nll_clean.item()/eval_data_len, 'eval_z_kld_final_clean': z_kld_clean.item()/eval_data_len,", "params with input: underlying clean data if args.inference_type == 'seqvae':", "q_params, args, logit_ret=True) # get pi vae_loss, vae_nll, vae_z_kld, vae_w_kld", "== 'seqvae': p_params_xc, q_params_xc, q_samples_xc = model(data_clean) if not args.AVI:", "q_samples) if args.seqvae_two_stage: seq_loss_pack, _, seq_param_pack = rnn_vae_forward_two_stage(params_in, data_eval, model,", "p_params, q_params, q_samples = model(data_eval) if not args.AVI: get_pi_exact_vec(model, data_eval,", "utils.error_computation(model, data_clean, p_params_xd['x'], 1-mask) print(\"\\n\\n {} REPAIR ERROR (CLEAN POS):{}\".format(mode,", "train_w_kld_vae += vae_w_kld.item() if args.inference_type == 'vae': vae_loss.backward() elif args.inference_type", "mute: print('\\n\\nTrain Epoch: {} [{}/{} ({:.0f}%)]\\tVAE Loss: {:.3f}\\tVAE NLL: {:.3f}\\tVAE", "# generative model only p(x|z, ...) nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval,", "_, (p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_two_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device),", "logit_pi_prev = torch.zeros_like(q_params_metric['w']['logit_pi']) converg_norm_w = (q_params_metric['w']['logit_pi'] - logit_pi_prev).norm().item() logit_pi_prev =", "epoch_id=epoch) else: # 'vae' type inference p_params_xc, q_params_xc, q_samples_xc =", "data_eval_clean=data_eval_clean) losses_add = {'eval_loss_final_clean': loss_clean.item()/eval_data_len, 'eval_nll_final_clean': nll_clean.item()/eval_data_len, 'eval_z_kld_final_clean': z_kld_clean.item()/eval_data_len, 'eval_w_kld_final_clean':", "params_xc_in = (p_params_xc, q_params_xc, q_samples_xc) if args.seqvae_two_stage: _, _, (p_params_xc,", "data_input = data_input.cuda() optimizer.zero_grad() ## first foward-pass p_params, q_params, q_samples", "= {**losses, **losses_seq_vae} if args.inference_type == 'seqvae': p_params_metric, q_params_metric, q_samples_metric", "q_samples_xc = model(data_clean) # no need to get pi, not", "= utils.error_computation(model, data_clean, p_params_xd['x'], mask) # x_truth - f_vae(x_dirty) print(\"\\n\\n", "else: converg_norm_w = -10 # insert here measurement of calibration", "utils.error_computation(model, data_clean, data_dirty, mask, x_input_size=True) # x_truth - x_dirty #", "data_clean, model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: #", "clean_row_pos) vae_loss_cc, vae_nll_cc, vae_z_kld_cc, vae_w_kld_cc = model.loss_function(data_clean[clean_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced,", "vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld,", "batch_idx * len(data_input), len(train_loader.dataset), 100. * batch_idx / len(train_loader), vae_loss.item()/len(data_input),", "seq_loss_pack train_total_loss_seq_vae += seq_total_loss.item() train_loss_seq_vae += seq_final_loss.item() train_nll_seq_vae += seq_final_nll.item()", "not used after # error (MSE) lower bound, on dirty", "argparse from sklearn.metrics import mean_squared_error import numpy as np import", "len(train_loader), vae_loss.item()/len(data_input), vae_nll.item()/len(data_input), vae_z_kld.item()/len(data_input), vae_w_kld.item()/len(data_input))) if args.inference_type == 'seqvae': print('\\n')", "pi_score_mat, 'converg_norm_w': converg_norm_w} return losses, metrics def repair_phase(model, data_dirty, data_clean,", "'eval_w_kld_vae':vae_w_kld.item()/eval_data_len} # SEQ-VAE if args.inference_type == 'seqvae': #with torch.no_grad(): params_in", "== 'seqvae': print('\\n') print('\\n\\nAdditional Info:\\tTotal Seq Loss: {:.3f}\\tFinal Seq Loss:", "{} [{}/{} ({:.0f}%)]\\tVAE Loss: {:.3f}\\tVAE NLL: {:.3f}\\tVAE KLD_Z: {:.3f}\\tVAE KLD_W:", "'eval_total_loss_seq': seq_total_loss.item()/eval_data_len} losses = {**losses, **losses_seq_vae} if args.inference_type == 'seqvae':", "REPAIR ERROR (DIRTY POS):{}\".format(mode, error_repair_dc)) # error upper bound, on", "get_pi_exact_vec(model, data_dirty, p_params_xc, q_params_xc, args, logit_ret=True) params_xc_in = (p_params_xc, q_params_xc,", "'eval_w_kld_final_clean_cc':vae_w_kld_cc.item()/n_clean_rows, 'eval_loss_final_clean_all': (vae_loss_cc+vae_loss_dc).item()/eval_data_len, 'eval_nll_final_clean_all':(vae_nll_cc+vae_nll_dc).item()/eval_data_len, 'eval_z_kld_final_clean_all': (vae_z_kld_cc+vae_z_kld_dc).item()/eval_data_len, 'eval_w_kld_final_clean_all':(vae_w_kld_cc+vae_w_kld_dc).item()/eval_data_len, 'mse_lower_bd_dirtycells': error_lb_dc.item(), 'mse_upper_bd_dirtycells':", "data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else:", "else: seq_loss_pack, _, seq_param_pack = rnn_vae_forward_one_stage(params_in, data_eval, model, vae_loss, args,", "= rnn_vae_forward_two_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True,", "q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True) eval_data_len = data_dirty.shape[0] losses = {'eval_loss_final_clean_dc':", "== \"VAE\": # VAE models only (no w's or pi's)", "pred: {}'.format(err_pi)) print('CE on pi pred: {}'.format(ce_pi)) print('dirt pi median:", "seq_loss_pack, _, seq_param_pack = rnn_vae_forward_two_stage(params_in, data_eval, model, vae_loss, args, number_steps=args.seqvae_steps,", "= {'eval_loss_final_clean_dc': vae_loss_dc.item()/n_dirty_rows, 'eval_nll_final_clean_dc':vae_nll_dc.item()/n_dirty_rows, 'eval_z_kld_final_clean_dc': vae_z_kld_dc.item()/n_dirty_rows, 'eval_w_kld_final_clean_dc':vae_w_kld_dc.item()/n_dirty_rows, 'eval_loss_final_clean_cc': vae_loss_cc.item()/n_clean_rows, 'eval_nll_final_clean_cc':vae_nll_cc.item()/n_clean_rows,", "_, seq_param_pack = rnn_vae_forward_two_stage(params_in, data_eval, model, vae_loss, args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage,", "= rnn_vae_forward_one_stage(params_in, data_input, model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) seq_total_loss,", "rnn_vae_forward_one_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else:", "if not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xd, q_params_xd, args, logit_ret=True) params_xd_in", "{:.3f}\\tFinal Sep KLD_Z: {:.3f}\\tFinal Sep KLD_W: {:.3f}\\n'.format( seq_total_loss.item()/len(data_input), seq_final_loss.item()/len(data_input), seq_final_nll.item()/len(data_input),", "mask) # x_truth - f_vae(x_clean) # error repair, on dirty", "no need to get pi, not used after # error", "# no need to get pi, not used after #", "{'nll_score': nll_score_mat, 'pi_score': pi_score_mat, 'converg_norm_w': converg_norm_w} return losses, metrics def", "on clean cells under model) error_repair_cc, error_repair_cc_per_feat = utils.error_computation(model, data_clean,", "= lambda dict_op, row_pos: {key:(value[row_pos,:] \\ if value.shape[0]==data_dirty.shape[0] else value)", "q_params, q_samples = model(data_eval) if not args.AVI: get_pi_exact_vec(model, data_eval, p_params,", "nll_score_mat, 'pi_score': pi_score_mat, 'converg_norm_w': converg_norm_w} return losses, metrics def repair_phase(model,", "= 5*[0] for batch_idx, unpack in enumerate(train_loader): data_input = unpack[0]", "train_total_loss_seq_vae += vae_loss.item() train_loss_seq_vae += vae_loss.item() train_nll_seq_vae += vae_nll.item() train_z_kld_seq_vae", "epoch, mute=True): model.train() train_loss_vae, train_nll_vae, train_z_kld_vae, train_w_kld_vae = 4*[0] train_loss_seq,", "dirty_row_pos) vae_loss_dc, vae_nll_dc, vae_z_kld_dc, vae_w_kld_dc = model.loss_function(data_clean[dirty_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced,", "vae_loss_cc, vae_nll_cc, vae_z_kld_cc, vae_w_kld_cc = model.loss_function(data_clean[clean_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True,", "+= seq_final_z_kld.item() train_w_kld_seq_vae += seq_final_w_kld.item() else: vae_loss.backward() train_total_loss_seq_vae += vae_loss.item()", "Seq Loss: {:.3f}\\tFinal Seq Loss: {:.3f}\\tFinal Sep NLL: {:.3f}\\tFinal Sep", "print('CE on pi pred: {}'.format(ce_pi)) print('dirt pi median: {} std:", "- x_dirty # error on clean cell positions only (to", "p_params_metric, q_params_metric, q_samples_metric = p_params_final, q_params_final, q_samples_final else: p_params_metric, q_params_metric,", "error_repair_dc, error_repair_dc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'], mask) # x_truth -", "print('clean pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][~mask_err]).std())) metrics = {'nll_score':", "'mse_repair_dirtycells': error_repair_dc.item(), 'mse_repair_cleancells': error_repair_cc.item(), 'errors_per_feature': [error_lb_dc_per_feat, error_repair_dc_per_feat, error_up_dc_per_feat, error_repair_cc_per_feat]} return", "get pi # model params with input: underlying clean data", "= rnn_vae_forward_two_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True,", "using MSE or cross-entropy if isinstance(mask_err, torch.Tensor): pi_mtx = pi_score_mat", "number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: # 'vae' type inference p_params_xc, q_params_xc,", "mask_err=mask_err, epoch_id=epoch) else: seq_loss_pack, _, seq_param_pack = rnn_vae_forward_one_stage(params_in, data_eval, model,", "data dict_slice = lambda dict_op, row_pos: {key:(value[row_pos,:] \\ if value.shape[0]==data_dirty.shape[0]", "not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xc, q_params_xc, args, logit_ret=True) params_xc_in =", "args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: # standard 'vae' type inference", "seq_loss_pack, _, _ = rnn_vae_forward_one_stage(params_in, data_input, model, vae_loss, args, number_steps=args.seqvae_steps,", "optim import torch.nn.functional as F import argparse from sklearn.metrics import", "dataset_len = float(len(train_loader.dataset)) ret = {'train_loss_vae': train_loss_vae/dataset_len, 'train_nll_vae': train_nll_vae/dataset_len, 'train_z_kld_vae':", "# model.cpu() if type(mask_err) != type(None): mask_err = mask_err.bool() model.eval()", "q_samples = model(data_input, n_epoch=epoch-1) if not args.AVI: get_pi_exact_vec(model, data_input, p_params,", "data_eval, dataset_obj, args, epoch, clean_comp_show=False, data_eval_clean=False, logit_pi_prev=torch.tensor([]), w_conv=False, mask_err=None): #", "= {'eval_loss_seq': seq_final_loss.item()/eval_data_len, 'eval_nll_seq': seq_final_nll.item()/eval_data_len, 'eval_z_kld_seq': seq_final_z_kld.item()/eval_data_len, 'eval_w_kld_seq': seq_final_w_kld.item()/eval_data_len, 'eval_total_loss_seq':", "number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) seq_total_loss, seq_final_loss, seq_final_nll, seq_final_z_kld, seq_final_w_kld = seq_loss_pack", "train_total_loss_seq_vae, train_loss_seq_vae, train_nll_seq_vae, train_z_kld_seq_vae, train_w_kld_seq_vae = 5*[0] for batch_idx, unpack", "through time and bprops params_in = (p_params, q_params, q_samples) seq_loss_pack,", "== \"seqvae\": ret_seq = {'train_loss_seq': train_loss_seq_vae/dataset_len, 'train_nll_seq': train_nll_seq_vae/dataset_len, 'train_z_kld_seq': train_z_kld_seq_vae/dataset_len,'train_w_kld_seq':", "data_eval_clean=False, logit_pi_prev=torch.tensor([]), w_conv=False, mask_err=None): # if args.cuda_on: # model.cpu() if", "(p_params_xd, q_params_xd, q_samples_xd) = rnn_vae_forward_one_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args,", "err_pi = ((pi_mtx - pi_mtx_true)**2).mean() ce_pi = F.binary_cross_entropy(pi_mtx, pi_mtx_true) print('MSE", "if batch_idx % args.log_interval == 0 and not mute: print('\\n\\nTrain", "train_z_kld_seq, train_w_kld_seq = 4*[0] train_total_loss_seq_vae, train_loss_seq_vae, train_nll_seq_vae, train_z_kld_seq_vae, train_w_kld_seq_vae =", "data_eval, model, vae_loss, args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) else:", "[{}/{} ({:.0f}%)]\\tVAE Loss: {:.3f}\\tVAE NLL: {:.3f}\\tVAE KLD_Z: {:.3f}\\tVAE KLD_W: {:.3f}'.format(", "# get pi # model params with input: underlying clean", "= dirty_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, dirty_row_pos) q_params_xd_sliced = dict() if", "lower bound, on dirty cell positions only error_lb_dc, error_lb_dc_per_feat =", "\"seqvae\": ret_seq = {'train_loss_seq': train_loss_seq_vae/dataset_len, 'train_nll_seq': train_nll_seq_vae/dataset_len, 'train_z_kld_seq': train_z_kld_seq_vae/dataset_len,'train_w_kld_seq': train_w_kld_seq_vae/dataset_len,", "args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xc, q_params_xc, args, logit_ret=True) params_xc_in = (p_params_xc,", "error_repair_dc)) # error upper bound, on dirty cell positions only", "key, value in dict_op.items()} dirty_row_pos = mask.any(dim=1).bool() n_dirty_rows = dirty_row_pos.sum().item()", "data_dirty, data_clean, dataset_obj, args, mask, mode, epoch): model.eval() # model", "== 0: logit_pi_prev = torch.zeros_like(q_params_metric['w']['logit_pi']) converg_norm_w = (q_params_metric['w']['logit_pi'] - logit_pi_prev).norm().item()", "p_params, q_params, q_samples #Getting scores and clean component if neededin_aux_samples", "pi, saves to q_params (with no_grad) vae_loss, vae_nll, vae_z_kld, vae_w_kld", "seq_final_nll.item()/len(data_input), seq_final_z_kld.item()/len(data_input), seq_final_w_kld.item()/len(data_input))) dataset_len = float(len(train_loader.dataset)) ret = {'train_loss_vae': train_loss_vae/dataset_len,", "(p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_two_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device), args,", "clean component if neededin_aux_samples with torch.no_grad(): if args.outlier_model == \"VAE\":", "f_vae(x_clean) # error repair, on dirty cell positions only error_repair_dc,", "vae_loss.backward() train_total_loss_seq_vae += vae_loss.item() train_loss_seq_vae += vae_loss.item() train_nll_seq_vae += vae_nll.item()", "'vae' type inference p_params_xd, q_params_xd, q_samples_xd = model(data_dirty) if not", "args.inference_type == \"seqvae\": ret_seq = {'train_loss_seq': train_loss_seq_vae/dataset_len, 'train_nll_seq': train_nll_seq_vae/dataset_len, 'train_z_kld_seq':", "= p_params_final, q_params_final, q_samples_final else: p_params_metric, q_params_metric, q_samples_metric = p_params,", "= dict_slice(p_params_xd, dirty_row_pos) q_params_xd_sliced = dict() if args.outlier_model == 'RVAE':", "#!/usr/bin/env python3 import torch from torch import optim import torch.nn.functional", "q_params_final, q_samples_final = seq_param_pack losses_seq_vae = {'eval_loss_seq': seq_final_loss.item()/eval_data_len, 'eval_nll_seq': seq_final_nll.item()/eval_data_len,", "or cross-entropy if isinstance(mask_err, torch.Tensor): pi_mtx = pi_score_mat pi_mtx_true =", "args, logit_ret=True) params_xc_in = (p_params_xc, q_params_xc, q_samples_xc) if args.seqvae_two_stage: _,", "'train_nll_seq': train_nll_seq_vae/dataset_len, 'train_z_kld_seq': train_z_kld_seq_vae/dataset_len,'train_w_kld_seq': train_w_kld_seq_vae/dataset_len, 'train_total_loss_seq':train_total_loss_seq_vae/dataset_len} ret = {**ret, **ret_seq}", "= seq_loss_pack p_params_final, q_params_final, q_samples_final = seq_param_pack losses_seq_vae = {'eval_loss_seq':", "model, torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _,", "device=data_clean.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, epoch_id=epoch) else: _, _, (p_params_xc,", "loss_per_iter=True, epoch_id=epoch) else: _, _, (p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_one_stage(params_xc_in,", "= (p_params_xc, q_params_xc, q_samples_xc) if args.seqvae_two_stage: _, _, (p_params_xc, q_params_xc,", "import utils from .model_utils import get_pi_exact_vec, rnn_vae_forward_one_stage, rnn_vae_forward_two_stage def training_phase(model,", "= torch.tensor(0.0) optimizer.step() if batch_idx % args.log_interval == 0 and", "vae_w_kld.item()/len(data_input))) if args.inference_type == 'seqvae': print('\\n') print('\\n\\nAdditional Info:\\tTotal Seq Loss:", "{}'.format(ce_pi)) print('dirt pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).std())) print('clean pi", "train_z_kld_seq_vae += vae_z_kld.item() train_w_kld_seq_vae += vae_w_kld.item() seq_total_loss = torch.tensor(0.0) seq_final_loss", "q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'], dirty_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, dirty_row_pos) vae_loss_dc, vae_nll_dc,", "error_lb_dc.item(), 'mse_upper_bd_dirtycells': error_up_dc.item() , 'mse_repair_dirtycells': error_repair_dc.item(), 'mse_repair_cleancells': error_repair_cc.item(), 'errors_per_feature': [error_lb_dc_per_feat,", "dataset_obj, args, epoch, clean_comp_show=False, data_eval_clean=False, logit_pi_prev=torch.tensor([]), w_conv=False, mask_err=None): # if", "POS):{}\".format(mode, error_repair_dc)) # error upper bound, on dirty cell positions", "(predict. posterior approx) under dirty data dict_slice = lambda dict_op,", "number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) else: seq_loss_pack, _, seq_param_pack =", "'eval_nll_final_clean_cc':vae_nll_cc.item()/n_clean_rows, 'eval_z_kld_final_clean_cc': vae_z_kld_cc.item()/n_clean_rows, 'eval_w_kld_final_clean_cc':vae_w_kld_cc.item()/n_clean_rows, 'eval_loss_final_clean_all': (vae_loss_cc+vae_loss_dc).item()/eval_data_len, 'eval_nll_final_clean_all':(vae_nll_cc+vae_nll_dc).item()/eval_data_len, 'eval_z_kld_final_clean_all': (vae_z_kld_cc+vae_z_kld_dc).item()/eval_data_len, 'eval_w_kld_final_clean_all':(vae_w_kld_cc+vae_w_kld_dc).item()/eval_data_len,", "pi_score_mat = -10 converg_norm_w = -10 else: if clean_comp_show: loss_clean,", "args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xd, q_params_xd, args, logit_ret=True) # get pi", "# Get NLL (predict. posterior approx) under dirty data dict_slice", "from torch import optim import torch.nn.functional as F import argparse", "torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: # standard 'vae'", "data_dirty.shape[0] losses = {'eval_loss_final_clean_dc': vae_loss_dc.item()/n_dirty_rows, 'eval_nll_final_clean_dc':vae_nll_dc.item()/n_dirty_rows, 'eval_z_kld_final_clean_dc': vae_z_kld_dc.item()/n_dirty_rows, 'eval_w_kld_final_clean_dc':vae_w_kld_dc.item()/n_dirty_rows, 'eval_loss_final_clean_cc':", "n_dirty_rows = dirty_row_pos.sum().item() p_params_xd_sliced = dict_slice(p_params_xd, dirty_row_pos) q_params_xd_sliced = dict()", "x_truth - f_vae(x_dirty) print(\"\\n\\n {} REPAIR ERROR (DIRTY POS):{}\".format(mode, error_repair_dc))", "- f_vae(x_clean) # error repair, on dirty cell positions only", "in enumerate(train_loader): data_input = unpack[0] if args.cuda_on: data_input = data_input.cuda()", "optimizer, train_loader, args, epoch, mute=True): model.train() train_loss_vae, train_nll_vae, train_z_kld_vae, train_w_kld_vae", "outlier score pi_score_mat = torch.sigmoid(q_params_metric['w']['logit_pi']).clamp(1e-6, 1-1e-6) # -log p(x|z, ...)", "args.outlier_model == \"VAE\": # VAE models only (no w's or", "Loss: {:.3f}\\tFinal Sep NLL: {:.3f}\\tFinal Sep KLD_Z: {:.3f}\\tFinal Sep KLD_W:", "dict_slice(q_params_xd['z'], dirty_row_pos) q_samples_xd_sliced = dict_slice(q_samples_xd, dirty_row_pos) vae_loss_dc, vae_nll_dc, vae_z_kld_dc, vae_w_kld_dc", "pi median: {} std: {}'.format(torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).median(), torch.sigmoid(q_params_metric['w']['logit_pi'][mask_err]).std())) print('clean pi median: {}", "loss_clean, nll_clean, z_kld_clean, w_kld_clean = model.loss_function(data_eval, p_params_metric, q_params_metric, q_samples_metric, clean_comp_only=True,", "if not args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xd, q_params_xd, args, logit_ret=True) #", "used after # error (MSE) lower bound, on dirty cell", "q_samples_xd_sliced = dict_slice(q_samples_xd, dirty_row_pos) vae_loss_dc, vae_nll_dc, vae_z_kld_dc, vae_w_kld_dc = model.loss_function(data_clean[dirty_row_pos,:],", "mute=True): model.train() train_loss_vae, train_nll_vae, train_z_kld_vae, train_w_kld_vae = 4*[0] train_loss_seq, train_nll_seq,", "dirty cell positions only error_lb_dc, error_lb_dc_per_feat = utils.error_computation(model, data_clean, p_params_xc['x'],", "= model.loss_function(data_input, p_params, q_params, q_samples) train_loss_vae += vae_loss.item() train_nll_vae +=", "= torch.tensor(0.0) seq_final_nll = torch.tensor(0.0) seq_final_z_kld = torch.tensor(0.0) seq_final_w_kld =", "optimizer.step() if batch_idx % args.log_interval == 0 and not mute:", "if value.shape[0]==data_dirty.shape[0] else value) for key, value in dict_op.items()} dirty_row_pos", "only error_repair_dc, error_repair_dc_per_feat = utils.error_computation(model, data_clean, p_params_xd['x'], mask) # x_truth", "if args.inference_type == \"seqvae\": ret_seq = {'train_loss_seq': train_loss_seq_vae/dataset_len, 'train_nll_seq': train_nll_seq_vae/dataset_len,", "#Getting scores and clean component if neededin_aux_samples with torch.no_grad(): if", "args, mask, mode, epoch): model.eval() # model params with input:", "{:.3f}\\tVAE NLL: {:.3f}\\tVAE KLD_Z: {:.3f}\\tVAE KLD_W: {:.3f}'.format( epoch, batch_idx *", "only error_up_dc, error_up_dc_per_feat = utils.error_computation(model, data_clean, data_dirty, mask, x_input_size=True) #", "x_input_size=True) # x_truth - x_dirty # error on clean cell", "not args.AVI: get_pi_exact_vec(model, data_input, p_params, q_params, args, logit_ret=True) # get", "= dict_slice(q_samples_xd, clean_row_pos) vae_loss_cc, vae_nll_cc, vae_z_kld_cc, vae_w_kld_cc = model.loss_function(data_clean[clean_row_pos,:], p_params_xd_sliced,", "bprops params_in = (p_params, q_params, q_samples) seq_loss_pack, _, _ =", "losses, metrics def repair_phase(model, data_dirty, data_clean, dataset_obj, args, mask, mode,", "vae_nll_dc, vae_z_kld_dc, vae_w_kld_dc = model.loss_function(data_clean[dirty_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True)", "if args.outlier_model == \"VAE\": # VAE models only (no w's", "args.inference_type == 'seqvae': if args.seqvae_bprop: # NOTE: rolls out iterations", "torch.tensor(0.0, device=data_clean.device), args, number_steps=args.seqvae_steps, loss_per_iter=True, epoch_id=epoch) else: # 'vae' type", "import torch.nn.functional as F import argparse from sklearn.metrics import mean_squared_error", "'vae': vae_loss.backward() elif args.inference_type == 'seqvae': if args.seqvae_bprop: # NOTE:", "of weights (pi's) if w_conv: if logit_pi_prev.nelement() == 0: logit_pi_prev", "vae_nll_cc, vae_z_kld_cc, vae_w_kld_cc = model.loss_function(data_clean[clean_row_pos,:], p_params_xd_sliced, q_params_xd_sliced, q_samples_xd_sliced, clean_comp_only=True, data_eval_clean=True)", "convergence of weights (pi's) if w_conv: if logit_pi_prev.nelement() == 0:", "{:.3f}\\n'.format( seq_total_loss.item()/len(data_input), seq_final_loss.item()/len(data_input), seq_final_nll.item()/len(data_input), seq_final_z_kld.item()/len(data_input), seq_final_w_kld.item()/len(data_input))) dataset_len = float(len(train_loader.dataset)) ret", "model, vae_loss, args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) else: seq_loss_pack,", "rnn_vae_forward_one_stage(params_in, data_eval, model, vae_loss, args, number_steps=args.seqvae_steps, loss_per_iter=True, mask_err=mask_err, epoch_id=epoch) seq_total_loss,", "repair_phase(model, data_dirty, data_clean, dataset_obj, args, mask, mode, epoch): model.eval() #", "args.AVI: get_pi_exact_vec(model, data_dirty, p_params_xd, q_params_xd, args, logit_ret=True) params_xd_in = (p_params_xd,", "cell positions only error_up_dc, error_up_dc_per_feat = utils.error_computation(model, data_clean, data_dirty, mask,", "_, (p_params_xc, q_params_xc, q_samples_xc) = rnn_vae_forward_one_stage(params_xc_in, data_clean, model, torch.tensor(0.0, device=data_clean.device),", "q_samples_xd) = rnn_vae_forward_two_stage(params_xd_in, data_dirty, model, torch.tensor(0.0, device=data_dirty.device), args, number_steps=args.seqvae_steps, number_steps_second_stage=args.steps_2stage,", "converg_norm_w} return losses, metrics def repair_phase(model, data_dirty, data_clean, dataset_obj, args,", "seq_total_loss.item()/eval_data_len} losses = {**losses, **losses_seq_vae} if args.inference_type == 'seqvae': p_params_metric,", "...) nll_score_mat = utils.generate_score_outlier_matrix(p_params_metric, data_eval, dataset_obj) pi_score_mat = -10 converg_norm_w", "args.outlier_model == 'RVAE': q_params_xd_sliced['w'] = dict_slice(q_params_xd['w'], clean_row_pos) q_params_xd_sliced['z'] = dict_slice(q_params_xd['z'],", "eval_data_len = data_dirty.shape[0] losses = {'eval_loss_final_clean_dc': vae_loss_dc.item()/n_dirty_rows, 'eval_nll_final_clean_dc':vae_nll_dc.item()/n_dirty_rows, 'eval_z_kld_final_clean_dc': vae_z_kld_dc.item()/n_dirty_rows,", "= seq_loss_pack train_total_loss_seq_vae += seq_total_loss.item() train_loss_seq_vae += seq_final_loss.item() train_nll_seq_vae +=", "logit_pi_prev).norm().item() logit_pi_prev = q_params_metric['w']['logit_pi'].clone().detach() else: converg_norm_w = -10 # insert", "converg_norm_w = (q_params_metric['w']['logit_pi'] - logit_pi_prev).norm().item() logit_pi_prev = q_params_metric['w']['logit_pi'].clone().detach() else: converg_norm_w", "args.inference_type == 'seqvae': p_params_metric, q_params_metric, q_samples_metric = p_params_final, q_params_final, q_samples_final", "== 'seqvae': p_params_xd, q_params_xd, q_samples_xd = model(data_dirty) if not args.AVI:", "= data_dirty.shape[0] losses = {'eval_loss_final_clean_dc': vae_loss_dc.item()/n_dirty_rows, 'eval_nll_final_clean_dc':vae_nll_dc.item()/n_dirty_rows, 'eval_z_kld_final_clean_dc': vae_z_kld_dc.item()/n_dirty_rows, 'eval_w_kld_final_clean_dc':vae_w_kld_dc.item()/n_dirty_rows,", "(vae_loss_cc+vae_loss_dc).item()/eval_data_len, 'eval_nll_final_clean_all':(vae_nll_cc+vae_nll_dc).item()/eval_data_len, 'eval_z_kld_final_clean_all': (vae_z_kld_cc+vae_z_kld_dc).item()/eval_data_len, 'eval_w_kld_final_clean_all':(vae_w_kld_cc+vae_w_kld_dc).item()/eval_data_len, 'mse_lower_bd_dirtycells': error_lb_dc.item(), 'mse_upper_bd_dirtycells': error_up_dc.item() ,", "args.cuda_on: # model.cpu() if type(mask_err) != type(None): mask_err = mask_err.bool()", "= (p_params, q_params, q_samples) seq_loss_pack, _, _ = rnn_vae_forward_one_stage(params_in, data_input," ]
[ "utf-8 -*- from setuptools import setup, find_packages setup( name='bert4keras', version='0.8.4',", "long_description='bert4keras: https://github.com/bojone/bert4keras', license='Apache License 2.0', url='https://github.com/bojone/bert4keras', author='bojone', author_email='<EMAIL>', install_requires=['keras<=2.3.1'], packages=find_packages()", "description='an elegant bert4keras', long_description='bert4keras: https://github.com/bojone/bert4keras', license='Apache License 2.0', url='https://github.com/bojone/bert4keras', author='bojone',", "#! -*- coding: utf-8 -*- from setuptools import setup, find_packages", "setuptools import setup, find_packages setup( name='bert4keras', version='0.8.4', description='an elegant bert4keras',", "from setuptools import setup, find_packages setup( name='bert4keras', version='0.8.4', description='an elegant", "bert4keras', long_description='bert4keras: https://github.com/bojone/bert4keras', license='Apache License 2.0', url='https://github.com/bojone/bert4keras', author='bojone', author_email='<EMAIL>', install_requires=['keras<=2.3.1'],", "-*- coding: utf-8 -*- from setuptools import setup, find_packages setup(", "setup( name='bert4keras', version='0.8.4', description='an elegant bert4keras', long_description='bert4keras: https://github.com/bojone/bert4keras', license='Apache License", "setup, find_packages setup( name='bert4keras', version='0.8.4', description='an elegant bert4keras', long_description='bert4keras: https://github.com/bojone/bert4keras',", "elegant bert4keras', long_description='bert4keras: https://github.com/bojone/bert4keras', license='Apache License 2.0', url='https://github.com/bojone/bert4keras', author='bojone', author_email='<EMAIL>',", "<gh_stars>1-10 #! -*- coding: utf-8 -*- from setuptools import setup,", "version='0.8.4', description='an elegant bert4keras', long_description='bert4keras: https://github.com/bojone/bert4keras', license='Apache License 2.0', url='https://github.com/bojone/bert4keras',", "https://github.com/bojone/bert4keras', license='Apache License 2.0', url='https://github.com/bojone/bert4keras', author='bojone', author_email='<EMAIL>', install_requires=['keras<=2.3.1'], packages=find_packages() )", "-*- from setuptools import setup, find_packages setup( name='bert4keras', version='0.8.4', description='an", "name='bert4keras', version='0.8.4', description='an elegant bert4keras', long_description='bert4keras: https://github.com/bojone/bert4keras', license='Apache License 2.0',", "import setup, find_packages setup( name='bert4keras', version='0.8.4', description='an elegant bert4keras', long_description='bert4keras:", "find_packages setup( name='bert4keras', version='0.8.4', description='an elegant bert4keras', long_description='bert4keras: https://github.com/bojone/bert4keras', license='Apache", "coding: utf-8 -*- from setuptools import setup, find_packages setup( name='bert4keras'," ]
[ "= io.StringIO() # sortby = 'cumulative' # ps = pstats.Stats(pr,", "* # pr = cProfile.Profile() # pr.enable() def out(p): for", "p.detuctAll() p.backtrackLoop() p.saveOtput() # pr.disable() # s = io.StringIO() #", "pr.disable() # s = io.StringIO() # sortby = 'cumulative' #", "s = io.StringIO() # sortby = 'cumulative' # ps =", "p.perms[i]]) if __name__ == '__main__': p = Picture() p.genPerms() p.detuctAll()", "out(p): for i in range(2): print([len(x) for x in p.perms[i]])", "Picture() p.genPerms() p.detuctAll() p.backtrackLoop() p.saveOtput() # pr.disable() # s =", "io from picture import * # pr = cProfile.Profile() #", "i in range(2): print([len(x) for x in p.perms[i]]) if __name__", "picture import * # pr = cProfile.Profile() # pr.enable() def", "import io from picture import * # pr = cProfile.Profile()", "from picture import * # pr = cProfile.Profile() # pr.enable()", "# sortby = 'cumulative' # ps = pstats.Stats(pr, stream=s).sort_stats(sortby) #", "sortby = 'cumulative' # ps = pstats.Stats(pr, stream=s).sort_stats(sortby) # ps.print_stats()", "'cumulative' # ps = pstats.Stats(pr, stream=s).sort_stats(sortby) # ps.print_stats() # print(s.getvalue())", "p.genPerms() p.detuctAll() p.backtrackLoop() p.saveOtput() # pr.disable() # s = io.StringIO()", "# s = io.StringIO() # sortby = 'cumulative' # ps", "cProfile.Profile() # pr.enable() def out(p): for i in range(2): print([len(x)", "# pr.enable() def out(p): for i in range(2): print([len(x) for", "import cProfile # import pstats # import io from picture", "<reponame>Magikis/Uniwersity # import cProfile # import pstats # import io", "# pr = cProfile.Profile() # pr.enable() def out(p): for i", "pr = cProfile.Profile() # pr.enable() def out(p): for i in", "def out(p): for i in range(2): print([len(x) for x in", "range(2): print([len(x) for x in p.perms[i]]) if __name__ == '__main__':", "print([len(x) for x in p.perms[i]]) if __name__ == '__main__': p", "p = Picture() p.genPerms() p.detuctAll() p.backtrackLoop() p.saveOtput() # pr.disable() #", "for i in range(2): print([len(x) for x in p.perms[i]]) if", "= 'cumulative' # ps = pstats.Stats(pr, stream=s).sort_stats(sortby) # ps.print_stats() #", "# import io from picture import * # pr =", "'__main__': p = Picture() p.genPerms() p.detuctAll() p.backtrackLoop() p.saveOtput() # pr.disable()", "import * # pr = cProfile.Profile() # pr.enable() def out(p):", "in range(2): print([len(x) for x in p.perms[i]]) if __name__ ==", "for x in p.perms[i]]) if __name__ == '__main__': p =", "== '__main__': p = Picture() p.genPerms() p.detuctAll() p.backtrackLoop() p.saveOtput() #", "x in p.perms[i]]) if __name__ == '__main__': p = Picture()", "cProfile # import pstats # import io from picture import", "# import pstats # import io from picture import *", "= cProfile.Profile() # pr.enable() def out(p): for i in range(2):", "__name__ == '__main__': p = Picture() p.genPerms() p.detuctAll() p.backtrackLoop() p.saveOtput()", "in p.perms[i]]) if __name__ == '__main__': p = Picture() p.genPerms()", "# import cProfile # import pstats # import io from", "pr.enable() def out(p): for i in range(2): print([len(x) for x", "pstats # import io from picture import * # pr", "import pstats # import io from picture import * #", "# pr.disable() # s = io.StringIO() # sortby = 'cumulative'", "= Picture() p.genPerms() p.detuctAll() p.backtrackLoop() p.saveOtput() # pr.disable() # s", "io.StringIO() # sortby = 'cumulative' # ps = pstats.Stats(pr, stream=s).sort_stats(sortby)", "if __name__ == '__main__': p = Picture() p.genPerms() p.detuctAll() p.backtrackLoop()", "p.saveOtput() # pr.disable() # s = io.StringIO() # sortby =", "p.backtrackLoop() p.saveOtput() # pr.disable() # s = io.StringIO() # sortby" ]
[ "120 # methods def generate_examples(bench_id, seed): command_line_args = [ \"dotnet\",", "print(f\"# ^^^^^^^^ Done: {done_result.returncode} ({bench_id}, {seed}) ^^^^^^^^\") except subprocess.TimeoutExpired: print('#", "TARGET_FULLDIR = abs_join(SCRIPT_DIR, TARGET_RELDIR) MAX_SAMPLE_SIZE = 2000 EXAMPLE_RELDIR = \"./strprose/example_files\"", "{seed}) --------\") done_result = subprocess.run(command_line_args, timeout=TIME_OUT) print(f\"# ^^^^^^^^ Done: {done_result.returncode}", "def generate_examples(bench_id, seed): command_line_args = [ \"dotnet\", TOOL_FULLPATH, \"--samplegen\", TARGET_FULLDIR,", "print('# Error: subprocess TIMEOUT !!!') if __name__ == \"__main__\": for", "\"__main__\": for bench_id in SEED_INFO[\"bench_seeds\"]: for seed in SEED_INFO[\"bench_seeds\"][bench_id]: generate_examples(bench_id,", "os.path.abspath(os.path.dirname(__file__)) SEED_RELPATH = \"./strprose/example_files/_seeds.json\" SEED_FULLPATH = abs_join(SCRIPT_DIR, SEED_RELPATH) SEED_INFO =", "subprocess.TimeoutExpired: print('# Error: subprocess TIMEOUT !!!') if __name__ == \"__main__\":", "TIME_OUT = 120 # methods def generate_examples(bench_id, seed): command_line_args =", "= json.load(f) TOOL_RELPATH = \"../StrPROSE-synthesizer/StrPROSE/bin/Debug/netcoreapp3.1/StrPROSE.dll\" TOOL_FULLPATH = abs_join(SCRIPT_DIR, TOOL_RELPATH) TARGET_RELDIR", "# constants SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) SEED_RELPATH = \"./strprose/example_files/_seeds.json\" SEED_FULLPATH =", "= \"./strprose/targets\" TARGET_FULLDIR = abs_join(SCRIPT_DIR, TARGET_RELDIR) MAX_SAMPLE_SIZE = 2000 EXAMPLE_RELDIR", "open(SEED_FULLPATH, 'r') as f: SEED_INFO = json.load(f) TOOL_RELPATH = \"../StrPROSE-synthesizer/StrPROSE/bin/Debug/netcoreapp3.1/StrPROSE.dll\"", "'r') as f: SEED_INFO = json.load(f) TOOL_RELPATH = \"../StrPROSE-synthesizer/StrPROSE/bin/Debug/netcoreapp3.1/StrPROSE.dll\" TOOL_FULLPATH", "SEED_FULLPATH = abs_join(SCRIPT_DIR, SEED_RELPATH) SEED_INFO = None with open(SEED_FULLPATH, 'r')", "json.load(f) TOOL_RELPATH = \"../StrPROSE-synthesizer/StrPROSE/bin/Debug/netcoreapp3.1/StrPROSE.dll\" TOOL_FULLPATH = abs_join(SCRIPT_DIR, TOOL_RELPATH) TARGET_RELDIR =", "subprocess TIMEOUT !!!') if __name__ == \"__main__\": for bench_id in", "== \"__main__\": for bench_id in SEED_INFO[\"bench_seeds\"]: for seed in SEED_INFO[\"bench_seeds\"][bench_id]:", "SEED_INFO = json.load(f) TOOL_RELPATH = \"../StrPROSE-synthesizer/StrPROSE/bin/Debug/netcoreapp3.1/StrPROSE.dll\" TOOL_FULLPATH = abs_join(SCRIPT_DIR, TOOL_RELPATH)", "os import json import subprocess abs_join = lambda p1, p2", "TOOL_RELPATH) TARGET_RELDIR = \"./strprose/targets\" TARGET_FULLDIR = abs_join(SCRIPT_DIR, TARGET_RELDIR) MAX_SAMPLE_SIZE =", "= abs_join(SCRIPT_DIR, EXAMPLE_RELDIR) TIME_OUT = 120 # methods def generate_examples(bench_id,", "EXAMPLE_RELDIR) TIME_OUT = 120 # methods def generate_examples(bench_id, seed): command_line_args", "[ \"dotnet\", TOOL_FULLPATH, \"--samplegen\", TARGET_FULLDIR, str(bench_id), str(seed), str(MAX_SAMPLE_SIZE), EXAMPLE_FULLDIR ]", "try: print(f\"# -------- Start Process ({bench_id}, {seed}) --------\") done_result =", "methods def generate_examples(bench_id, seed): command_line_args = [ \"dotnet\", TOOL_FULLPATH, \"--samplegen\",", "TIMEOUT !!!') if __name__ == \"__main__\": for bench_id in SEED_INFO[\"bench_seeds\"]:", "Process ({bench_id}, {seed}) --------\") done_result = subprocess.run(command_line_args, timeout=TIME_OUT) print(f\"# ^^^^^^^^", "!!!') if __name__ == \"__main__\": for bench_id in SEED_INFO[\"bench_seeds\"]: for", "abs_join = lambda p1, p2 : os.path.abspath(os.path.join(p1, p2)) # constants", "f: SEED_INFO = json.load(f) TOOL_RELPATH = \"../StrPROSE-synthesizer/StrPROSE/bin/Debug/netcoreapp3.1/StrPROSE.dll\" TOOL_FULLPATH = abs_join(SCRIPT_DIR,", "command_line_args = [ \"dotnet\", TOOL_FULLPATH, \"--samplegen\", TARGET_FULLDIR, str(bench_id), str(seed), str(MAX_SAMPLE_SIZE),", "= \"./strprose/example_files/_seeds.json\" SEED_FULLPATH = abs_join(SCRIPT_DIR, SEED_RELPATH) SEED_INFO = None with", "\"--samplegen\", TARGET_FULLDIR, str(bench_id), str(seed), str(MAX_SAMPLE_SIZE), EXAMPLE_FULLDIR ] try: print(f\"# --------", "with open(SEED_FULLPATH, 'r') as f: SEED_INFO = json.load(f) TOOL_RELPATH =", "= [ \"dotnet\", TOOL_FULLPATH, \"--samplegen\", TARGET_FULLDIR, str(bench_id), str(seed), str(MAX_SAMPLE_SIZE), EXAMPLE_FULLDIR", "TOOL_RELPATH = \"../StrPROSE-synthesizer/StrPROSE/bin/Debug/netcoreapp3.1/StrPROSE.dll\" TOOL_FULLPATH = abs_join(SCRIPT_DIR, TOOL_RELPATH) TARGET_RELDIR = \"./strprose/targets\"", "import subprocess abs_join = lambda p1, p2 : os.path.abspath(os.path.join(p1, p2))", "str(bench_id), str(seed), str(MAX_SAMPLE_SIZE), EXAMPLE_FULLDIR ] try: print(f\"# -------- Start Process", "= 120 # methods def generate_examples(bench_id, seed): command_line_args = [", "\"./strprose/targets\" TARGET_FULLDIR = abs_join(SCRIPT_DIR, TARGET_RELDIR) MAX_SAMPLE_SIZE = 2000 EXAMPLE_RELDIR =", "^^^^^^^^ Done: {done_result.returncode} ({bench_id}, {seed}) ^^^^^^^^\") except subprocess.TimeoutExpired: print('# Error:", "= os.path.abspath(os.path.dirname(__file__)) SEED_RELPATH = \"./strprose/example_files/_seeds.json\" SEED_FULLPATH = abs_join(SCRIPT_DIR, SEED_RELPATH) SEED_INFO", "p2)) # constants SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) SEED_RELPATH = \"./strprose/example_files/_seeds.json\" SEED_FULLPATH", "= \"./strprose/example_files\" EXAMPLE_FULLDIR = abs_join(SCRIPT_DIR, EXAMPLE_RELDIR) TIME_OUT = 120 #", "EXAMPLE_RELDIR = \"./strprose/example_files\" EXAMPLE_FULLDIR = abs_join(SCRIPT_DIR, EXAMPLE_RELDIR) TIME_OUT = 120", "Done: {done_result.returncode} ({bench_id}, {seed}) ^^^^^^^^\") except subprocess.TimeoutExpired: print('# Error: subprocess", "= \"../StrPROSE-synthesizer/StrPROSE/bin/Debug/netcoreapp3.1/StrPROSE.dll\" TOOL_FULLPATH = abs_join(SCRIPT_DIR, TOOL_RELPATH) TARGET_RELDIR = \"./strprose/targets\" TARGET_FULLDIR", "generate_examples(bench_id, seed): command_line_args = [ \"dotnet\", TOOL_FULLPATH, \"--samplegen\", TARGET_FULLDIR, str(bench_id),", "as f: SEED_INFO = json.load(f) TOOL_RELPATH = \"../StrPROSE-synthesizer/StrPROSE/bin/Debug/netcoreapp3.1/StrPROSE.dll\" TOOL_FULLPATH =", "\"dotnet\", TOOL_FULLPATH, \"--samplegen\", TARGET_FULLDIR, str(bench_id), str(seed), str(MAX_SAMPLE_SIZE), EXAMPLE_FULLDIR ] try:", "({bench_id}, {seed}) --------\") done_result = subprocess.run(command_line_args, timeout=TIME_OUT) print(f\"# ^^^^^^^^ Done:", "subprocess.run(command_line_args, timeout=TIME_OUT) print(f\"# ^^^^^^^^ Done: {done_result.returncode} ({bench_id}, {seed}) ^^^^^^^^\") except", "{seed}) ^^^^^^^^\") except subprocess.TimeoutExpired: print('# Error: subprocess TIMEOUT !!!') if", "SEED_RELPATH = \"./strprose/example_files/_seeds.json\" SEED_FULLPATH = abs_join(SCRIPT_DIR, SEED_RELPATH) SEED_INFO = None", "json import subprocess abs_join = lambda p1, p2 : os.path.abspath(os.path.join(p1,", "= abs_join(SCRIPT_DIR, SEED_RELPATH) SEED_INFO = None with open(SEED_FULLPATH, 'r') as", "TOOL_FULLPATH = abs_join(SCRIPT_DIR, TOOL_RELPATH) TARGET_RELDIR = \"./strprose/targets\" TARGET_FULLDIR = abs_join(SCRIPT_DIR,", "None with open(SEED_FULLPATH, 'r') as f: SEED_INFO = json.load(f) TOOL_RELPATH", "\"./strprose/example_files\" EXAMPLE_FULLDIR = abs_join(SCRIPT_DIR, EXAMPLE_RELDIR) TIME_OUT = 120 # methods", "SEED_RELPATH) SEED_INFO = None with open(SEED_FULLPATH, 'r') as f: SEED_INFO", "abs_join(SCRIPT_DIR, TOOL_RELPATH) TARGET_RELDIR = \"./strprose/targets\" TARGET_FULLDIR = abs_join(SCRIPT_DIR, TARGET_RELDIR) MAX_SAMPLE_SIZE", "] try: print(f\"# -------- Start Process ({bench_id}, {seed}) --------\") done_result", "except subprocess.TimeoutExpired: print('# Error: subprocess TIMEOUT !!!') if __name__ ==", "seed): command_line_args = [ \"dotnet\", TOOL_FULLPATH, \"--samplegen\", TARGET_FULLDIR, str(bench_id), str(seed),", "import json import subprocess abs_join = lambda p1, p2 :", "MAX_SAMPLE_SIZE = 2000 EXAMPLE_RELDIR = \"./strprose/example_files\" EXAMPLE_FULLDIR = abs_join(SCRIPT_DIR, EXAMPLE_RELDIR)", "abs_join(SCRIPT_DIR, EXAMPLE_RELDIR) TIME_OUT = 120 # methods def generate_examples(bench_id, seed):", "p1, p2 : os.path.abspath(os.path.join(p1, p2)) # constants SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))", "= None with open(SEED_FULLPATH, 'r') as f: SEED_INFO = json.load(f)", "imports import os import json import subprocess abs_join = lambda", "({bench_id}, {seed}) ^^^^^^^^\") except subprocess.TimeoutExpired: print('# Error: subprocess TIMEOUT !!!')", "lambda p1, p2 : os.path.abspath(os.path.join(p1, p2)) # constants SCRIPT_DIR =", "print(f\"# -------- Start Process ({bench_id}, {seed}) --------\") done_result = subprocess.run(command_line_args,", "= subprocess.run(command_line_args, timeout=TIME_OUT) print(f\"# ^^^^^^^^ Done: {done_result.returncode} ({bench_id}, {seed}) ^^^^^^^^\")", "\"./strprose/example_files/_seeds.json\" SEED_FULLPATH = abs_join(SCRIPT_DIR, SEED_RELPATH) SEED_INFO = None with open(SEED_FULLPATH,", "{done_result.returncode} ({bench_id}, {seed}) ^^^^^^^^\") except subprocess.TimeoutExpired: print('# Error: subprocess TIMEOUT", "SEED_INFO = None with open(SEED_FULLPATH, 'r') as f: SEED_INFO =", "TOOL_FULLPATH, \"--samplegen\", TARGET_FULLDIR, str(bench_id), str(seed), str(MAX_SAMPLE_SIZE), EXAMPLE_FULLDIR ] try: print(f\"#", "if __name__ == \"__main__\": for bench_id in SEED_INFO[\"bench_seeds\"]: for seed", "2000 EXAMPLE_RELDIR = \"./strprose/example_files\" EXAMPLE_FULLDIR = abs_join(SCRIPT_DIR, EXAMPLE_RELDIR) TIME_OUT =", "timeout=TIME_OUT) print(f\"# ^^^^^^^^ Done: {done_result.returncode} ({bench_id}, {seed}) ^^^^^^^^\") except subprocess.TimeoutExpired:", "--------\") done_result = subprocess.run(command_line_args, timeout=TIME_OUT) print(f\"# ^^^^^^^^ Done: {done_result.returncode} ({bench_id},", "TARGET_FULLDIR, str(bench_id), str(seed), str(MAX_SAMPLE_SIZE), EXAMPLE_FULLDIR ] try: print(f\"# -------- Start", "subprocess abs_join = lambda p1, p2 : os.path.abspath(os.path.join(p1, p2)) #", "__name__ == \"__main__\": for bench_id in SEED_INFO[\"bench_seeds\"]: for seed in", "EXAMPLE_FULLDIR = abs_join(SCRIPT_DIR, EXAMPLE_RELDIR) TIME_OUT = 120 # methods def", "for bench_id in SEED_INFO[\"bench_seeds\"]: for seed in SEED_INFO[\"bench_seeds\"][bench_id]: generate_examples(bench_id, seed)", "abs_join(SCRIPT_DIR, SEED_RELPATH) SEED_INFO = None with open(SEED_FULLPATH, 'r') as f:", "str(seed), str(MAX_SAMPLE_SIZE), EXAMPLE_FULLDIR ] try: print(f\"# -------- Start Process ({bench_id},", "Error: subprocess TIMEOUT !!!') if __name__ == \"__main__\": for bench_id", "-------- Start Process ({bench_id}, {seed}) --------\") done_result = subprocess.run(command_line_args, timeout=TIME_OUT)", "p2 : os.path.abspath(os.path.join(p1, p2)) # constants SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) SEED_RELPATH", ": os.path.abspath(os.path.join(p1, p2)) # constants SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) SEED_RELPATH =", "= abs_join(SCRIPT_DIR, TOOL_RELPATH) TARGET_RELDIR = \"./strprose/targets\" TARGET_FULLDIR = abs_join(SCRIPT_DIR, TARGET_RELDIR)", "str(MAX_SAMPLE_SIZE), EXAMPLE_FULLDIR ] try: print(f\"# -------- Start Process ({bench_id}, {seed})", "= 2000 EXAMPLE_RELDIR = \"./strprose/example_files\" EXAMPLE_FULLDIR = abs_join(SCRIPT_DIR, EXAMPLE_RELDIR) TIME_OUT", "os.path.abspath(os.path.join(p1, p2)) # constants SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) SEED_RELPATH = \"./strprose/example_files/_seeds.json\"", "TARGET_RELDIR) MAX_SAMPLE_SIZE = 2000 EXAMPLE_RELDIR = \"./strprose/example_files\" EXAMPLE_FULLDIR = abs_join(SCRIPT_DIR,", "abs_join(SCRIPT_DIR, TARGET_RELDIR) MAX_SAMPLE_SIZE = 2000 EXAMPLE_RELDIR = \"./strprose/example_files\" EXAMPLE_FULLDIR =", "# imports import os import json import subprocess abs_join =", "= lambda p1, p2 : os.path.abspath(os.path.join(p1, p2)) # constants SCRIPT_DIR", "EXAMPLE_FULLDIR ] try: print(f\"# -------- Start Process ({bench_id}, {seed}) --------\")", "import os import json import subprocess abs_join = lambda p1,", "TARGET_RELDIR = \"./strprose/targets\" TARGET_FULLDIR = abs_join(SCRIPT_DIR, TARGET_RELDIR) MAX_SAMPLE_SIZE = 2000", "# methods def generate_examples(bench_id, seed): command_line_args = [ \"dotnet\", TOOL_FULLPATH,", "Start Process ({bench_id}, {seed}) --------\") done_result = subprocess.run(command_line_args, timeout=TIME_OUT) print(f\"#", "\"../StrPROSE-synthesizer/StrPROSE/bin/Debug/netcoreapp3.1/StrPROSE.dll\" TOOL_FULLPATH = abs_join(SCRIPT_DIR, TOOL_RELPATH) TARGET_RELDIR = \"./strprose/targets\" TARGET_FULLDIR =", "= abs_join(SCRIPT_DIR, TARGET_RELDIR) MAX_SAMPLE_SIZE = 2000 EXAMPLE_RELDIR = \"./strprose/example_files\" EXAMPLE_FULLDIR", "done_result = subprocess.run(command_line_args, timeout=TIME_OUT) print(f\"# ^^^^^^^^ Done: {done_result.returncode} ({bench_id}, {seed})", "^^^^^^^^\") except subprocess.TimeoutExpired: print('# Error: subprocess TIMEOUT !!!') if __name__", "constants SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) SEED_RELPATH = \"./strprose/example_files/_seeds.json\" SEED_FULLPATH = abs_join(SCRIPT_DIR,", "SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) SEED_RELPATH = \"./strprose/example_files/_seeds.json\" SEED_FULLPATH = abs_join(SCRIPT_DIR, SEED_RELPATH)" ]
[ "[(1,0,0), (0, sqrt(2)/2, sqrt(2)/2), (0, -sqrt(2)/2, sqrt(2)/2)] ) vs.append( [(sqrt(3)/2,", "(0, -sqrt(2)/2, sqrt(2)/2)] ) vs.append( [(sqrt(3)/2, 1/2, 0), (-1/2, sqrt(3)/2,", "0.00 C ATOM 1 CA THR B 6 0.000 0.000", "tx=0.05,ty=0.07,tz=0.09, vx=vx, vy=vy, vz=vz, n_models=1000) if (__name__ == \"__main__\"): t0", "sqrt(3)/2)] ) for pdb_str in [pdb_str_1, pdb_str_2, pdb_str_3, pdb_str_4]: for", "for pdb_str in [pdb_str_1, pdb_str_2, pdb_str_3, pdb_str_4]: for vs_ in", "sqrt(3)/2, 1/2), (0, -1/2, sqrt(3)/2)] ) for pdb_str in [pdb_str_1,", "vz=vz, n_models=1000) if (__name__ == \"__main__\"): t0 = time.time() exercise_03()", "mmtbx.tls import tools import math import time pdb_str_1 = \"\"\"", "3.000 0.000 1.00 0.00 C \"\"\" pdb_str_3 = \"\"\" CRYST1", "if (__name__ == \"__main__\"): t0 = time.time() exercise_03() print \"Time:", "3.000 1.00 0.00 C \"\"\" pdb_str_4 = \"\"\" CRYST1 10.000", "sqrt(2)/2), (0, -sqrt(2)/2, sqrt(2)/2)] ) vs.append( [(sqrt(3)/2, 1/2, 0), (-1/2,", "time pdb_str_1 = \"\"\" CRYST1 10.000 10.000 10.000 90.00 90.00", "0.000 1.00 0.00 C ATOM 1 CA THR B 6", "1 CA THR B 6 3.000 0.000 0.000 1.00 0.00", "B 6 0.000 3.000 0.000 1.00 0.00 C \"\"\" pdb_str_3", "division from mmtbx.tls import tools import math import time pdb_str_1", "import tools import math import time pdb_str_1 = \"\"\" CRYST1", "0.000 3.000 1.00 0.00 C \"\"\" pdb_str_4 = \"\"\" CRYST1", "pdb_str_4]: for vs_ in vs: vx,vy,vz = vs_ print vx,vy,vz", "vx,vy,vz = vs_ print vx,vy,vz tools.u_tls_vs_u_ens(pdb_str=pdb_str, tx=0.05,ty=0.07,tz=0.09, vx=vx, vy=vy, vz=vz,", "= [] vs.append( [(sqrt(2)/2, sqrt(2)/2, 0), (-sqrt(2)/2, sqrt(2)/2, 0), (0,0,1)]", ") for pdb_str in [pdb_str_1, pdb_str_2, pdb_str_3, pdb_str_4]: for vs_", "-sqrt(2)/2, sqrt(2)/2)] ) vs.append( [(sqrt(3)/2, 1/2, 0), (-1/2, sqrt(3)/2, 0),", "ATOM 1 CA THR B 6 1.000 2.000 3.000 1.00", "\"\"\" pdb_str_4 = \"\"\" CRYST1 10.000 10.000 10.000 90.00 90.00", "math.sqrt vs = [] vs.append( [(sqrt(2)/2, sqrt(2)/2, 0), (-sqrt(2)/2, sqrt(2)/2,", "= math.sqrt vs = [] vs.append( [(sqrt(2)/2, sqrt(2)/2, 0), (-sqrt(2)/2,", "0.000 1.00 0.00 C \"\"\" pdb_str_2 = \"\"\" CRYST1 10.000", "0.00 C \"\"\" def exercise_03(): sqrt = math.sqrt vs =", "tools import math import time pdb_str_1 = \"\"\" CRYST1 10.000", "B 6 0.000 0.000 3.000 1.00 0.00 C \"\"\" pdb_str_4", "exercise_03(): sqrt = math.sqrt vs = [] vs.append( [(sqrt(2)/2, sqrt(2)/2,", "0), (0,0,1)] ) vs.append( [(1,0,0), (0, sqrt(3)/2, 1/2), (0, -1/2,", "6 0.000 0.000 0.000 1.00 0.00 C ATOM 1 CA", "pdb_str_2, pdb_str_3, pdb_str_4]: for vs_ in vs: vx,vy,vz = vs_", "== \"__main__\"): t0 = time.time() exercise_03() print \"Time: %6.4f\"%(time.time()-t0) print", "A 6 0.000 0.000 0.000 1.00 0.00 C ATOM 1", "3.000 0.000 0.000 1.00 0.00 C \"\"\" pdb_str_2 = \"\"\"", "\"__main__\"): t0 = time.time() exercise_03() print \"Time: %6.4f\"%(time.time()-t0) print \"OK\"", "0.000 0.000 1.00 0.00 C \"\"\" pdb_str_2 = \"\"\" CRYST1", "0.00 C ATOM 1 CA THR B 6 3.000 0.000", "(-1/2, sqrt(3)/2, 0), (0,0,1)] ) vs.append( [(1,0,0), (0, sqrt(3)/2, 1/2),", "= \"\"\" CRYST1 10.000 10.000 10.000 90.00 90.00 90.00 P1", "10.000 10.000 10.000 90.00 90.00 90.00 P1 ATOM 1 CA", "sqrt(2)/2, sqrt(2)/2), (0, -sqrt(2)/2, sqrt(2)/2)] ) vs.append( [(sqrt(3)/2, 1/2, 0),", "90.00 90.00 P1 ATOM 1 CA THR A 6 0.000", "1.00 0.00 C \"\"\" pdb_str_2 = \"\"\" CRYST1 10.000 10.000", "0.00 C ATOM 1 CA THR B 6 0.000 3.000", "(0, sqrt(3)/2, 1/2), (0, -1/2, sqrt(3)/2)] ) for pdb_str in", "[(1,0,0), (0, sqrt(3)/2, 1/2), (0, -1/2, sqrt(3)/2)] ) for pdb_str", "CA THR B 6 3.000 0.000 0.000 1.00 0.00 C", "(0,0,1)] ) vs.append( [(1,0,0), (0, sqrt(3)/2, 1/2), (0, -1/2, sqrt(3)/2)]", "THR A 6 0.000 0.000 0.000 1.00 0.00 C ATOM", "6 3.000 0.000 0.000 1.00 0.00 C \"\"\" pdb_str_2 =", "0.00 C \"\"\" pdb_str_4 = \"\"\" CRYST1 10.000 10.000 10.000", "ATOM 1 CA THR A 6 0.000 0.000 0.000 1.00", "6 1.000 2.000 3.000 1.00 0.00 C \"\"\" def exercise_03():", "pdb_str_1 = \"\"\" CRYST1 10.000 10.000 10.000 90.00 90.00 90.00", "1.00 0.00 C \"\"\" def exercise_03(): sqrt = math.sqrt vs", "1.00 0.00 C \"\"\" pdb_str_4 = \"\"\" CRYST1 10.000 10.000", "sqrt(3)/2, 0), (0,0,1)] ) vs.append( [(1,0,0), (0, sqrt(3)/2, 1/2), (0,", "CRYST1 10.000 10.000 10.000 90.00 90.00 90.00 P1 ATOM 1", "sqrt = math.sqrt vs = [] vs.append( [(sqrt(2)/2, sqrt(2)/2, 0),", "C ATOM 1 CA THR B 6 3.000 0.000 0.000", "CA THR B 6 0.000 3.000 0.000 1.00 0.00 C", "ATOM 1 CA THR B 6 3.000 0.000 0.000 1.00", "vs.append( [(sqrt(3)/2, 1/2, 0), (-1/2, sqrt(3)/2, 0), (0,0,1)] ) vs.append(", "C \"\"\" pdb_str_2 = \"\"\" CRYST1 10.000 10.000 10.000 90.00", "C ATOM 1 CA THR B 6 1.000 2.000 3.000", "vs.append( [(1,0,0), (0, sqrt(2)/2, sqrt(2)/2), (0, -sqrt(2)/2, sqrt(2)/2)] ) vs.append(", "3.000 1.00 0.00 C \"\"\" def exercise_03(): sqrt = math.sqrt", "THR B 6 1.000 2.000 3.000 1.00 0.00 C \"\"\"", "1.000 2.000 3.000 1.00 0.00 C \"\"\" def exercise_03(): sqrt", "(0, sqrt(2)/2, sqrt(2)/2), (0, -sqrt(2)/2, sqrt(2)/2)] ) vs.append( [(sqrt(3)/2, 1/2,", "P1 ATOM 1 CA THR A 6 0.000 0.000 0.000", "import math import time pdb_str_1 = \"\"\" CRYST1 10.000 10.000", "1 CA THR B 6 0.000 3.000 0.000 1.00 0.00", "\"\"\" pdb_str_3 = \"\"\" CRYST1 10.000 10.000 10.000 90.00 90.00", "n_models=1000) if (__name__ == \"__main__\"): t0 = time.time() exercise_03() print", "C ATOM 1 CA THR B 6 0.000 0.000 3.000", "THR B 6 0.000 3.000 0.000 1.00 0.00 C \"\"\"", "-1/2, sqrt(3)/2)] ) for pdb_str in [pdb_str_1, pdb_str_2, pdb_str_3, pdb_str_4]:", "vs: vx,vy,vz = vs_ print vx,vy,vz tools.u_tls_vs_u_ens(pdb_str=pdb_str, tx=0.05,ty=0.07,tz=0.09, vx=vx, vy=vy,", "1.00 0.00 C ATOM 1 CA THR B 6 3.000", "2.000 3.000 1.00 0.00 C \"\"\" def exercise_03(): sqrt =", "0), (0,0,1)] ) vs.append( [(1,0,0), (0, sqrt(2)/2, sqrt(2)/2), (0, -sqrt(2)/2,", "for vs_ in vs: vx,vy,vz = vs_ print vx,vy,vz tools.u_tls_vs_u_ens(pdb_str=pdb_str,", "[pdb_str_1, pdb_str_2, pdb_str_3, pdb_str_4]: for vs_ in vs: vx,vy,vz =", "B 6 3.000 0.000 0.000 1.00 0.00 C \"\"\" pdb_str_2", "(-sqrt(2)/2, sqrt(2)/2, 0), (0,0,1)] ) vs.append( [(1,0,0), (0, sqrt(2)/2, sqrt(2)/2),", "__future__ import division from mmtbx.tls import tools import math import", "import division from mmtbx.tls import tools import math import time", "pdb_str_2 = \"\"\" CRYST1 10.000 10.000 10.000 90.00 90.00 90.00", "C ATOM 1 CA THR B 6 0.000 3.000 0.000", "print vx,vy,vz tools.u_tls_vs_u_ens(pdb_str=pdb_str, tx=0.05,ty=0.07,tz=0.09, vx=vx, vy=vy, vz=vz, n_models=1000) if (__name__", "ATOM 1 CA THR B 6 0.000 3.000 0.000 1.00", "sqrt(2)/2)] ) vs.append( [(sqrt(3)/2, 1/2, 0), (-1/2, sqrt(3)/2, 0), (0,0,1)]", "from __future__ import division from mmtbx.tls import tools import math", "THR B 6 0.000 0.000 3.000 1.00 0.00 C \"\"\"", "ATOM 1 CA THR B 6 0.000 0.000 3.000 1.00", "def exercise_03(): sqrt = math.sqrt vs = [] vs.append( [(sqrt(2)/2,", "1/2), (0, -1/2, sqrt(3)/2)] ) for pdb_str in [pdb_str_1, pdb_str_2,", "sqrt(2)/2, 0), (-sqrt(2)/2, sqrt(2)/2, 0), (0,0,1)] ) vs.append( [(1,0,0), (0,", "0.000 1.00 0.00 C \"\"\" pdb_str_3 = \"\"\" CRYST1 10.000", "10.000 90.00 90.00 90.00 P1 ATOM 1 CA THR A", "1/2, 0), (-1/2, sqrt(3)/2, 0), (0,0,1)] ) vs.append( [(1,0,0), (0,", "(__name__ == \"__main__\"): t0 = time.time() exercise_03() print \"Time: %6.4f\"%(time.time()-t0)", "pdb_str_4 = \"\"\" CRYST1 10.000 10.000 10.000 90.00 90.00 90.00", "1.00 0.00 C ATOM 1 CA THR B 6 1.000", "CA THR B 6 1.000 2.000 3.000 1.00 0.00 C", "0.000 3.000 0.000 1.00 0.00 C \"\"\" pdb_str_3 = \"\"\"", "pdb_str_3, pdb_str_4]: for vs_ in vs: vx,vy,vz = vs_ print", "1.00 0.00 C ATOM 1 CA THR B 6 0.000", "1 CA THR B 6 1.000 2.000 3.000 1.00 0.00", "pdb_str_3 = \"\"\" CRYST1 10.000 10.000 10.000 90.00 90.00 90.00", "0.000 0.000 0.000 1.00 0.00 C ATOM 1 CA THR", "6 0.000 3.000 0.000 1.00 0.00 C \"\"\" pdb_str_3 =", "0.000 0.000 1.00 0.00 C ATOM 1 CA THR B", "0.00 C ATOM 1 CA THR B 6 1.000 2.000", "C \"\"\" def exercise_03(): sqrt = math.sqrt vs = []", "1 CA THR A 6 0.000 0.000 0.000 1.00 0.00", "1 CA THR B 6 0.000 0.000 3.000 1.00 0.00", "0), (-1/2, sqrt(3)/2, 0), (0,0,1)] ) vs.append( [(1,0,0), (0, sqrt(3)/2,", "vs_ print vx,vy,vz tools.u_tls_vs_u_ens(pdb_str=pdb_str, tx=0.05,ty=0.07,tz=0.09, vx=vx, vy=vy, vz=vz, n_models=1000) if", "vx,vy,vz tools.u_tls_vs_u_ens(pdb_str=pdb_str, tx=0.05,ty=0.07,tz=0.09, vx=vx, vy=vy, vz=vz, n_models=1000) if (__name__ ==", "in vs: vx,vy,vz = vs_ print vx,vy,vz tools.u_tls_vs_u_ens(pdb_str=pdb_str, tx=0.05,ty=0.07,tz=0.09, vx=vx,", "CA THR A 6 0.000 0.000 0.000 1.00 0.00 C", "in [pdb_str_1, pdb_str_2, pdb_str_3, pdb_str_4]: for vs_ in vs: vx,vy,vz", "import time pdb_str_1 = \"\"\" CRYST1 10.000 10.000 10.000 90.00", "pdb_str in [pdb_str_1, pdb_str_2, pdb_str_3, pdb_str_4]: for vs_ in vs:", "CA THR B 6 0.000 0.000 3.000 1.00 0.00 C", "vs.append( [(1,0,0), (0, sqrt(3)/2, 1/2), (0, -1/2, sqrt(3)/2)] ) for", "0.00 C \"\"\" pdb_str_3 = \"\"\" CRYST1 10.000 10.000 10.000", "vx=vx, vy=vy, vz=vz, n_models=1000) if (__name__ == \"__main__\"): t0 =", "math import time pdb_str_1 = \"\"\" CRYST1 10.000 10.000 10.000", "(0, -1/2, sqrt(3)/2)] ) for pdb_str in [pdb_str_1, pdb_str_2, pdb_str_3,", "1.00 0.00 C \"\"\" pdb_str_3 = \"\"\" CRYST1 10.000 10.000", "90.00 P1 ATOM 1 CA THR A 6 0.000 0.000", "vy=vy, vz=vz, n_models=1000) if (__name__ == \"__main__\"): t0 = time.time()", ") vs.append( [(sqrt(3)/2, 1/2, 0), (-1/2, sqrt(3)/2, 0), (0,0,1)] )", "\"\"\" pdb_str_2 = \"\"\" CRYST1 10.000 10.000 10.000 90.00 90.00", "tools.u_tls_vs_u_ens(pdb_str=pdb_str, tx=0.05,ty=0.07,tz=0.09, vx=vx, vy=vy, vz=vz, n_models=1000) if (__name__ == \"__main__\"):", "[(sqrt(3)/2, 1/2, 0), (-1/2, sqrt(3)/2, 0), (0,0,1)] ) vs.append( [(1,0,0),", "6 0.000 0.000 3.000 1.00 0.00 C \"\"\" pdb_str_4 =", "10.000 10.000 90.00 90.00 90.00 P1 ATOM 1 CA THR", "0.00 C \"\"\" pdb_str_2 = \"\"\" CRYST1 10.000 10.000 10.000", ") vs.append( [(1,0,0), (0, sqrt(3)/2, 1/2), (0, -1/2, sqrt(3)/2)] )", "0), (-sqrt(2)/2, sqrt(2)/2, 0), (0,0,1)] ) vs.append( [(1,0,0), (0, sqrt(2)/2,", "\"\"\" def exercise_03(): sqrt = math.sqrt vs = [] vs.append(", "B 6 1.000 2.000 3.000 1.00 0.00 C \"\"\" def", "C \"\"\" pdb_str_3 = \"\"\" CRYST1 10.000 10.000 10.000 90.00", ") vs.append( [(1,0,0), (0, sqrt(2)/2, sqrt(2)/2), (0, -sqrt(2)/2, sqrt(2)/2)] )", "vs = [] vs.append( [(sqrt(2)/2, sqrt(2)/2, 0), (-sqrt(2)/2, sqrt(2)/2, 0),", "90.00 90.00 90.00 P1 ATOM 1 CA THR A 6", "\"\"\" CRYST1 10.000 10.000 10.000 90.00 90.00 90.00 P1 ATOM", "= vs_ print vx,vy,vz tools.u_tls_vs_u_ens(pdb_str=pdb_str, tx=0.05,ty=0.07,tz=0.09, vx=vx, vy=vy, vz=vz, n_models=1000)", "0.000 0.000 3.000 1.00 0.00 C \"\"\" pdb_str_4 = \"\"\"", "sqrt(2)/2, 0), (0,0,1)] ) vs.append( [(1,0,0), (0, sqrt(2)/2, sqrt(2)/2), (0,", "vs.append( [(sqrt(2)/2, sqrt(2)/2, 0), (-sqrt(2)/2, sqrt(2)/2, 0), (0,0,1)] ) vs.append(", "C \"\"\" pdb_str_4 = \"\"\" CRYST1 10.000 10.000 10.000 90.00", "vs_ in vs: vx,vy,vz = vs_ print vx,vy,vz tools.u_tls_vs_u_ens(pdb_str=pdb_str, tx=0.05,ty=0.07,tz=0.09,", "(0,0,1)] ) vs.append( [(1,0,0), (0, sqrt(2)/2, sqrt(2)/2), (0, -sqrt(2)/2, sqrt(2)/2)]", "[] vs.append( [(sqrt(2)/2, sqrt(2)/2, 0), (-sqrt(2)/2, sqrt(2)/2, 0), (0,0,1)] )", "from mmtbx.tls import tools import math import time pdb_str_1 =", "[(sqrt(2)/2, sqrt(2)/2, 0), (-sqrt(2)/2, sqrt(2)/2, 0), (0,0,1)] ) vs.append( [(1,0,0),", "THR B 6 3.000 0.000 0.000 1.00 0.00 C \"\"\"" ]
[ "import resolve def global_vars(request): return { 'GLOBAL_TWITTER_ACCOUNT': '@open_apprentice', 'ORGANIZATION_NAME': 'Open", "'/static/img/ellie/open-apprentice-logo-full.png', # relative URL with pre /, 'SITE_LOGO_URL': '/static/img/ellie/ellie-platform-logo.png', #", "resolve def global_vars(request): return { 'GLOBAL_TWITTER_ACCOUNT': '@open_apprentice', 'ORGANIZATION_NAME': 'Open Apprentice", "'https://openapprentice.org', 'ORGANIZATION_LOGO': '/static/img/ellie/open-apprentice-logo-full.png', # relative URL with pre /, 'SITE_LOGO_URL':", "global_vars(request): return { 'GLOBAL_TWITTER_ACCOUNT': '@open_apprentice', 'ORGANIZATION_NAME': 'Open Apprentice Foundation', 'ORGANIZATION_WEBSITE':", "'ORGANIZATION_LOGO': '/static/img/ellie/open-apprentice-logo-full.png', # relative URL with pre /, 'SITE_LOGO_URL': '/static/img/ellie/ellie-platform-logo.png',", "def global_vars(request): return { 'GLOBAL_TWITTER_ACCOUNT': '@open_apprentice', 'ORGANIZATION_NAME': 'Open Apprentice Foundation',", "with pre /, 'SITE_LOGO_URL': '/static/img/ellie/ellie-platform-logo.png', # relative URL with pre", "relative URL with pre /, 'SITE_LOGO_URL': '/static/img/ellie/ellie-platform-logo.png', # relative URL", "from django.urls import resolve def global_vars(request): return { 'GLOBAL_TWITTER_ACCOUNT': '@open_apprentice',", "# relative URL with pre /, 'SITE_LOGO_URL': '/static/img/ellie/ellie-platform-logo.png', # relative", "'SITE_LOGO_URL': '/static/img/ellie/ellie-platform-logo.png', # relative URL with pre / 'APPNAME': sys.modules[resolve(request.path_info).func.__module__].__package__,", "'GLOBAL_TWITTER_ACCOUNT': '@open_apprentice', 'ORGANIZATION_NAME': 'Open Apprentice Foundation', 'ORGANIZATION_WEBSITE': 'https://openapprentice.org', 'ORGANIZATION_LOGO': '/static/img/ellie/open-apprentice-logo-full.png',", "URL with pre /, 'SITE_LOGO_URL': '/static/img/ellie/ellie-platform-logo.png', # relative URL with", "Foundation', 'ORGANIZATION_WEBSITE': 'https://openapprentice.org', 'ORGANIZATION_LOGO': '/static/img/ellie/open-apprentice-logo-full.png', # relative URL with pre", "Apprentice Foundation', 'ORGANIZATION_WEBSITE': 'https://openapprentice.org', 'ORGANIZATION_LOGO': '/static/img/ellie/open-apprentice-logo-full.png', # relative URL with", "{ 'GLOBAL_TWITTER_ACCOUNT': '@open_apprentice', 'ORGANIZATION_NAME': 'Open Apprentice Foundation', 'ORGANIZATION_WEBSITE': 'https://openapprentice.org', 'ORGANIZATION_LOGO':", "django.urls import resolve def global_vars(request): return { 'GLOBAL_TWITTER_ACCOUNT': '@open_apprentice', 'ORGANIZATION_NAME':", "sys from django.urls import resolve def global_vars(request): return { 'GLOBAL_TWITTER_ACCOUNT':", "import sys from django.urls import resolve def global_vars(request): return {", "'ORGANIZATION_WEBSITE': 'https://openapprentice.org', 'ORGANIZATION_LOGO': '/static/img/ellie/open-apprentice-logo-full.png', # relative URL with pre /,", "'ORGANIZATION_NAME': 'Open Apprentice Foundation', 'ORGANIZATION_WEBSITE': 'https://openapprentice.org', 'ORGANIZATION_LOGO': '/static/img/ellie/open-apprentice-logo-full.png', # relative", "'@open_apprentice', 'ORGANIZATION_NAME': 'Open Apprentice Foundation', 'ORGANIZATION_WEBSITE': 'https://openapprentice.org', 'ORGANIZATION_LOGO': '/static/img/ellie/open-apprentice-logo-full.png', #", "/, 'SITE_LOGO_URL': '/static/img/ellie/ellie-platform-logo.png', # relative URL with pre / 'APPNAME':", "'Open Apprentice Foundation', 'ORGANIZATION_WEBSITE': 'https://openapprentice.org', 'ORGANIZATION_LOGO': '/static/img/ellie/open-apprentice-logo-full.png', # relative URL", "pre /, 'SITE_LOGO_URL': '/static/img/ellie/ellie-platform-logo.png', # relative URL with pre /", "'/static/img/ellie/ellie-platform-logo.png', # relative URL with pre / 'APPNAME': sys.modules[resolve(request.path_info).func.__module__].__package__, }", "return { 'GLOBAL_TWITTER_ACCOUNT': '@open_apprentice', 'ORGANIZATION_NAME': 'Open Apprentice Foundation', 'ORGANIZATION_WEBSITE': 'https://openapprentice.org'," ]
[ "\"coco2017\": cfg.TRAIN.DATASETS = ('coco_2014_train',) cfg.MODEL.NUM_CLASSES = 4 elif args.dataset ==", "Load checkpoint if args.load_ckpt: load_name = args.load_ckpt logging.info(\"loading checkpoint %s\",", "type=int) parser.add_argument( '--nw', dest='num_workers', help='Explicitly specify to overwrite number of", "scaled based # on batch_size instead of effective_batch_size old_base_lr =", "to be set properly at the start of training params", "default=None, type=float) # Epoch parser.add_argument( '--start_step', help='Starting step count for", "warmup_factor = cfg.SOLVER.WARM_UP_FACTOR elif method == 'linear': alpha = step", "args.num_classes is None: raise ValueError(\"Need number of classes in your", "in maskRCNN.named_modules(): if isinstance(module, nn.GroupNorm): gn_param_nameset.add(name+'.weight') gn_param_nameset.add(name+'.bias') gn_params = []", "checkpoint %s\", load_name) checkpoint = torch.load(load_name, map_location=lambda storage, loc: storage)", "args.batch_size is None: args.batch_size = original_batch_size cfg.NUM_GPUS = torch.cuda.device_count() assert", "lr = optimizer.param_groups[0]['lr'] assert lr == cfg.SOLVER.BASE_LR # Learning rate", "cfg_from_file(args.cfg_file) if args.set_cfgs is not None: cfg_from_list(args.set_cfgs) ### Adaptively adjust", "os.path.basename(args.cfg_file) if not args.no_save: if not os.path.exists(output_dir): os.makedirs(output_dir) blob =", "len(cfg.SOLVER.STEPS) and \\ step == cfg.SOLVER.STEPS[decay_steps_ind]: logger.info('Decay the learning on", "for steps_with_decay policy\"\"\" import argparse import os import sys import", "args.run_name = misc_utils.get_run_name() + '_step' output_dir = misc_utils.get_output_dir(args, args.run_name) args.cfg_filename", "{'cfg': yaml.dump(cfg), 'args': args} with open(os.path.join(output_dir, 'config_and_args.pkl'), 'wb') as f:", "args.lr_decay_gamma is not None: cfg.SOLVER.GAMMA = args.lr_decay_gamma assert_and_infer_cfg() timers =", "mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'], minibatch=True) ### Training Setups ### args.run_name =", "### Overwrite some solver settings from command line arguments if", "os.makedirs(ckpt_dir) save_name = os.path.join(ckpt_dir, 'model_step{}.pth'.format(step)) if isinstance(model, mynn.DataParallel): model =", "% (original_batch_size, effective_batch_size)) print(' NUM_GPUS: %d --> %d' % (original_num_gpus,", "logging.getLogger('roi_data.loader').setLevel(logging.INFO) # RuntimeError: received 0 items of ancdata. Issue: pytorch/pytorch#973", "args = parse_args() print('Called with args:') print(args) if not torch.cuda.is_available():", "are `accumulated`, so lr is scaled based # on batch_size", "cfg.TRAIN.IMS_PER_BATCH)) ### Adjust learning based on batch size change linearly", "args.dataset: {}\".format(args.dataset)) cfg_from_file(args.cfg_file) if args.set_cfgs is not None: cfg_from_list(args.set_cfgs) ###", "roidb entries'.format(roidb_size)) logger.info('Takes %.2f sec(s) to construct roidb', timers['roidb'].average_time) #", "dest='optimizer', help='Training optimizer.', default=None) parser.add_argument( '--lr', help='Base learning rate.', default=None,", "cfg.SOLVER.WARM_UP_METHOD if method == 'constant': warmup_factor = cfg.SOLVER.WARM_UP_FACTOR elif method", "= args.optimizer if args.lr is not None: cfg.SOLVER.BASE_LR = args.lr", "on step %d', step) lr_new = lr * cfg.SOLVER.GAMMA net_utils.update_learning_rate(optimizer,", "= args.num_workers print('Number of data loading threads: %d' % cfg.DATA_LOADER.NUM_THREADS)", "cfg.SOLVER.WEIGHT_DECAY if cfg.SOLVER.BIAS_WEIGHT_DECAY else 0}, {'params': gn_params, 'lr': 0, 'weight_decay':", "timers['roidb'].tic() roidb, ratio_list, ratio_index = combined_roidb_for_training( cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES) timers['roidb'].toc() roidb_size", "= Generalized_RCNN() if cfg.CUDA: maskRCNN.cuda() ### Optimizer ### gn_param_nameset =", "'step': step, 'train_size': train_size, 'batch_size': args.batch_size, 'model': model.state_dict(), 'optimizer': optimizer.state_dict()},", "(4096, rlimit[1])) def parse_args(): \"\"\"Parse input arguments\"\"\" parser = argparse.ArgumentParser(description='Train", "= [] nonbias_params = [] nonbias_param_names = [] nograd_param_names =", "lr_new) lr = optimizer.param_groups[0]['lr'] assert lr == lr_new elif step", "CUDA device', action='store_false') # Optimization # These options has the", "be set properly at the start of training params =", "blob = {'cfg': yaml.dump(cfg), 'args': args} with open(os.path.join(output_dir, 'config_and_args.pkl'), 'wb')", "in optimizer checkpoint's params_groups if needed # misc_utils.ensure_optimizer_ckpt_params_order(param_names, checkpoint) #", "train_size, maskRCNN, optimizer) # ---- Training ends ---- # Save", "= original_batch_size cfg.NUM_GPUS = torch.cuda.device_count() assert (args.batch_size % cfg.NUM_GPUS) ==", "# Warm up if step < cfg.SOLVER.WARM_UP_ITERS: method = cfg.SOLVER.WARM_UP_METHOD", "\"voc2012\": cfg.TRAIN.DATASETS = ('voc_2012_train',) cfg.MODEL.NUM_CLASSES = 21 elif args.dataset ==", "help='Set config keys. Key value sequence seperate by whitespace.' 'e.g.", "for key in input_data: if key != 'roidb': # roidb", "# There is a bug in optimizer.load_state_dict on Pytorch 0.3.1.", "Scale FPN rpn_proposals collect size (post_nms_topN) in `collect` function #", "key, value in maskRCNN.named_parameters(): if value.requires_grad: if 'bias' in key:", "original_num_gpus = cfg.NUM_GPUS if args.batch_size is None: args.batch_size = original_batch_size", "ckpt done.') stack_trace = traceback.format_exc() print(stack_trace) finally: if args.use_tfboard and", "(original_batch_size, effective_batch_size)) print(' NUM_GPUS: %d --> %d' % (original_num_gpus, cfg.NUM_GPUS))", "if checkpoint['train_size'] != train_size: print('train_size value: %d different from the", "the code.\") if args.cuda or cfg.NUM_GPUS > 0: cfg.CUDA =", "in `collect` function # of `collect_and_distribute_fpn_rpn_proposals.py` # # post_nms_topN =", "= misc_utils.get_output_dir(args, args.run_name) args.cfg_filename = os.path.basename(args.cfg_file) if not args.no_save: if", "size directly propotional to the change of IMS_PER_BATCH:\\n' ' cfg.FPN.RPN_COLLECT_SCALE:", "{}\\n' ' SOLVER.MAX_ITER: {} --> {}'.format(old_solver_steps, cfg.SOLVER.STEPS, old_max_iter, cfg.SOLVER.MAX_ITER)) #", "Issue: pytorch/pytorch#973 rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1])) def parse_args():", "cfg.TRAIN.IMS_PER_BATCH = args.batch_size // cfg.NUM_GPUS effective_batch_size = args.iter_size * args.batch_size", "(1 - alpha) + alpha else: raise KeyError('Unknown SOLVER.WARM_UP_METHOD: {}'.format(method))", "testing)') parser.add_argument( '--set', dest='set_cfgs', help='Set config keys. Key value sequence", "= list(map(Variable, input_data[key])) try: net_outputs = maskRCNN(**input_data) except: continue training_stats.UpdateIterStats(net_outputs,", "('coco_2014_train',) cfg.MODEL.NUM_CLASSES = 4 elif args.dataset == \"keypoints_coco2017\": cfg.TRAIN.DATASETS =", "main(): \"\"\"Main function\"\"\" args = parse_args() print('Called with args:') print(args)", "dataset = RoiDataLoader( roidb, cfg.MODEL.NUM_CLASSES, training=True) dataloader = torch.utils.data.DataLoader( dataset,", "in range(1, len(cfg.SOLVER.STEPS)): if cfg.SOLVER.STEPS[i] >= args.start_step: decay_steps_ind = i", "### timers['roidb'].tic() roidb, ratio_list, ratio_index = combined_roidb_for_training( cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES) timers['roidb'].toc()", "Save last checkpoint save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) except", "parser.add_argument( '--resume', help='resume to training on a checkpoint', action='store_true') parser.add_argument(", "= original_batch_size / effective_batch_size old_solver_steps = cfg.SOLVER.STEPS old_max_iter = cfg.SOLVER.MAX_ITER", "import load_detectron_weight from utils.logging import setup_logging from utils.timer import Timer", "cfg.MODEL.NUM_CLASSES = 4 elif args.dataset == \"keypoints_coco2017\": cfg.TRAIN.DATASETS = ('keypoints_coco_2017_train',)", "print(' effective_batch_size: %d --> %d' % (original_batch_size, effective_batch_size)) print(' NUM_GPUS:", "del dataiterator logger.info('Save ckpt on exception ...') save_ckpt(output_dir, args, step,", "line arguments if args.optimizer is not None: cfg.SOLVER.TYPE = args.optimizer", "misc_utils from core.config import cfg, cfg_from_file, cfg_from_list, assert_and_infer_cfg from datasets.roidb", "rpn_proposals collect size (post_nms_topN) in `collect` function # of `collect_and_distribute_fpn_rpn_proposals.py`", "assert_and_infer_cfg from datasets.roidb import combined_roidb_for_training from roi_data.loader import RoiDataLoader, MinibatchSampler,", "in your custom dataset', default=None, type=int) parser.add_argument( '--cfg', dest='cfg_file', required=True,", "means do not overwrite. parser.add_argument( '--bs', dest='batch_size', help='Explicitly specify to", "'--no_save', help='do not save anything', action='store_true') parser.add_argument( '--load_ckpt', help='checkpoint path", "index for decay steps decay_steps_ind = None for i in", "storage) net_utils.load_ckpt(maskRCNN, checkpoint['model']) if args.resume: args.start_step = checkpoint['step'] + 1", "of classes in your custom dataset to run!\") if args.dataset", "{}\".format(args.dataset)) cfg_from_file(args.cfg_file) if args.set_cfgs is not None: cfg_from_list(args.set_cfgs) ### Adaptively", "config keys. Key value sequence seperate by whitespace.' 'e.g. [key]", "device to run !\") if args.dataset == \"custom_dataset\" and args.num_classes", "rate.', default=None, type=float) # Epoch parser.add_argument( '--start_step', help='Starting step count", "- set(bias_param_names)) == set(gn_param_names) # Learning rate of 0 is", "### Dataset ### timers['roidb'].tic() roidb, ratio_list, ratio_index = combined_roidb_for_training( cfg.TRAIN.DATASETS,", "(original_num_gpus, cfg.NUM_GPUS)) print(' IMS_PER_BATCH: %d --> %d' % (original_ims_per_batch, cfg.TRAIN.IMS_PER_BATCH))", "However it's fixed on master. optimizer.load_state_dict(checkpoint['optimizer']) # misc_utils.load_optimizer_state_dict(optimizer, checkpoint['optimizer']) del", "Detectron weights %s\", args.load_detectron) load_detectron_weight(maskRCNN, args.load_detectron) lr = optimizer.param_groups[0]['lr'] #", "help='Base learning rate.', default=None, type=float) parser.add_argument( '--lr_decay_gamma', help='Learning rate decay", "args.load_detectron) load_detectron_weight(maskRCNN, args.load_detectron) lr = optimizer.param_groups[0]['lr'] # lr of non-bias", "import SummaryWriter # Set the Tensorboard logger tblogger = SummaryWriter(output_dir)", "if value.requires_grad: if 'bias' in key: bias_params.append(value) bias_param_names.append(key) elif key", "ValueError(\"Unexpected args.dataset: {}\".format(args.dataset)) cfg_from_file(args.cfg_file) if args.set_cfgs is not None: cfg_from_list(args.set_cfgs)", "= os.path.join(ckpt_dir, 'model_step{}.pth'.format(step)) if isinstance(model, mynn.DataParallel): model = model.module model_state_dict", "### Training Loop ### maskRCNN.train() CHECKPOINT_PERIOD = int(cfg.TRAIN.SNAPSHOT_ITERS / cfg.NUM_GPUS)", "maskRCNN(**input_data) except: continue training_stats.UpdateIterStats(net_outputs, inner_iter) loss = net_outputs['total_loss'] loss.backward() optimizer.step()", "'--iter_size', help='Update once every iter_size steps, as in Caffe.', default=1,", "[] nonbias_param_names = [] nograd_param_names = [] for key, value", "cfg.FPN.RPN_COLLECT_SCALE: {}'.format(cfg.FPN.RPN_COLLECT_SCALE)) if args.num_workers is not None: cfg.DATA_LOADER.NUM_THREADS = args.num_workers", "inner_iter) loss = net_outputs['total_loss'] loss.backward() optimizer.step() training_stats.IterToc() training_stats.LogIterStats(step, lr) if", "if decay_steps_ind is None: decay_steps_ind = len(cfg.SOLVER.STEPS) training_stats = TrainingStats(", "from tensorboardX import SummaryWriter # Set the Tensorboard logger tblogger", "not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) save_name = os.path.join(ckpt_dir, 'model_step{}.pth'.format(step)) if isinstance(model, mynn.DataParallel):", "to use') parser.add_argument( '--num_classes', dest='num_classes', help='Number of classes in your", "help='Do not use CUDA device', action='store_false') # Optimization # These", "learning rate.', default=None, type=float) parser.add_argument( '--lr_decay_gamma', help='Learning rate decay rate.',", "[value]', default=[], nargs='+') parser.add_argument( '--disp_interval', help='Display training info every N", "import Timer from utils.training_stats import TrainingStats # Set up logging", "overwrite. parser.add_argument( '--bs', dest='batch_size', help='Explicitly specify to overwrite the value", "ratio_index), batch_size=args.batch_size, drop_last=True ) dataset = RoiDataLoader( roidb, cfg.MODEL.NUM_CLASSES, training=True)", "number of workers to load data. Defaults to 4', type=int)", "nograd_param_names = [] for key, value in maskRCNN.named_parameters(): if value.requires_grad:", "set_cfgs. `None` means do not overwrite. parser.add_argument( '--bs', dest='batch_size', help='Explicitly", "%d' % (original_batch_size, effective_batch_size)) print(' NUM_GPUS: %d --> %d' %", "CHECKPOINT_PERIOD = int(cfg.TRAIN.SNAPSHOT_ITERS / cfg.NUM_GPUS) # Set index for decay", "if method == 'constant': warmup_factor = cfg.SOLVER.WARM_UP_FACTOR elif method ==", "comed from cfg_file.', type=int) parser.add_argument( '--nw', dest='num_workers', help='Explicitly specify to", "checkpoint['optimizer']) del checkpoint torch.cuda.empty_cache() if args.load_detectron: #TODO resume for detectron", "'bias' in key: bias_params.append(value) bias_param_names.append(key) elif key in gn_param_nameset: gn_params.append(value)", "specify to overwrite number of workers to load data. Defaults", "original_ims_per_batch = cfg.TRAIN.IMS_PER_BATCH original_num_gpus = cfg.NUM_GPUS if args.batch_size is None:", "a checkpoint', action='store_true') parser.add_argument( '--no_save', help='do not save anything', action='store_true')", "%.2f sec(s) to construct roidb', timers['roidb'].average_time) # Effective training sample", "original_ims_per_batch print('Scale FPN rpn_proposals collect size directly propotional to the", "- set(nograd_param_names) - set(bias_param_names)) == set(gn_param_names) # Learning rate of", "train_size, 'batch_size': args.batch_size, 'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, save_name) logger.info('save model:", "change:\\n' ' BASE_LR: {} --> {}'.format(old_base_lr, cfg.SOLVER.BASE_LR)) ### Adjust solver", "old_max_iter = cfg.SOLVER.MAX_ITER cfg.SOLVER.STEPS = list(map(lambda x: int(x * step_scale", "args.dataset == \"voc2012\": cfg.TRAIN.DATASETS = ('voc_2012_train',) cfg.MODEL.NUM_CLASSES = 21 elif", "optimizer) except (RuntimeError, KeyboardInterrupt): del dataiterator logger.info('Save ckpt on exception", "= optimizer.param_groups[0]['lr'] assert lr == lr_new decay_steps_ind += 1 training_stats.IterTic()", "and SOLVER.MAX_ITER linearly based on effective_batch_size change:\\n' ' SOLVER.STEPS: {}", "elif step == cfg.SOLVER.WARM_UP_ITERS: net_utils.update_learning_rate(optimizer, lr, cfg.SOLVER.BASE_LR) lr = optimizer.param_groups[0]['lr']", "training on a checkpoint', action='store_true') parser.add_argument( '--no_save', help='do not save", "to load') parser.add_argument( '--load_detectron', help='path to the detectron weight pickle", "dest='batch_size', help='Explicitly specify to overwrite the value comed from cfg_file.',", "= 2 elif args.dataset == \"voc2007\": cfg.TRAIN.DATASETS = ('voc_2007_train',) cfg.MODEL.NUM_CLASSES", "parser.add_argument( '--set', dest='set_cfgs', help='Set config keys. Key value sequence seperate", "---- Training ends ---- # Save last checkpoint save_ckpt(output_dir, args,", "= [] bias_param_names = [] nonbias_params = [] nonbias_param_names =", "= traceback.format_exc() print(stack_trace) finally: if args.use_tfboard and not args.no_save: tblogger.close()", "Model ### maskRCNN = Generalized_RCNN() if cfg.CUDA: maskRCNN.cuda() ### Optimizer", "required=True, help='Config file for training (and optionally testing)') parser.add_argument( '--set',", "up if step < cfg.SOLVER.WARM_UP_ITERS: method = cfg.SOLVER.WARM_UP_METHOD if method", "data loading threads: %d' % cfg.DATA_LOADER.NUM_THREADS) ### Overwrite some solver", "= TrainingStats( args, args.disp_interval, tblogger if args.use_tfboard and not args.no_save", "checkpoint save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) except (RuntimeError, KeyboardInterrupt):", "torch.save({ 'step': step, 'train_size': train_size, 'batch_size': args.batch_size, 'model': model.state_dict(), 'optimizer':", "1, gradients are `accumulated`, so lr is scaled based #", "f, pickle.HIGHEST_PROTOCOL) if args.use_tfboard: from tensorboardX import SummaryWriter # Set", "import nn as mynn import utils.net as net_utils import utils.misc", "method == 'constant': warmup_factor = cfg.SOLVER.WARM_UP_FACTOR elif method == 'linear':", "params in optimizer checkpoint's params_groups if needed # misc_utils.ensure_optimizer_ckpt_params_order(param_names, checkpoint)", "RuntimeError: received 0 items of ancdata. Issue: pytorch/pytorch#973 rlimit =", "cpu_keywords=['im_info', 'roidb'], minibatch=True) ### Training Setups ### args.run_name = misc_utils.get_run_name()", "workers to load data. Defaults to 4', type=int) parser.add_argument( '--iter_size',", "Training ends ---- # Save last checkpoint save_ckpt(output_dir, args, step,", "\"\"\" Training script for steps_with_decay policy\"\"\" import argparse import os", "highest prioity and can overwrite the values in config file", "gn_params.append(value) gn_param_names.append(key) else: nonbias_params.append(value) nonbias_param_names.append(key) else: nograd_param_names.append(key) assert (gn_param_nameset -", "* step_scale + 0.5) print('Adjust SOLVER.STEPS and SOLVER.MAX_ITER linearly based", "config changes:') print(' effective_batch_size: %d --> %d' % (original_batch_size, effective_batch_size))", "args.lr if args.lr_decay_gamma is not None: cfg.SOLVER.GAMMA = args.lr_decay_gamma assert_and_infer_cfg()", "help='Number of classes in your custom dataset', default=None, type=int) parser.add_argument(", "--> %d' % (original_num_gpus, cfg.NUM_GPUS)) print(' IMS_PER_BATCH: %d --> %d'", "method == 'linear': alpha = step / cfg.SOLVER.WARM_UP_ITERS warmup_factor =", "cfg.TRAIN.DATASETS = ('keypoints_coco_2017_train',) cfg.MODEL.NUM_CLASSES = 2 elif args.dataset == \"voc2007\":", "next(dataiterator) for key in input_data: if key != 'roidb': #", "= %d * %d' % (args.batch_size, args.iter_size)) print('Adaptive config changes:')", "in range(args.iter_size): try: input_data = next(dataiterator) except StopIteration: dataiterator =", "cfg.SOLVER.WEIGHT_DECAY}, {'params': bias_params, 'lr': 0 * (cfg.SOLVER.BIAS_DOUBLE_LR + 1), 'weight_decay':", "decay_steps_ind = i break if decay_steps_ind is None: decay_steps_ind =", "logger.info('Save ckpt done.') stack_trace = traceback.format_exc() print(stack_trace) finally: if args.use_tfboard", "BASE_LR: {} --> {}'.format(old_base_lr, cfg.SOLVER.BASE_LR)) ### Adjust solver steps step_scale", "checkpoint if args.load_ckpt: load_name = args.load_ckpt logging.info(\"loading checkpoint %s\", load_name)", "'lr': 0 * (cfg.SOLVER.BIAS_DOUBLE_LR + 1), 'weight_decay': cfg.SOLVER.WEIGHT_DECAY if cfg.SOLVER.BIAS_WEIGHT_DECAY", "train_size: print('train_size value: %d different from the one in checkpoint:", "size change linearly # For iter_size > 1, gradients are", "= None for i in range(1, len(cfg.SOLVER.STEPS)): if cfg.SOLVER.STEPS[i] >=", "= ('coco_2014_train',) cfg.MODEL.NUM_CLASSES = 4 elif args.dataset == \"keypoints_coco2017\": cfg.TRAIN.DATASETS", "for key, value in maskRCNN.named_parameters(): if value.requires_grad: if 'bias' in", "= 4 elif args.dataset == \"keypoints_coco2017\": cfg.TRAIN.DATASETS = ('keypoints_coco_2017_train',) cfg.MODEL.NUM_CLASSES", "run!\") if args.dataset == \"coco2017\": cfg.TRAIN.DATASETS = ('coco_2014_train',) cfg.MODEL.NUM_CLASSES =", "list(map(Variable, input_data[key])) try: net_outputs = maskRCNN(**input_data) except: continue training_stats.UpdateIterStats(net_outputs, inner_iter)", "lr is scaled based # on batch_size instead of effective_batch_size", "bias_params = [] bias_param_names = [] nonbias_params = [] nonbias_param_names", "training: requires same iterations per epoch parser.add_argument( '--resume', help='resume to", "%s\", args.load_detectron) load_detectron_weight(maskRCNN, args.load_detectron) lr = optimizer.param_groups[0]['lr'] # lr of", "'_step' output_dir = misc_utils.get_output_dir(args, args.run_name) args.cfg_filename = os.path.basename(args.cfg_file) if not", "MinibatchSampler, BatchSampler, collate_minibatch from modeling.model_builder import Generalized_RCNN from utils.detectron_weight_helper import", "import pickle import resource import traceback import logging from collections", "help='Learning rate decay rate.', default=None, type=float) # Epoch parser.add_argument( '--start_step',", "logger tblogger = SummaryWriter(output_dir) ### Training Loop ### maskRCNN.train() CHECKPOINT_PERIOD", "== 0: save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) # ----", "elif args.dataset == \"keypoints_coco2017\": cfg.TRAIN.DATASETS = ('keypoints_coco_2017_train',) cfg.MODEL.NUM_CLASSES = 2", "\"\"\"Save checkpoint\"\"\" if args.no_save: return ckpt_dir = os.path.join(output_dir, 'ckpt') if", "SOLVER.MAX_ITER linearly based on effective_batch_size change:\\n' ' SOLVER.STEPS: {} -->", "pylint: disable=unused-import import nn as mynn import utils.net as net_utils", "# Effective training sample size for one epoch train_size =", "pytorch/pytorch#973 rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1])) def parse_args(): \"\"\"Parse", "cfg.MODEL.NUM_CLASSES = 21 elif args.dataset == \"voc2012\": cfg.TRAIN.DATASETS = ('voc_2012_train',)", "to overwrite number of workers to load data. Defaults to", "timers['roidb'].average_time) # Effective training sample size for one epoch train_size", "= ('voc_2007_train',) cfg.MODEL.NUM_CLASSES = 21 elif args.dataset == \"voc2012\": cfg.TRAIN.DATASETS", "else: nograd_param_names.append(key) assert (gn_param_nameset - set(nograd_param_names) - set(bias_param_names)) == set(gn_param_names)", "### maskRCNN = Generalized_RCNN() if cfg.CUDA: maskRCNN.cuda() ### Optimizer ###", "import os import sys import pickle import resource import traceback", "maskRCNN.named_modules(): if isinstance(module, nn.GroupNorm): gn_param_nameset.add(name+'.weight') gn_param_nameset.add(name+'.bias') gn_params = [] gn_param_names", "import utils.misc as misc_utils from core.config import cfg, cfg_from_file, cfg_from_list,", "different from the one in checkpoint: %d' % (train_size, checkpoint['train_size']))", "if not torch.cuda.is_available(): sys.exit(\"Need a CUDA device to run the", "construct roidb', timers['roidb'].average_time) # Effective training sample size for one", "TrainingStats( args, args.disp_interval, tblogger if args.use_tfboard and not args.no_save else", "steps_with_decay policy\"\"\" import argparse import os import sys import pickle", "2 elif args.dataset == \"voc2007\": cfg.TRAIN.DATASETS = ('voc_2007_train',) cfg.MODEL.NUM_CLASSES =", "+ 0.5) print('Adjust SOLVER.STEPS and SOLVER.MAX_ITER linearly based on effective_batch_size", "cfg.NUM_GPUS > 0: cfg.CUDA = True else: raise ValueError(\"Need Cuda", "sampler=MinibatchSampler(ratio_list, ratio_index), batch_size=args.batch_size, drop_last=True ) dataset = RoiDataLoader( roidb, cfg.MODEL.NUM_CLASSES,", "next(dataiterator) except StopIteration: dataiterator = iter(dataloader) input_data = next(dataiterator) for", "finally: if args.use_tfboard and not args.no_save: tblogger.close() if __name__ ==", "whitespace.' 'e.g. [key] [value] [key] [value]', default=[], nargs='+') parser.add_argument( '--disp_interval',", "lr) if (step+1) % CHECKPOINT_PERIOD == 0: save_ckpt(output_dir, args, step,", "load_detectron_weight from utils.logging import setup_logging from utils.timer import Timer from", "args} with open(os.path.join(output_dir, 'config_and_args.pkl'), 'wb') as f: pickle.dump(blob, f, pickle.HIGHEST_PROTOCOL)", "logging and load config options logger = setup_logging(__name__) logging.getLogger('roi_data.loader').setLevel(logging.INFO) #", "log training info', action='store_true') return parser.parse_args() def save_ckpt(output_dir, args, step,", "roidb', timers['roidb'].average_time) # Effective training sample size for one epoch", "training info', action='store_true') return parser.parse_args() def save_ckpt(output_dir, args, step, train_size,", "lr_new elif step == cfg.SOLVER.WARM_UP_ITERS: net_utils.update_learning_rate(optimizer, lr, cfg.SOLVER.BASE_LR) lr =", "cfg.NUM_GPUS)) print(' IMS_PER_BATCH: %d --> %d' % (original_ims_per_batch, cfg.TRAIN.IMS_PER_BATCH)) ###", "batch_size instead of effective_batch_size old_base_lr = cfg.SOLVER.BASE_LR cfg.SOLVER.BASE_LR *= args.batch_size", "help='checkpoint path to load') parser.add_argument( '--load_detectron', help='path to the detectron", "print('Adjust SOLVER.STEPS and SOLVER.MAX_ITER linearly based on effective_batch_size change:\\n' '", "cfg_from_list, assert_and_infer_cfg from datasets.roidb import combined_roidb_for_training from roi_data.loader import RoiDataLoader,", "effective_batch_size old_solver_steps = cfg.SOLVER.STEPS old_max_iter = cfg.SOLVER.MAX_ITER cfg.SOLVER.STEPS = list(map(lambda", "%d --> %d' % (original_ims_per_batch, cfg.TRAIN.IMS_PER_BATCH)) ### Adjust learning based", "type=float) parser.add_argument( '--lr_decay_gamma', help='Learning rate decay rate.', default=None, type=float) #", "X-RCNN network') parser.add_argument( '--dataset', dest='dataset', required=True, help='Dataset to use') parser.add_argument(", "def main(): \"\"\"Main function\"\"\" args = parse_args() print('Called with args:')", "decay_steps_ind < len(cfg.SOLVER.STEPS) and \\ step == cfg.SOLVER.STEPS[decay_steps_ind]: logger.info('Decay the", "# ---- Training ends ---- # Save last checkpoint save_ckpt(output_dir,", "values set by set_cfgs. `None` means do not overwrite. parser.add_argument(", "set(gn_param_names) # Learning rate of 0 is a dummy value", "logger.info('Decay the learning on step %d', step) lr_new = lr", "range(args.start_step, cfg.SOLVER.MAX_ITER): # Warm up if step < cfg.SOLVER.WARM_UP_ITERS: method", "= args.lr if args.lr_decay_gamma is not None: cfg.SOLVER.GAMMA = args.lr_decay_gamma", "= resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1])) def parse_args(): \"\"\"Parse input arguments\"\"\"", "on master. optimizer.load_state_dict(checkpoint['optimizer']) # misc_utils.load_optimizer_state_dict(optimizer, checkpoint['optimizer']) del checkpoint torch.cuda.empty_cache() if", "help='Explicitly specify to overwrite number of workers to load data.", "with open(os.path.join(output_dir, 'config_and_args.pkl'), 'wb') as f: pickle.dump(blob, f, pickle.HIGHEST_PROTOCOL) if", "not args.no_save else None) try: logger.info('Training starts !') step =", "deadlock in dataloader import _init_paths # pylint: disable=unused-import import nn", "net_utils import utils.misc as misc_utils from core.config import cfg, cfg_from_file,", "args.start_step: decay_steps_ind = i break if decay_steps_ind is None: decay_steps_ind", "not args.no_save: if not os.path.exists(output_dir): os.makedirs(output_dir) blob = {'cfg': yaml.dump(cfg),", "print(' NUM_GPUS: %d --> %d' % (original_num_gpus, cfg.NUM_GPUS)) print(' IMS_PER_BATCH:", "0: cfg.CUDA = True else: raise ValueError(\"Need Cuda device to", "prioity and can overwrite the values in config file #", "and cfg.MODEL.FASTER_RCNN: cfg.FPN.RPN_COLLECT_SCALE = cfg.TRAIN.IMS_PER_BATCH / original_ims_per_batch print('Scale FPN rpn_proposals", "print('train_size value: %d different from the one in checkpoint: %d'", "parser.add_argument( '--use_tfboard', help='Use tensorflow tensorboard to log training info', action='store_true')", "raise ValueError(\"Need Cuda device to run !\") if args.dataset ==", "`collect_and_distribute_fpn_rpn_proposals.py` # # post_nms_topN = int(cfg[cfg_key].RPN_POST_NMS_TOP_N * cfg.FPN.RPN_COLLECT_SCALE + 0.5)", "for one epoch train_size = roidb_size // args.batch_size * args.batch_size", "according to batch_size change:\\n' ' BASE_LR: {} --> {}'.format(old_base_lr, cfg.SOLVER.BASE_LR))", "Adaptively adjust some configs ### original_batch_size = cfg.NUM_GPUS * cfg.TRAIN.IMS_PER_BATCH", "number of classes in your custom dataset to run!\") if", "if args.load_detectron: #TODO resume for detectron weights (load sgd momentum", "maskRCNN, optimizer) logger.info('Save ckpt done.') stack_trace = traceback.format_exc() print(stack_trace) finally:", "is not None: cfg_from_list(args.set_cfgs) ### Adaptively adjust some configs ###", "= model.module model_state_dict = model.state_dict() torch.save({ 'step': step, 'train_size': train_size,", "[value] [key] [value]', default=[], nargs='+') parser.add_argument( '--disp_interval', help='Display training info", "None for i in range(1, len(cfg.SOLVER.STEPS)): if cfg.SOLVER.STEPS[i] >= args.start_step:", "warmup_factor = cfg.SOLVER.WARM_UP_FACTOR * (1 - alpha) + alpha else:", "cfg.SOLVER.MAX_ITER = int(cfg.SOLVER.MAX_ITER * step_scale + 0.5) print('Adjust SOLVER.STEPS and", "Dataset ### timers['roidb'].tic() roidb, ratio_list, ratio_index = combined_roidb_for_training( cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES)", "= lr * cfg.SOLVER.GAMMA net_utils.update_learning_rate(optimizer, lr, lr_new) lr = optimizer.param_groups[0]['lr']", "= combined_roidb_for_training( cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES) timers['roidb'].toc() roidb_size = len(roidb) logger.info('{:d} roidb", "cfg.SOLVER.MAX_ITER)) # Scale FPN rpn_proposals collect size (post_nms_topN) in `collect`", "sec(s) to construct roidb', timers['roidb'].average_time) # Effective training sample size", "issue 1355: possible deadlock in dataloader import _init_paths # pylint:", "np import yaml import torch from torch.autograd import Variable import", "batch_size * iter_size = %d * %d' % (args.batch_size, args.iter_size))", "%s\", load_name) checkpoint = torch.load(load_name, map_location=lambda storage, loc: storage) net_utils.load_ckpt(maskRCNN,", "every N iterations', default=20, type=int) parser.add_argument( '--no_cuda', dest='cuda', help='Do not", "= [ {'params': nonbias_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY}, {'params': bias_params,", "action='store_true') return parser.parse_args() def save_ckpt(output_dir, args, step, train_size, model, optimizer):", "checkpoint's params_groups if needed # misc_utils.ensure_optimizer_ckpt_params_order(param_names, checkpoint) # There is", "the values in config file # or values set by", "original_batch_size = cfg.NUM_GPUS * cfg.TRAIN.IMS_PER_BATCH original_ims_per_batch = cfg.TRAIN.IMS_PER_BATCH original_num_gpus =", "# Epoch parser.add_argument( '--start_step', help='Starting step count for training epoch.", "momentum values) logging.info(\"loading Detectron weights %s\", args.load_detectron) load_detectron_weight(maskRCNN, args.load_detectron) lr", "None: args.batch_size = original_batch_size cfg.NUM_GPUS = torch.cuda.device_count() assert (args.batch_size %", "!') step = args.start_step for step in range(args.start_step, cfg.SOLVER.MAX_ITER): #", "gn_param_nameset = set() for name, module in maskRCNN.named_modules(): if isinstance(module,", "except: continue training_stats.UpdateIterStats(net_outputs, inner_iter) loss = net_outputs['total_loss'] loss.backward() optimizer.step() training_stats.IterToc()", "starts !') step = args.start_step for step in range(args.start_step, cfg.SOLVER.MAX_ITER):", "{}'.format(cfg.FPN.RPN_COLLECT_SCALE)) if args.num_workers is not None: cfg.DATA_LOADER.NUM_THREADS = args.num_workers print('Number", "set(bias_param_names)) == set(gn_param_names) # Learning rate of 0 is a", "is not None: cfg.SOLVER.GAMMA = args.lr_decay_gamma assert_and_infer_cfg() timers = defaultdict(Timer)", "'--no_cuda', dest='cuda', help='Do not use CUDA device', action='store_false') # Optimization", "== lr_new elif step == cfg.SOLVER.WARM_UP_ITERS: net_utils.update_learning_rate(optimizer, lr, cfg.SOLVER.BASE_LR) lr", "os.path.join(ckpt_dir, 'model_step{}.pth'.format(step)) if isinstance(model, mynn.DataParallel): model = model.module model_state_dict =", "%d' % (args.batch_size, args.iter_size)) print('Adaptive config changes:') print(' effective_batch_size: %d", "= cfg.NUM_GPUS * cfg.TRAIN.IMS_PER_BATCH original_ims_per_batch = cfg.TRAIN.IMS_PER_BATCH original_num_gpus = cfg.NUM_GPUS", "not save anything', action='store_true') parser.add_argument( '--load_ckpt', help='checkpoint path to load')", "module in maskRCNN.named_modules(): if isinstance(module, nn.GroupNorm): gn_param_nameset.add(name+'.weight') gn_param_nameset.add(name+'.bias') gn_params =", "value in maskRCNN.named_parameters(): if value.requires_grad: if 'bias' in key: bias_params.append(value)", "steps step_scale = original_batch_size / effective_batch_size old_solver_steps = cfg.SOLVER.STEPS old_max_iter", "parser.add_argument( '--bs', dest='batch_size', help='Explicitly specify to overwrite the value comed", "help='Update once every iter_size steps, as in Caffe.', default=1, type=int)", "on effective_batch_size change:\\n' ' SOLVER.STEPS: {} --> {}\\n' ' SOLVER.MAX_ITER:", "checkpoint['model']) if args.resume: args.start_step = checkpoint['step'] + 1 if 'train_size'", "isinstance(module, nn.GroupNorm): gn_param_nameset.add(name+'.weight') gn_param_nameset.add(name+'.bias') gn_params = [] gn_param_names = []", "These options has the highest prioity and can overwrite the", "optimizer.param_groups[0]['lr'] assert lr == lr_new elif step == cfg.SOLVER.WARM_UP_ITERS: net_utils.update_learning_rate(optimizer,", "tblogger = SummaryWriter(output_dir) ### Training Loop ### maskRCNN.train() CHECKPOINT_PERIOD =", "weights (load sgd momentum values) logging.info(\"loading Detectron weights %s\", args.load_detectron)", "resource import traceback import logging from collections import defaultdict import", "try: input_data = next(dataiterator) except StopIteration: dataiterator = iter(dataloader) input_data", "to the detectron weight pickle file') parser.add_argument( '--use_tfboard', help='Use tensorflow", "\"\"\"Main function\"\"\" args = parse_args() print('Called with args:') print(args) if", "'weight_decay': cfg.SOLVER.WEIGHT_DECAY}, {'params': bias_params, 'lr': 0 * (cfg.SOLVER.BIAS_DOUBLE_LR + 1),", "of paramerters for each paramter param_names = [nonbias_param_names, bias_param_names, gn_param_names]", "else: raise ValueError(\"Need Cuda device to run !\") if args.dataset", "type=int) parser.add_argument( '--no_cuda', dest='cuda', help='Do not use CUDA device', action='store_false')", "solver steps step_scale = original_batch_size / effective_batch_size old_solver_steps = cfg.SOLVER.STEPS", "alpha else: raise KeyError('Unknown SOLVER.WARM_UP_METHOD: {}'.format(method)) lr_new = cfg.SOLVER.BASE_LR *", "parser.add_argument( '--dataset', dest='dataset', required=True, help='Dataset to use') parser.add_argument( '--num_classes', dest='num_classes',", "elif args.dataset == \"custom_dataset\": cfg.TRAIN.DATASETS = ('custom_data_train',) cfg.MODEL.NUM_CLASSES = args.num_classes", "< len(cfg.SOLVER.STEPS) and \\ step == cfg.SOLVER.STEPS[decay_steps_ind]: logger.info('Decay the learning", "torch.nn as nn import cv2 cv2.setNumThreads(0) # pytorch issue 1355:", "raise ValueError(\"Need number of classes in your custom dataset to", "%d' % (original_ims_per_batch, cfg.TRAIN.IMS_PER_BATCH)) ### Adjust learning based on batch", "help='Explicitly specify to overwrite the value comed from cfg_file.', type=int)", "'--lr', help='Base learning rate.', default=None, type=float) parser.add_argument( '--lr_decay_gamma', help='Learning rate", "cfg.TRAIN.IMS_PER_BATCH original_num_gpus = cfg.NUM_GPUS if args.batch_size is None: args.batch_size =", "#TODO resume for detectron weights (load sgd momentum values) logging.info(\"loading", "size for one epoch train_size = roidb_size // args.batch_size *", "i break if decay_steps_ind is None: decay_steps_ind = len(cfg.SOLVER.STEPS) training_stats", "[nonbias_param_names, bias_param_names, gn_param_names] if cfg.SOLVER.TYPE == \"SGD\": optimizer = torch.optim.SGD(params,", "name, module in maskRCNN.named_modules(): if isinstance(module, nn.GroupNorm): gn_param_nameset.add(name+'.weight') gn_param_nameset.add(name+'.bias') gn_params", "of workers to load data. Defaults to 4', type=int) parser.add_argument(", ") dataset = RoiDataLoader( roidb, cfg.MODEL.NUM_CLASSES, training=True) dataloader = torch.utils.data.DataLoader(", "value: %d different from the one in checkpoint: %d' %", "torch.cuda.is_available(): sys.exit(\"Need a CUDA device to run the code.\") if", "= optimizer.param_groups[0]['lr'] assert lr == lr_new elif step == cfg.SOLVER.WARM_UP_ITERS:", "net_outputs['total_loss'] loss.backward() optimizer.step() training_stats.IterToc() training_stats.LogIterStats(step, lr) if (step+1) % CHECKPOINT_PERIOD", "nn.GroupNorm): gn_param_nameset.add(name+'.weight') gn_param_nameset.add(name+'.bias') gn_params = [] gn_param_names = [] bias_params", "of 0 is a dummy value to be set properly", "logging.info(\"loading checkpoint %s\", load_name) checkpoint = torch.load(load_name, map_location=lambda storage, loc:", "%d, NUM_GPUS: %d' % (args.batch_size, cfg.NUM_GPUS) cfg.TRAIN.IMS_PER_BATCH = args.batch_size //", "= i break if decay_steps_ind is None: decay_steps_ind = len(cfg.SOLVER.STEPS)", "len(cfg.SOLVER.STEPS) training_stats = TrainingStats( args, args.disp_interval, tblogger if args.use_tfboard and", "lr * cfg.SOLVER.GAMMA net_utils.update_learning_rate(optimizer, lr, lr_new) lr = optimizer.param_groups[0]['lr'] assert", "%s', save_name) def main(): \"\"\"Main function\"\"\" args = parse_args() print('Called", "num_workers=cfg.DATA_LOADER.NUM_THREADS, collate_fn=collate_minibatch) dataiterator = iter(dataloader) ### Model ### maskRCNN =", "\"\"\"Parse input arguments\"\"\" parser = argparse.ArgumentParser(description='Train a X-RCNN network') parser.add_argument(", "save_name) logger.info('save model: %s', save_name) def main(): \"\"\"Main function\"\"\" args", "import argparse import os import sys import pickle import resource", "logger.info('{:d} roidb entries'.format(roidb_size)) logger.info('Takes %.2f sec(s) to construct roidb', timers['roidb'].average_time)", "0 is a dummy value to be set properly at", "'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY}, {'params': bias_params, 'lr': 0 * (cfg.SOLVER.BIAS_DOUBLE_LR", "None: cfg.DATA_LOADER.NUM_THREADS = args.num_workers print('Number of data loading threads: %d'", "train_size, maskRCNN, optimizer) logger.info('Save ckpt done.') stack_trace = traceback.format_exc() print(stack_trace)", "in maskRCNN.named_parameters(): if value.requires_grad: if 'bias' in key: bias_params.append(value) bias_param_names.append(key)", "%d different from the one in checkpoint: %d' % (train_size,", "+ 0.5) if cfg.FPN.FPN_ON and cfg.MODEL.FASTER_RCNN: cfg.FPN.RPN_COLLECT_SCALE = cfg.TRAIN.IMS_PER_BATCH /", "lr of non-bias parameters, for commmand line outputs. maskRCNN =", "classes in your custom dataset to run!\") if args.dataset ==", "default=None, type=int) parser.add_argument( '--cfg', dest='cfg_file', required=True, help='Config file for training", "original_batch_size print('Adjust BASE_LR linearly according to batch_size change:\\n' ' BASE_LR:", "loading threads: %d' % cfg.DATA_LOADER.NUM_THREADS) ### Overwrite some solver settings", "None: cfg.SOLVER.GAMMA = args.lr_decay_gamma assert_and_infer_cfg() timers = defaultdict(Timer) ### Dataset", "{} --> {}'.format(old_base_lr, cfg.SOLVER.BASE_LR)) ### Adjust solver steps step_scale =", "line outputs. maskRCNN = mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'], minibatch=True) ### Training", "Overwrite some solver settings from command line arguments if args.optimizer", "'weight_decay': cfg.SOLVER.WEIGHT_DECAY if cfg.SOLVER.BIAS_WEIGHT_DECAY else 0}, {'params': gn_params, 'lr': 0,", "range(1, len(cfg.SOLVER.STEPS)): if cfg.SOLVER.STEPS[i] >= args.start_step: decay_steps_ind = i break", "file # or values set by set_cfgs. `None` means do", "= args.num_classes else: raise ValueError(\"Unexpected args.dataset: {}\".format(args.dataset)) cfg_from_file(args.cfg_file) if args.set_cfgs", "the learning on step %d', step) lr_new = lr *", "iterations', default=20, type=int) parser.add_argument( '--no_cuda', dest='cuda', help='Do not use CUDA", "1), 'weight_decay': cfg.SOLVER.WEIGHT_DECAY if cfg.SOLVER.BIAS_WEIGHT_DECAY else 0}, {'params': gn_params, 'lr':", "!\") if args.dataset == \"custom_dataset\" and args.num_classes is None: raise", "None: cfg_from_list(args.set_cfgs) ### Adaptively adjust some configs ### original_batch_size =", "if args.num_workers is not None: cfg.DATA_LOADER.NUM_THREADS = args.num_workers print('Number of", "[] for key, value in maskRCNN.named_parameters(): if value.requires_grad: if 'bias'", "import RoiDataLoader, MinibatchSampler, BatchSampler, collate_minibatch from modeling.model_builder import Generalized_RCNN from", "batch_sampler=batchSampler, num_workers=cfg.DATA_LOADER.NUM_THREADS, collate_fn=collate_minibatch) dataiterator = iter(dataloader) ### Model ### maskRCNN", "pickle file') parser.add_argument( '--use_tfboard', help='Use tensorflow tensorboard to log training", "= set() for name, module in maskRCNN.named_modules(): if isinstance(module, nn.GroupNorm):", "roidb, cfg.MODEL.NUM_CLASSES, training=True) dataloader = torch.utils.data.DataLoader( dataset, batch_sampler=batchSampler, num_workers=cfg.DATA_LOADER.NUM_THREADS, collate_fn=collate_minibatch)", "lr, lr_new) lr = optimizer.param_groups[0]['lr'] assert lr == lr_new decay_steps_ind", "cfg.SOLVER.WARM_UP_ITERS: net_utils.update_learning_rate(optimizer, lr, cfg.SOLVER.BASE_LR) lr = optimizer.param_groups[0]['lr'] assert lr ==", "steps, as in Caffe.', default=1, type=int) parser.add_argument( '--o', dest='optimizer', help='Training", "+ 1), 'weight_decay': cfg.SOLVER.WEIGHT_DECAY if cfg.SOLVER.BIAS_WEIGHT_DECAY else 0}, {'params': gn_params,", "some solver settings from command line arguments if args.optimizer is", "Cuda device to run !\") if args.dataset == \"custom_dataset\" and", "### Model ### maskRCNN = Generalized_RCNN() if cfg.CUDA: maskRCNN.cuda() ###", "SOLVER.WARM_UP_METHOD: {}'.format(method)) lr_new = cfg.SOLVER.BASE_LR * warmup_factor net_utils.update_learning_rate(optimizer, lr, lr_new)", "break if decay_steps_ind is None: decay_steps_ind = len(cfg.SOLVER.STEPS) training_stats =", "rate decay rate.', default=None, type=float) # Epoch parser.add_argument( '--start_step', help='Starting", "seperate by whitespace.' 'e.g. [key] [value] [key] [value]', default=[], nargs='+')", "model: %s', save_name) def main(): \"\"\"Main function\"\"\" args = parse_args()", "(post_nms_topN) in `collect` function # of `collect_and_distribute_fpn_rpn_proposals.py` # # post_nms_topN", "key in gn_param_nameset: gn_params.append(value) gn_param_names.append(key) else: nonbias_params.append(value) nonbias_param_names.append(key) else: nograd_param_names.append(key)", "None: raise ValueError(\"Need number of classes in your custom dataset", "'e.g. [key] [value] [key] [value]', default=[], nargs='+') parser.add_argument( '--disp_interval', help='Display", "= cfg.NUM_GPUS if args.batch_size is None: args.batch_size = original_batch_size cfg.NUM_GPUS", "roidb_size = len(roidb) logger.info('{:d} roidb entries'.format(roidb_size)) logger.info('Takes %.2f sec(s) to", "cfg_file.', type=int) parser.add_argument( '--nw', dest='num_workers', help='Explicitly specify to overwrite number", "cfg.SOLVER.GAMMA net_utils.update_learning_rate(optimizer, lr, lr_new) lr = optimizer.param_groups[0]['lr'] assert lr ==", "### Training Setups ### args.run_name = misc_utils.get_run_name() + '_step' output_dir", "= 21 elif args.dataset == \"voc2012\": cfg.TRAIN.DATASETS = ('voc_2012_train',) cfg.MODEL.NUM_CLASSES", "directly propotional to the change of IMS_PER_BATCH:\\n' ' cfg.FPN.RPN_COLLECT_SCALE: {}'.format(cfg.FPN.RPN_COLLECT_SCALE))", "elif cfg.SOLVER.TYPE == \"Adam\": optimizer = torch.optim.Adam(params) ### Load checkpoint", "# or values set by set_cfgs. `None` means do not", "tblogger if args.use_tfboard and not args.no_save else None) try: logger.info('Training", "save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) # ---- Training ends", "0-indexed.', default=0, type=int) # Resume training: requires same iterations per", "nograd_param_names.append(key) assert (gn_param_nameset - set(nograd_param_names) - set(bias_param_names)) == set(gn_param_names) #", "optimizer.step() training_stats.IterToc() training_stats.LogIterStats(step, lr) if (step+1) % CHECKPOINT_PERIOD == 0:", "import torch from torch.autograd import Variable import torch.nn as nn", "# Resume training: requires same iterations per epoch parser.add_argument( '--resume',", "= setup_logging(__name__) logging.getLogger('roi_data.loader').setLevel(logging.INFO) # RuntimeError: received 0 items of ancdata.", "args.load_ckpt: load_name = args.load_ckpt logging.info(\"loading checkpoint %s\", load_name) checkpoint =", "args.use_tfboard and not args.no_save else None) try: logger.info('Training starts !')", "not None: cfg.SOLVER.GAMMA = args.lr_decay_gamma assert_and_infer_cfg() timers = defaultdict(Timer) ###", "and not args.no_save else None) try: logger.info('Training starts !') step", "Caffe.', default=1, type=int) parser.add_argument( '--o', dest='optimizer', help='Training optimizer.', default=None) parser.add_argument(", "type=float) # Epoch parser.add_argument( '--start_step', help='Starting step count for training", "resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1])) def parse_args(): \"\"\"Parse input arguments\"\"\" parser", "the change of IMS_PER_BATCH:\\n' ' cfg.FPN.RPN_COLLECT_SCALE: {}'.format(cfg.FPN.RPN_COLLECT_SCALE)) if args.num_workers is", "# of `collect_and_distribute_fpn_rpn_proposals.py` # # post_nms_topN = int(cfg[cfg_key].RPN_POST_NMS_TOP_N * cfg.FPN.RPN_COLLECT_SCALE", "BASE_LR linearly according to batch_size change:\\n' ' BASE_LR: {} -->", "entries'.format(roidb_size)) logger.info('Takes %.2f sec(s) to construct roidb', timers['roidb'].average_time) # Effective", "arguments if args.optimizer is not None: cfg.SOLVER.TYPE = args.optimizer if", "old_max_iter, cfg.SOLVER.MAX_ITER)) # Scale FPN rpn_proposals collect size (post_nms_topN) in", "gn_params = [] gn_param_names = [] bias_params = [] bias_param_names", "maskRCNN, optimizer) # ---- Training ends ---- # Save last", "('voc_2007_train',) cfg.MODEL.NUM_CLASSES = 21 elif args.dataset == \"voc2012\": cfg.TRAIN.DATASETS =", "core.config import cfg, cfg_from_file, cfg_from_list, assert_and_infer_cfg from datasets.roidb import combined_roidb_for_training", "linearly # For iter_size > 1, gradients are `accumulated`, so", "[] nonbias_params = [] nonbias_param_names = [] nograd_param_names = []", "[] gn_param_names = [] bias_params = [] bias_param_names = []", "'--start_step', help='Starting step count for training epoch. 0-indexed.', default=0, type=int)", "Training Loop ### maskRCNN.train() CHECKPOINT_PERIOD = int(cfg.TRAIN.SNAPSHOT_ITERS / cfg.NUM_GPUS) #", "config file # or values set by set_cfgs. `None` means", "of classes in your custom dataset', default=None, type=int) parser.add_argument( '--cfg',", "save_name = os.path.join(ckpt_dir, 'model_step{}.pth'.format(step)) if isinstance(model, mynn.DataParallel): model = model.module", "import sys import pickle import resource import traceback import logging", "sequence seperate by whitespace.' 'e.g. [key] [value] [key] [value]', default=[],", "= cfg.TRAIN.IMS_PER_BATCH original_num_gpus = cfg.NUM_GPUS if args.batch_size is None: args.batch_size", "--> {}'.format(old_solver_steps, cfg.SOLVER.STEPS, old_max_iter, cfg.SOLVER.MAX_ITER)) # Scale FPN rpn_proposals collect", "(cfg.SOLVER.BIAS_DOUBLE_LR + 1), 'weight_decay': cfg.SOLVER.WEIGHT_DECAY if cfg.SOLVER.BIAS_WEIGHT_DECAY else 0}, {'params':", "# # post_nms_topN = int(cfg[cfg_key].RPN_POST_NMS_TOP_N * cfg.FPN.RPN_COLLECT_SCALE + 0.5) if", "if args.lr is not None: cfg.SOLVER.BASE_LR = args.lr if args.lr_decay_gamma", "type=int) parser.add_argument( '--o', dest='optimizer', help='Training optimizer.', default=None) parser.add_argument( '--lr', help='Base", "int(cfg.TRAIN.SNAPSHOT_ITERS / cfg.NUM_GPUS) # Set index for decay steps decay_steps_ind", "'linear': alpha = step / cfg.SOLVER.WARM_UP_ITERS warmup_factor = cfg.SOLVER.WARM_UP_FACTOR *", "assert lr == lr_new elif step == cfg.SOLVER.WARM_UP_ITERS: net_utils.update_learning_rate(optimizer, lr,", "else: raise ValueError(\"Unexpected args.dataset: {}\".format(args.dataset)) cfg_from_file(args.cfg_file) if args.set_cfgs is not", "Set up logging and load config options logger = setup_logging(__name__)", "cfg.SOLVER.WARM_UP_FACTOR elif method == 'linear': alpha = step / cfg.SOLVER.WARM_UP_ITERS", "= parse_args() print('Called with args:') print(args) if not torch.cuda.is_available(): sys.exit(\"Need", "in range(args.start_step, cfg.SOLVER.MAX_ITER): # Warm up if step < cfg.SOLVER.WARM_UP_ITERS:", "[] nograd_param_names = [] for key, value in maskRCNN.named_parameters(): if", "`accumulated`, so lr is scaled based # on batch_size instead", "Optimizer ### gn_param_nameset = set() for name, module in maskRCNN.named_modules():", "required=True, help='Dataset to use') parser.add_argument( '--num_classes', dest='num_classes', help='Number of classes", "dataiterator = iter(dataloader) ### Model ### maskRCNN = Generalized_RCNN() if", "(step+1) % CHECKPOINT_PERIOD == 0: save_ckpt(output_dir, args, step, train_size, maskRCNN,", "non-bias parameters, for commmand line outputs. maskRCNN = mynn.DataParallel(maskRCNN, cpu_keywords=['im_info',", "as f: pickle.dump(blob, f, pickle.HIGHEST_PROTOCOL) if args.use_tfboard: from tensorboardX import", "use CUDA device', action='store_false') # Optimization # These options has", "### maskRCNN.train() CHECKPOINT_PERIOD = int(cfg.TRAIN.SNAPSHOT_ITERS / cfg.NUM_GPUS) # Set index", "training epoch. 0-indexed.', default=0, type=int) # Resume training: requires same", "int(x * step_scale + 0.5), cfg.SOLVER.STEPS)) cfg.SOLVER.MAX_ITER = int(cfg.SOLVER.MAX_ITER *", "args.use_tfboard: from tensorboardX import SummaryWriter # Set the Tensorboard logger", "is None: raise ValueError(\"Need number of classes in your custom", "Training script for steps_with_decay policy\"\"\" import argparse import os import", "= cfg.SOLVER.BASE_LR cfg.SOLVER.BASE_LR *= args.batch_size / original_batch_size print('Adjust BASE_LR linearly", "weight pickle file') parser.add_argument( '--use_tfboard', help='Use tensorflow tensorboard to log", "device to run the code.\") if args.cuda or cfg.NUM_GPUS >", "lr == lr_new decay_steps_ind += 1 training_stats.IterTic() optimizer.zero_grad() for inner_iter", "import Variable import torch.nn as nn import cv2 cv2.setNumThreads(0) #", "net_outputs = maskRCNN(**input_data) except: continue training_stats.UpdateIterStats(net_outputs, inner_iter) loss = net_outputs['total_loss']", "int(cfg[cfg_key].RPN_POST_NMS_TOP_N * cfg.FPN.RPN_COLLECT_SCALE + 0.5) if cfg.FPN.FPN_ON and cfg.MODEL.FASTER_RCNN: cfg.FPN.RPN_COLLECT_SCALE", "bias_params, 'lr': 0 * (cfg.SOLVER.BIAS_DOUBLE_LR + 1), 'weight_decay': cfg.SOLVER.WEIGHT_DECAY if", "= [] nonbias_param_names = [] nograd_param_names = [] for key,", "needed # misc_utils.ensure_optimizer_ckpt_params_order(param_names, checkpoint) # There is a bug in", "assert lr == cfg.SOLVER.BASE_LR # Learning rate decay if decay_steps_ind", "linearly based on effective_batch_size change:\\n' ' SOLVER.STEPS: {} --> {}\\n'", "data. Defaults to 4', type=int) parser.add_argument( '--iter_size', help='Update once every", "cfg.NUM_GPUS * cfg.TRAIN.IMS_PER_BATCH original_ims_per_batch = cfg.TRAIN.IMS_PER_BATCH original_num_gpus = cfg.NUM_GPUS if", "on batch size change linearly # For iter_size > 1,", "gn_param_names = [] bias_params = [] bias_param_names = [] nonbias_params", "setup_logging from utils.timer import Timer from utils.training_stats import TrainingStats #", "0.5) if cfg.FPN.FPN_ON and cfg.MODEL.FASTER_RCNN: cfg.FPN.RPN_COLLECT_SCALE = cfg.TRAIN.IMS_PER_BATCH / original_ims_per_batch", "for training epoch. 0-indexed.', default=0, type=int) # Resume training: requires", "train_size = roidb_size // args.batch_size * args.batch_size batchSampler = BatchSampler(", "default=None) parser.add_argument( '--lr', help='Base learning rate.', default=None, type=float) parser.add_argument( '--lr_decay_gamma',", "args.iter_size * args.batch_size print('effective_batch_size = batch_size * iter_size = %d", "change:\\n' ' SOLVER.STEPS: {} --> {}\\n' ' SOLVER.MAX_ITER: {} -->", "args.cfg_filename = os.path.basename(args.cfg_file) if not args.no_save: if not os.path.exists(output_dir): os.makedirs(output_dir)", "if args.lr_decay_gamma is not None: cfg.SOLVER.GAMMA = args.lr_decay_gamma assert_and_infer_cfg() timers", "= [] bias_params = [] bias_param_names = [] nonbias_params =", "if not os.path.exists(output_dir): os.makedirs(output_dir) blob = {'cfg': yaml.dump(cfg), 'args': args}", "= args.batch_size // cfg.NUM_GPUS effective_batch_size = args.iter_size * args.batch_size print('effective_batch_size", "the params in optimizer checkpoint's params_groups if needed # misc_utils.ensure_optimizer_ckpt_params_order(param_names,", "decay if decay_steps_ind < len(cfg.SOLVER.STEPS) and \\ step == cfg.SOLVER.STEPS[decay_steps_ind]:", "and load config options logger = setup_logging(__name__) logging.getLogger('roi_data.loader').setLevel(logging.INFO) # RuntimeError:", "length input_data[key] = list(map(Variable, input_data[key])) try: net_outputs = maskRCNN(**input_data) except:", "Warm up if step < cfg.SOLVER.WARM_UP_ITERS: method = cfg.SOLVER.WARM_UP_METHOD if", "train_size, model, optimizer): \"\"\"Save checkpoint\"\"\" if args.no_save: return ckpt_dir =", "args.disp_interval, tblogger if args.use_tfboard and not args.no_save else None) try:", "args, step, train_size, model, optimizer): \"\"\"Save checkpoint\"\"\" if args.no_save: return", "args.num_workers is not None: cfg.DATA_LOADER.NUM_THREADS = args.num_workers print('Number of data", "at the start of training params = [ {'params': nonbias_params,", "Adjust solver steps step_scale = original_batch_size / effective_batch_size old_solver_steps =", "epoch train_size = roidb_size // args.batch_size * args.batch_size batchSampler =", "optimizer.load_state_dict on Pytorch 0.3.1. # However it's fixed on master.", "Defaults to 4', type=int) parser.add_argument( '--iter_size', help='Update once every iter_size", "assert (args.batch_size % cfg.NUM_GPUS) == 0, \\ 'batch_size: %d, NUM_GPUS:", "import logging from collections import defaultdict import numpy as np", "default=0, type=int) # Resume training: requires same iterations per epoch", "to load data. Defaults to 4', type=int) parser.add_argument( '--iter_size', help='Update", "cfg.SOLVER.TYPE == \"Adam\": optimizer = torch.optim.Adam(params) ### Load checkpoint if", "dummy value to be set properly at the start of", "args.load_detectron) lr = optimizer.param_groups[0]['lr'] # lr of non-bias parameters, for", "cfg.TRAIN.IMS_PER_BATCH / original_ims_per_batch print('Scale FPN rpn_proposals collect size directly propotional", "open(os.path.join(output_dir, 'config_and_args.pkl'), 'wb') as f: pickle.dump(blob, f, pickle.HIGHEST_PROTOCOL) if args.use_tfboard:", "elif key in gn_param_nameset: gn_params.append(value) gn_param_names.append(key) else: nonbias_params.append(value) nonbias_param_names.append(key) else:", "(args.batch_size, args.iter_size)) print('Adaptive config changes:') print(' effective_batch_size: %d --> %d'", "lr_new decay_steps_ind += 1 training_stats.IterTic() optimizer.zero_grad() for inner_iter in range(args.iter_size):", "propotional to the change of IMS_PER_BATCH:\\n' ' cfg.FPN.RPN_COLLECT_SCALE: {}'.format(cfg.FPN.RPN_COLLECT_SCALE)) if", "set(nograd_param_names) - set(bias_param_names)) == set(gn_param_names) # Learning rate of 0", "# Set the Tensorboard logger tblogger = SummaryWriter(output_dir) ### Training", "iter(dataloader) input_data = next(dataiterator) for key in input_data: if key", "as mynn import utils.net as net_utils import utils.misc as misc_utils", "os.path.join(output_dir, 'ckpt') if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) save_name = os.path.join(ckpt_dir, 'model_step{}.pth'.format(step))", "= {'cfg': yaml.dump(cfg), 'args': args} with open(os.path.join(output_dir, 'config_and_args.pkl'), 'wb') as", "learning based on batch size change linearly # For iter_size", "+ alpha else: raise KeyError('Unknown SOLVER.WARM_UP_METHOD: {}'.format(method)) lr_new = cfg.SOLVER.BASE_LR", "gn_param_names] if cfg.SOLVER.TYPE == \"SGD\": optimizer = torch.optim.SGD(params, momentum=cfg.SOLVER.MOMENTUM) elif", "and can overwrite the values in config file # or", "import combined_roidb_for_training from roi_data.loader import RoiDataLoader, MinibatchSampler, BatchSampler, collate_minibatch from", "cfg.NUM_GPUS effective_batch_size = args.iter_size * args.batch_size print('effective_batch_size = batch_size *", "cfg.NUM_GPUS) == 0, \\ 'batch_size: %d, NUM_GPUS: %d' % (args.batch_size,", "step == cfg.SOLVER.WARM_UP_ITERS: net_utils.update_learning_rate(optimizer, lr, cfg.SOLVER.BASE_LR) lr = optimizer.param_groups[0]['lr'] assert", "logger.info('Takes %.2f sec(s) to construct roidb', timers['roidb'].average_time) # Effective training", "defaultdict import numpy as np import yaml import torch from", "parser.add_argument( '--no_cuda', dest='cuda', help='Do not use CUDA device', action='store_false') #", "decay_steps_ind += 1 training_stats.IterTic() optimizer.zero_grad() for inner_iter in range(args.iter_size): try:", "bias_param_names.append(key) elif key in gn_param_nameset: gn_params.append(value) gn_param_names.append(key) else: nonbias_params.append(value) nonbias_param_names.append(key)", "on a checkpoint', action='store_true') parser.add_argument( '--no_save', help='do not save anything',", "--> {}'.format(old_base_lr, cfg.SOLVER.BASE_LR)) ### Adjust solver steps step_scale = original_batch_size", "gradients are `accumulated`, so lr is scaled based # on", "' SOLVER.MAX_ITER: {} --> {}'.format(old_solver_steps, cfg.SOLVER.STEPS, old_max_iter, cfg.SOLVER.MAX_ITER)) # Scale", "drop_last=True ) dataset = RoiDataLoader( roidb, cfg.MODEL.NUM_CLASSES, training=True) dataloader =", "+= 1 training_stats.IterTic() optimizer.zero_grad() for inner_iter in range(args.iter_size): try: input_data", "None: decay_steps_ind = len(cfg.SOLVER.STEPS) training_stats = TrainingStats( args, args.disp_interval, tblogger", "to batch_size change:\\n' ' BASE_LR: {} --> {}'.format(old_base_lr, cfg.SOLVER.BASE_LR)) ###", "roidb_size // args.batch_size * args.batch_size batchSampler = BatchSampler( sampler=MinibatchSampler(ratio_list, ratio_index),", "collect size directly propotional to the change of IMS_PER_BATCH:\\n' '", "code.\") if args.cuda or cfg.NUM_GPUS > 0: cfg.CUDA = True", "iter(dataloader) ### Model ### maskRCNN = Generalized_RCNN() if cfg.CUDA: maskRCNN.cuda()", "changes:') print(' effective_batch_size: %d --> %d' % (original_batch_size, effective_batch_size)) print('", "' cfg.FPN.RPN_COLLECT_SCALE: {}'.format(cfg.FPN.RPN_COLLECT_SCALE)) if args.num_workers is not None: cfg.DATA_LOADER.NUM_THREADS =", "weights %s\", args.load_detectron) load_detectron_weight(maskRCNN, args.load_detectron) lr = optimizer.param_groups[0]['lr'] # lr", "step = args.start_step for step in range(args.start_step, cfg.SOLVER.MAX_ITER): # Warm", "if key != 'roidb': # roidb is a list of", "assert_and_infer_cfg() timers = defaultdict(Timer) ### Dataset ### timers['roidb'].tic() roidb, ratio_list,", "parser = argparse.ArgumentParser(description='Train a X-RCNN network') parser.add_argument( '--dataset', dest='dataset', required=True,", "is not None: cfg.DATA_LOADER.NUM_THREADS = args.num_workers print('Number of data loading", "lr = optimizer.param_groups[0]['lr'] # lr of non-bias parameters, for commmand", "for decay steps decay_steps_ind = None for i in range(1,", "if args.use_tfboard and not args.no_save: tblogger.close() if __name__ == '__main__':", "list(map(lambda x: int(x * step_scale + 0.5), cfg.SOLVER.STEPS)) cfg.SOLVER.MAX_ITER =", "args, step, train_size, maskRCNN, optimizer) except (RuntimeError, KeyboardInterrupt): del dataiterator", "if (step+1) % CHECKPOINT_PERIOD == 0: save_ckpt(output_dir, args, step, train_size,", "== cfg.SOLVER.STEPS[decay_steps_ind]: logger.info('Decay the learning on step %d', step) lr_new", "of data loading threads: %d' % cfg.DATA_LOADER.NUM_THREADS) ### Overwrite some", "disable=unused-import import nn as mynn import utils.net as net_utils import", "args.batch_size print('effective_batch_size = batch_size * iter_size = %d * %d'", "run the code.\") if args.cuda or cfg.NUM_GPUS > 0: cfg.CUDA", "step_scale = original_batch_size / effective_batch_size old_solver_steps = cfg.SOLVER.STEPS old_max_iter =", "== \"voc2007\": cfg.TRAIN.DATASETS = ('voc_2007_train',) cfg.MODEL.NUM_CLASSES = 21 elif args.dataset", "{}'.format(old_base_lr, cfg.SOLVER.BASE_LR)) ### Adjust solver steps step_scale = original_batch_size /", "def save_ckpt(output_dir, args, step, train_size, model, optimizer): \"\"\"Save checkpoint\"\"\" if", "= batch_size * iter_size = %d * %d' % (args.batch_size,", "action='store_true') parser.add_argument( '--no_save', help='do not save anything', action='store_true') parser.add_argument( '--load_ckpt',", "options has the highest prioity and can overwrite the values", "else: nonbias_params.append(value) nonbias_param_names.append(key) else: nograd_param_names.append(key) assert (gn_param_nameset - set(nograd_param_names) -", "storage, loc: storage) net_utils.load_ckpt(maskRCNN, checkpoint['model']) if args.resume: args.start_step = checkpoint['step']", "[] bias_params = [] bias_param_names = [] nonbias_params = []", "== \"coco2017\": cfg.TRAIN.DATASETS = ('coco_2014_train',) cfg.MODEL.NUM_CLASSES = 4 elif args.dataset", "solver settings from command line arguments if args.optimizer is not", "nonbias_param_names = [] nograd_param_names = [] for key, value in", "= args.load_ckpt logging.info(\"loading checkpoint %s\", load_name) checkpoint = torch.load(load_name, map_location=lambda", "step, 'train_size': train_size, 'batch_size': args.batch_size, 'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, save_name)", "%d' % (train_size, checkpoint['train_size'])) # reorder the params in optimizer", "None) try: logger.info('Training starts !') step = args.start_step for step", "import cv2 cv2.setNumThreads(0) # pytorch issue 1355: possible deadlock in", "args.dataset == \"voc2007\": cfg.TRAIN.DATASETS = ('voc_2007_train',) cfg.MODEL.NUM_CLASSES = 21 elif", "= defaultdict(Timer) ### Dataset ### timers['roidb'].tic() roidb, ratio_list, ratio_index =", "model = model.module model_state_dict = model.state_dict() torch.save({ 'step': step, 'train_size':", "\"voc2007\": cfg.TRAIN.DATASETS = ('voc_2007_train',) cfg.MODEL.NUM_CLASSES = 21 elif args.dataset ==", "argparse.ArgumentParser(description='Train a X-RCNN network') parser.add_argument( '--dataset', dest='dataset', required=True, help='Dataset to", "type=int) parser.add_argument( '--iter_size', help='Update once every iter_size steps, as in", "training_stats.IterToc() training_stats.LogIterStats(step, lr) if (step+1) % CHECKPOINT_PERIOD == 0: save_ckpt(output_dir,", "dest='dataset', required=True, help='Dataset to use') parser.add_argument( '--num_classes', dest='num_classes', help='Number of", "cfg.SOLVER.WEIGHT_DECAY_GN} ] # names of paramerters for each paramter param_names", "elif args.dataset == \"voc2007\": cfg.TRAIN.DATASETS = ('voc_2007_train',) cfg.MODEL.NUM_CLASSES = 21", "* %d' % (args.batch_size, args.iter_size)) print('Adaptive config changes:') print(' effective_batch_size:", "for training (and optionally testing)') parser.add_argument( '--set', dest='set_cfgs', help='Set config", "'--set', dest='set_cfgs', help='Set config keys. Key value sequence seperate by", "if args.use_tfboard: from tensorboardX import SummaryWriter # Set the Tensorboard", "collate_minibatch from modeling.model_builder import Generalized_RCNN from utils.detectron_weight_helper import load_detectron_weight from", "### gn_param_nameset = set() for name, module in maskRCNN.named_modules(): if", "= ('voc_2012_train',) cfg.MODEL.NUM_CLASSES = 21 elif args.dataset == \"custom_dataset\": cfg.TRAIN.DATASETS", "\"custom_dataset\": cfg.TRAIN.DATASETS = ('custom_data_train',) cfg.MODEL.NUM_CLASSES = args.num_classes else: raise ValueError(\"Unexpected", "load_detectron_weight(maskRCNN, args.load_detectron) lr = optimizer.param_groups[0]['lr'] # lr of non-bias parameters,", "Set the Tensorboard logger tblogger = SummaryWriter(output_dir) ### Training Loop", "help='Use tensorflow tensorboard to log training info', action='store_true') return parser.parse_args()", "StopIteration: dataiterator = iter(dataloader) input_data = next(dataiterator) for key in", "parameters, for commmand line outputs. maskRCNN = mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'],", "size (post_nms_topN) in `collect` function # of `collect_and_distribute_fpn_rpn_proposals.py` # #", "= maskRCNN(**input_data) except: continue training_stats.UpdateIterStats(net_outputs, inner_iter) loss = net_outputs['total_loss'] loss.backward()", "== cfg.SOLVER.WARM_UP_ITERS: net_utils.update_learning_rate(optimizer, lr, cfg.SOLVER.BASE_LR) lr = optimizer.param_groups[0]['lr'] assert lr", "roi_data.loader import RoiDataLoader, MinibatchSampler, BatchSampler, collate_minibatch from modeling.model_builder import Generalized_RCNN", "ckpt on exception ...') save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer)", "reorder the params in optimizer checkpoint's params_groups if needed #", "roidb is a list of ndarrays with inconsistent length input_data[key]", "paramerters for each paramter param_names = [nonbias_param_names, bias_param_names, gn_param_names] if", "< cfg.SOLVER.WARM_UP_ITERS: method = cfg.SOLVER.WARM_UP_METHOD if method == 'constant': warmup_factor", "parser.parse_args() def save_ckpt(output_dir, args, step, train_size, model, optimizer): \"\"\"Save checkpoint\"\"\"", "from utils.detectron_weight_helper import load_detectron_weight from utils.logging import setup_logging from utils.timer", "try: net_outputs = maskRCNN(**input_data) except: continue training_stats.UpdateIterStats(net_outputs, inner_iter) loss =", "For backward compatibility if checkpoint['train_size'] != train_size: print('train_size value: %d", "# For backward compatibility if checkpoint['train_size'] != train_size: print('train_size value:", "decay steps decay_steps_ind = None for i in range(1, len(cfg.SOLVER.STEPS)):", "# Learning rate of 0 is a dummy value to", "SummaryWriter(output_dir) ### Training Loop ### maskRCNN.train() CHECKPOINT_PERIOD = int(cfg.TRAIN.SNAPSHOT_ITERS /", "pickle.HIGHEST_PROTOCOL) if args.use_tfboard: from tensorboardX import SummaryWriter # Set the", "cfg.SOLVER.TYPE = args.optimizer if args.lr is not None: cfg.SOLVER.BASE_LR =", "specify to overwrite the value comed from cfg_file.', type=int) parser.add_argument(", "# Set up logging and load config options logger =", "range(args.iter_size): try: input_data = next(dataiterator) except StopIteration: dataiterator = iter(dataloader)", "dataset, batch_sampler=batchSampler, num_workers=cfg.DATA_LOADER.NUM_THREADS, collate_fn=collate_minibatch) dataiterator = iter(dataloader) ### Model ###", "0, \\ 'batch_size: %d, NUM_GPUS: %d' % (args.batch_size, cfg.NUM_GPUS) cfg.TRAIN.IMS_PER_BATCH", "cfg.SOLVER.BASE_LR)) ### Adjust solver steps step_scale = original_batch_size / effective_batch_size", "command line arguments if args.optimizer is not None: cfg.SOLVER.TYPE =", "yaml import torch from torch.autograd import Variable import torch.nn as", "### Adjust learning based on batch size change linearly #", "checkpoint['step'] + 1 if 'train_size' in checkpoint: # For backward", "try: logger.info('Training starts !') step = args.start_step for step in", "default=1, type=int) parser.add_argument( '--o', dest='optimizer', help='Training optimizer.', default=None) parser.add_argument( '--lr',", "### original_batch_size = cfg.NUM_GPUS * cfg.TRAIN.IMS_PER_BATCH original_ims_per_batch = cfg.TRAIN.IMS_PER_BATCH original_num_gpus", "training info every N iterations', default=20, type=int) parser.add_argument( '--no_cuda', dest='cuda',", "checkpoint torch.cuda.empty_cache() if args.load_detectron: #TODO resume for detectron weights (load", "/ cfg.NUM_GPUS) # Set index for decay steps decay_steps_ind =", "[ {'params': nonbias_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY}, {'params': bias_params, 'lr':", "+ '_step' output_dir = misc_utils.get_output_dir(args, args.run_name) args.cfg_filename = os.path.basename(args.cfg_file) if", "cfg.NUM_GPUS) # Set index for decay steps decay_steps_ind = None", "post_nms_topN = int(cfg[cfg_key].RPN_POST_NMS_TOP_N * cfg.FPN.RPN_COLLECT_SCALE + 0.5) if cfg.FPN.FPN_ON and", "not os.path.exists(output_dir): os.makedirs(output_dir) blob = {'cfg': yaml.dump(cfg), 'args': args} with", "maskRCNN, optimizer) except (RuntimeError, KeyboardInterrupt): del dataiterator logger.info('Save ckpt on", "save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) except (RuntimeError, KeyboardInterrupt): del", "save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) logger.info('Save ckpt done.') stack_trace", "loss = net_outputs['total_loss'] loss.backward() optimizer.step() training_stats.IterToc() training_stats.LogIterStats(step, lr) if (step+1)", "info every N iterations', default=20, type=int) parser.add_argument( '--no_cuda', dest='cuda', help='Do", "IMS_PER_BATCH: %d --> %d' % (original_ims_per_batch, cfg.TRAIN.IMS_PER_BATCH)) ### Adjust learning", "decay_steps_ind = len(cfg.SOLVER.STEPS) training_stats = TrainingStats( args, args.disp_interval, tblogger if", "for each paramter param_names = [nonbias_param_names, bias_param_names, gn_param_names] if cfg.SOLVER.TYPE", "learning on step %d', step) lr_new = lr * cfg.SOLVER.GAMMA", "a list of ndarrays with inconsistent length input_data[key] = list(map(Variable,", "args, step, train_size, maskRCNN, optimizer) logger.info('Save ckpt done.') stack_trace =", "params = [ {'params': nonbias_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY}, {'params':", "%d' % (args.batch_size, cfg.NUM_GPUS) cfg.TRAIN.IMS_PER_BATCH = args.batch_size // cfg.NUM_GPUS effective_batch_size", "default=20, type=int) parser.add_argument( '--no_cuda', dest='cuda', help='Do not use CUDA device',", "// args.batch_size * args.batch_size batchSampler = BatchSampler( sampler=MinibatchSampler(ratio_list, ratio_index), batch_size=args.batch_size,", "x: int(x * step_scale + 0.5), cfg.SOLVER.STEPS)) cfg.SOLVER.MAX_ITER = int(cfg.SOLVER.MAX_ITER", "is None: args.batch_size = original_batch_size cfg.NUM_GPUS = torch.cuda.device_count() assert (args.batch_size", "# pytorch issue 1355: possible deadlock in dataloader import _init_paths", "cfg_from_list(args.set_cfgs) ### Adaptively adjust some configs ### original_batch_size = cfg.NUM_GPUS", "Variable import torch.nn as nn import cv2 cv2.setNumThreads(0) # pytorch", "by set_cfgs. `None` means do not overwrite. parser.add_argument( '--bs', dest='batch_size',", "checkpoint: %d' % (train_size, checkpoint['train_size'])) # reorder the params in", "the Tensorboard logger tblogger = SummaryWriter(output_dir) ### Training Loop ###", "ckpt_dir = os.path.join(output_dir, 'ckpt') if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) save_name =", "sys.exit(\"Need a CUDA device to run the code.\") if args.cuda", "backward compatibility if checkpoint['train_size'] != train_size: print('train_size value: %d different", "RoiDataLoader, MinibatchSampler, BatchSampler, collate_minibatch from modeling.model_builder import Generalized_RCNN from utils.detectron_weight_helper", "based # on batch_size instead of effective_batch_size old_base_lr = cfg.SOLVER.BASE_LR", "print(' IMS_PER_BATCH: %d --> %d' % (original_ims_per_batch, cfg.TRAIN.IMS_PER_BATCH)) ### Adjust", "misc_utils.get_run_name() + '_step' output_dir = misc_utils.get_output_dir(args, args.run_name) args.cfg_filename = os.path.basename(args.cfg_file)", "one epoch train_size = roidb_size // args.batch_size * args.batch_size batchSampler", "is a bug in optimizer.load_state_dict on Pytorch 0.3.1. # However", "utils.logging import setup_logging from utils.timer import Timer from utils.training_stats import", "file') parser.add_argument( '--use_tfboard', help='Use tensorflow tensorboard to log training info',", "parse_args(): \"\"\"Parse input arguments\"\"\" parser = argparse.ArgumentParser(description='Train a X-RCNN network')", "cfg.TRAIN.DATASETS = ('coco_2014_train',) cfg.MODEL.NUM_CLASSES = 4 elif args.dataset == \"keypoints_coco2017\":", "cfg.TRAIN.DATASETS = ('voc_2012_train',) cfg.MODEL.NUM_CLASSES = 21 elif args.dataset == \"custom_dataset\":", "of non-bias parameters, for commmand line outputs. maskRCNN = mynn.DataParallel(maskRCNN,", "optimizer.load_state_dict(checkpoint['optimizer']) # misc_utils.load_optimizer_state_dict(optimizer, checkpoint['optimizer']) del checkpoint torch.cuda.empty_cache() if args.load_detectron: #TODO", "list of ndarrays with inconsistent length input_data[key] = list(map(Variable, input_data[key]))", "else: raise KeyError('Unknown SOLVER.WARM_UP_METHOD: {}'.format(method)) lr_new = cfg.SOLVER.BASE_LR * warmup_factor", "ratio_list, ratio_index = combined_roidb_for_training( cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES) timers['roidb'].toc() roidb_size = len(roidb)", "# Scale FPN rpn_proposals collect size (post_nms_topN) in `collect` function", "cfg.SOLVER.BASE_LR = args.lr if args.lr_decay_gamma is not None: cfg.SOLVER.GAMMA =", "rpn_proposals collect size directly propotional to the change of IMS_PER_BATCH:\\n'", "else None) try: logger.info('Training starts !') step = args.start_step for", "as misc_utils from core.config import cfg, cfg_from_file, cfg_from_list, assert_and_infer_cfg from", "= cfg.SOLVER.MAX_ITER cfg.SOLVER.STEPS = list(map(lambda x: int(x * step_scale +", "# RuntimeError: received 0 items of ancdata. Issue: pytorch/pytorch#973 rlimit", "each paramter param_names = [nonbias_param_names, bias_param_names, gn_param_names] if cfg.SOLVER.TYPE ==", "ndarrays with inconsistent length input_data[key] = list(map(Variable, input_data[key])) try: net_outputs", "== \"custom_dataset\": cfg.TRAIN.DATASETS = ('custom_data_train',) cfg.MODEL.NUM_CLASSES = args.num_classes else: raise", "import utils.net as net_utils import utils.misc as misc_utils from core.config", "### Adjust solver steps step_scale = original_batch_size / effective_batch_size old_solver_steps", "if not args.no_save: if not os.path.exists(output_dir): os.makedirs(output_dir) blob = {'cfg':", "optimizer = torch.optim.SGD(params, momentum=cfg.SOLVER.MOMENTUM) elif cfg.SOLVER.TYPE == \"Adam\": optimizer =", "--> {}\\n' ' SOLVER.MAX_ITER: {} --> {}'.format(old_solver_steps, cfg.SOLVER.STEPS, old_max_iter, cfg.SOLVER.MAX_ITER))", "* args.batch_size batchSampler = BatchSampler( sampler=MinibatchSampler(ratio_list, ratio_index), batch_size=args.batch_size, drop_last=True )", "old_solver_steps = cfg.SOLVER.STEPS old_max_iter = cfg.SOLVER.MAX_ITER cfg.SOLVER.STEPS = list(map(lambda x:", "import setup_logging from utils.timer import Timer from utils.training_stats import TrainingStats", "torch.load(load_name, map_location=lambda storage, loc: storage) net_utils.load_ckpt(maskRCNN, checkpoint['model']) if args.resume: args.start_step", "def parse_args(): \"\"\"Parse input arguments\"\"\" parser = argparse.ArgumentParser(description='Train a X-RCNN", "logger.info('save model: %s', save_name) def main(): \"\"\"Main function\"\"\" args =", "if args.optimizer is not None: cfg.SOLVER.TYPE = args.optimizer if args.lr", "args.load_ckpt logging.info(\"loading checkpoint %s\", load_name) checkpoint = torch.load(load_name, map_location=lambda storage,", "if args.no_save: return ckpt_dir = os.path.join(output_dir, 'ckpt') if not os.path.exists(ckpt_dir):", "None: cfg.SOLVER.TYPE = args.optimizer if args.lr is not None: cfg.SOLVER.BASE_LR", "not None: cfg.SOLVER.BASE_LR = args.lr if args.lr_decay_gamma is not None:", "* (cfg.SOLVER.BIAS_DOUBLE_LR + 1), 'weight_decay': cfg.SOLVER.WEIGHT_DECAY if cfg.SOLVER.BIAS_WEIGHT_DECAY else 0},", "is not None: cfg.SOLVER.TYPE = args.optimizer if args.lr is not", "0.5) print('Adjust SOLVER.STEPS and SOLVER.MAX_ITER linearly based on effective_batch_size change:\\n'", "bug in optimizer.load_state_dict on Pytorch 0.3.1. # However it's fixed", "step, train_size, maskRCNN, optimizer) except (RuntimeError, KeyboardInterrupt): del dataiterator logger.info('Save", "dataset to run!\") if args.dataset == \"coco2017\": cfg.TRAIN.DATASETS = ('coco_2014_train',)", "network') parser.add_argument( '--dataset', dest='dataset', required=True, help='Dataset to use') parser.add_argument( '--num_classes',", "step, train_size, maskRCNN, optimizer) logger.info('Save ckpt done.') stack_trace = traceback.format_exc()", "= len(cfg.SOLVER.STEPS) training_stats = TrainingStats( args, args.disp_interval, tblogger if args.use_tfboard", "parser.add_argument( '--no_save', help='do not save anything', action='store_true') parser.add_argument( '--load_ckpt', help='checkpoint", "timers = defaultdict(Timer) ### Dataset ### timers['roidb'].tic() roidb, ratio_list, ratio_index", "# However it's fixed on master. optimizer.load_state_dict(checkpoint['optimizer']) # misc_utils.load_optimizer_state_dict(optimizer, checkpoint['optimizer'])", "args.num_classes else: raise ValueError(\"Unexpected args.dataset: {}\".format(args.dataset)) cfg_from_file(args.cfg_file) if args.set_cfgs is", "pickle.dump(blob, f, pickle.HIGHEST_PROTOCOL) if args.use_tfboard: from tensorboardX import SummaryWriter #", "CHECKPOINT_PERIOD == 0: save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) #", "net_utils.update_learning_rate(optimizer, lr, lr_new) lr = optimizer.param_groups[0]['lr'] assert lr == lr_new", "* step_scale + 0.5), cfg.SOLVER.STEPS)) cfg.SOLVER.MAX_ITER = int(cfg.SOLVER.MAX_ITER * step_scale", "if 'train_size' in checkpoint: # For backward compatibility if checkpoint['train_size']", "= args.lr_decay_gamma assert_and_infer_cfg() timers = defaultdict(Timer) ### Dataset ### timers['roidb'].tic()", "lr == cfg.SOLVER.BASE_LR # Learning rate decay if decay_steps_ind <", "(args.batch_size % cfg.NUM_GPUS) == 0, \\ 'batch_size: %d, NUM_GPUS: %d'", "optimizer) logger.info('Save ckpt done.') stack_trace = traceback.format_exc() print(stack_trace) finally: if", "> 0: cfg.CUDA = True else: raise ValueError(\"Need Cuda device", "from command line arguments if args.optimizer is not None: cfg.SOLVER.TYPE", "to log training info', action='store_true') return parser.parse_args() def save_ckpt(output_dir, args,", "possible deadlock in dataloader import _init_paths # pylint: disable=unused-import import", "Pytorch 0.3.1. # However it's fixed on master. optimizer.load_state_dict(checkpoint['optimizer']) #", "in input_data: if key != 'roidb': # roidb is a", "to construct roidb', timers['roidb'].average_time) # Effective training sample size for", "policy\"\"\" import argparse import os import sys import pickle import", "lr, lr_new) lr = optimizer.param_groups[0]['lr'] assert lr == lr_new elif", "%d --> %d' % (original_batch_size, effective_batch_size)) print(' NUM_GPUS: %d -->", "('voc_2012_train',) cfg.MODEL.NUM_CLASSES = 21 elif args.dataset == \"custom_dataset\": cfg.TRAIN.DATASETS =", "of effective_batch_size old_base_lr = cfg.SOLVER.BASE_LR cfg.SOLVER.BASE_LR *= args.batch_size / original_batch_size", "args.no_save: return ckpt_dir = os.path.join(output_dir, 'ckpt') if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir)", "change linearly # For iter_size > 1, gradients are `accumulated`,", "iter_size = %d * %d' % (args.batch_size, args.iter_size)) print('Adaptive config", "tensorflow tensorboard to log training info', action='store_true') return parser.parse_args() def", "nonbias_params = [] nonbias_param_names = [] nograd_param_names = [] for", "numpy as np import yaml import torch from torch.autograd import", "from torch.autograd import Variable import torch.nn as nn import cv2", "cfg.SOLVER.BASE_LR cfg.SOLVER.BASE_LR *= args.batch_size / original_batch_size print('Adjust BASE_LR linearly according", "cfg.SOLVER.BASE_LR *= args.batch_size / original_batch_size print('Adjust BASE_LR linearly according to", "save anything', action='store_true') parser.add_argument( '--load_ckpt', help='checkpoint path to load') parser.add_argument(", "args.batch_size = original_batch_size cfg.NUM_GPUS = torch.cuda.device_count() assert (args.batch_size % cfg.NUM_GPUS)", "is not None: cfg.SOLVER.BASE_LR = args.lr if args.lr_decay_gamma is not", "checkpoint', action='store_true') parser.add_argument( '--no_save', help='do not save anything', action='store_true') parser.add_argument(", "%d' % cfg.DATA_LOADER.NUM_THREADS) ### Overwrite some solver settings from command", "dest='cuda', help='Do not use CUDA device', action='store_false') # Optimization #", "torch from torch.autograd import Variable import torch.nn as nn import", "checkpoint = torch.load(load_name, map_location=lambda storage, loc: storage) net_utils.load_ckpt(maskRCNN, checkpoint['model']) if", "step, train_size, maskRCNN, optimizer) # ---- Training ends ---- #", "as in Caffe.', default=1, type=int) parser.add_argument( '--o', dest='optimizer', help='Training optimizer.',", "gn_param_nameset: gn_params.append(value) gn_param_names.append(key) else: nonbias_params.append(value) nonbias_param_names.append(key) else: nograd_param_names.append(key) assert (gn_param_nameset", "cfg.SOLVER.MAX_ITER cfg.SOLVER.STEPS = list(map(lambda x: int(x * step_scale + 0.5),", "= torch.load(load_name, map_location=lambda storage, loc: storage) net_utils.load_ckpt(maskRCNN, checkpoint['model']) if args.resume:", "cfg.MODEL.NUM_CLASSES = 21 elif args.dataset == \"custom_dataset\": cfg.TRAIN.DATASETS = ('custom_data_train',)", "args.resume: args.start_step = checkpoint['step'] + 1 if 'train_size' in checkpoint:", "collections import defaultdict import numpy as np import yaml import", "% cfg.NUM_GPUS) == 0, \\ 'batch_size: %d, NUM_GPUS: %d' %", "training_stats.IterTic() optimizer.zero_grad() for inner_iter in range(args.iter_size): try: input_data = next(dataiterator)", "if args.set_cfgs is not None: cfg_from_list(args.set_cfgs) ### Adaptively adjust some", "model.state_dict(), 'optimizer': optimizer.state_dict()}, save_name) logger.info('save model: %s', save_name) def main():", "except (RuntimeError, KeyboardInterrupt): del dataiterator logger.info('Save ckpt on exception ...')", "save_ckpt(output_dir, args, step, train_size, model, optimizer): \"\"\"Save checkpoint\"\"\" if args.no_save:", "0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY_GN} ] # names of paramerters for each", "dataloader import _init_paths # pylint: disable=unused-import import nn as mynn", "21 elif args.dataset == \"voc2012\": cfg.TRAIN.DATASETS = ('voc_2012_train',) cfg.MODEL.NUM_CLASSES =", "sgd momentum values) logging.info(\"loading Detectron weights %s\", args.load_detectron) load_detectron_weight(maskRCNN, args.load_detectron)", "model, optimizer): \"\"\"Save checkpoint\"\"\" if args.no_save: return ckpt_dir = os.path.join(output_dir,", "minibatch=True) ### Training Setups ### args.run_name = misc_utils.get_run_name() + '_step'", "batchSampler = BatchSampler( sampler=MinibatchSampler(ratio_list, ratio_index), batch_size=args.batch_size, drop_last=True ) dataset =", "resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1])) def parse_args(): \"\"\"Parse input arguments\"\"\" parser =", "= len(roidb) logger.info('{:d} roidb entries'.format(roidb_size)) logger.info('Takes %.2f sec(s) to construct", "if args.resume: args.start_step = checkpoint['step'] + 1 if 'train_size' in", "count for training epoch. 0-indexed.', default=0, type=int) # Resume training:", "not torch.cuda.is_available(): sys.exit(\"Need a CUDA device to run the code.\")", "cfg.SOLVER.STEPS[decay_steps_ind]: logger.info('Decay the learning on step %d', step) lr_new =", "utils.net as net_utils import utils.misc as misc_utils from core.config import", "your custom dataset', default=None, type=int) parser.add_argument( '--cfg', dest='cfg_file', required=True, help='Config", "to 4', type=int) parser.add_argument( '--iter_size', help='Update once every iter_size steps,", "nonbias_param_names.append(key) else: nograd_param_names.append(key) assert (gn_param_nameset - set(nograd_param_names) - set(bias_param_names)) ==", "step count for training epoch. 0-indexed.', default=0, type=int) # Resume", "of `collect_and_distribute_fpn_rpn_proposals.py` # # post_nms_topN = int(cfg[cfg_key].RPN_POST_NMS_TOP_N * cfg.FPN.RPN_COLLECT_SCALE +", "args.iter_size)) print('Adaptive config changes:') print(' effective_batch_size: %d --> %d' %", "if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) save_name = os.path.join(ckpt_dir, 'model_step{}.pth'.format(step)) if isinstance(model,", "torch.cuda.empty_cache() if args.load_detectron: #TODO resume for detectron weights (load sgd", "misc_utils.get_output_dir(args, args.run_name) args.cfg_filename = os.path.basename(args.cfg_file) if not args.no_save: if not", "optionally testing)') parser.add_argument( '--set', dest='set_cfgs', help='Set config keys. Key value", "cfg.TRAIN.IMS_PER_BATCH original_ims_per_batch = cfg.TRAIN.IMS_PER_BATCH original_num_gpus = cfg.NUM_GPUS if args.batch_size is", "* cfg.FPN.RPN_COLLECT_SCALE + 0.5) if cfg.FPN.FPN_ON and cfg.MODEL.FASTER_RCNN: cfg.FPN.RPN_COLLECT_SCALE =", "---- # Save last checkpoint save_ckpt(output_dir, args, step, train_size, maskRCNN,", "key != 'roidb': # roidb is a list of ndarrays", "if 'bias' in key: bias_params.append(value) bias_param_names.append(key) elif key in gn_param_nameset:", "is None: decay_steps_ind = len(cfg.SOLVER.STEPS) training_stats = TrainingStats( args, args.disp_interval,", "parser.add_argument( '--o', dest='optimizer', help='Training optimizer.', default=None) parser.add_argument( '--lr', help='Base learning", "{}'.format(method)) lr_new = cfg.SOLVER.BASE_LR * warmup_factor net_utils.update_learning_rate(optimizer, lr, lr_new) lr", "your custom dataset to run!\") if args.dataset == \"coco2017\": cfg.TRAIN.DATASETS", "training_stats.UpdateIterStats(net_outputs, inner_iter) loss = net_outputs['total_loss'] loss.backward() optimizer.step() training_stats.IterToc() training_stats.LogIterStats(step, lr)", "'--load_detectron', help='path to the detectron weight pickle file') parser.add_argument( '--use_tfboard',", "training sample size for one epoch train_size = roidb_size //", "not overwrite. parser.add_argument( '--bs', dest='batch_size', help='Explicitly specify to overwrite the", "from utils.training_stats import TrainingStats # Set up logging and load", "optimizer.param_groups[0]['lr'] assert lr == lr_new decay_steps_ind += 1 training_stats.IterTic() optimizer.zero_grad()", "training_stats = TrainingStats( args, args.disp_interval, tblogger if args.use_tfboard and not", "BatchSampler, collate_minibatch from modeling.model_builder import Generalized_RCNN from utils.detectron_weight_helper import load_detectron_weight", "= next(dataiterator) for key in input_data: if key != 'roidb':", "optimizer = torch.optim.Adam(params) ### Load checkpoint if args.load_ckpt: load_name =", "cfg.SOLVER.GAMMA = args.lr_decay_gamma assert_and_infer_cfg() timers = defaultdict(Timer) ### Dataset ###", "warmup_factor net_utils.update_learning_rate(optimizer, lr, lr_new) lr = optimizer.param_groups[0]['lr'] assert lr ==", "# on batch_size instead of effective_batch_size old_base_lr = cfg.SOLVER.BASE_LR cfg.SOLVER.BASE_LR", "input_data = next(dataiterator) for key in input_data: if key !=", "overwrite the value comed from cfg_file.', type=int) parser.add_argument( '--nw', dest='num_workers',", "Loop ### maskRCNN.train() CHECKPOINT_PERIOD = int(cfg.TRAIN.SNAPSHOT_ITERS / cfg.NUM_GPUS) # Set", "_init_paths # pylint: disable=unused-import import nn as mynn import utils.net", "cfg.SOLVER.WARM_UP_ITERS: method = cfg.SOLVER.WARM_UP_METHOD if method == 'constant': warmup_factor =", "cv2 cv2.setNumThreads(0) # pytorch issue 1355: possible deadlock in dataloader", "'--dataset', dest='dataset', required=True, help='Dataset to use') parser.add_argument( '--num_classes', dest='num_classes', help='Number", "# reorder the params in optimizer checkpoint's params_groups if needed", "= misc_utils.get_run_name() + '_step' output_dir = misc_utils.get_output_dir(args, args.run_name) args.cfg_filename =", "args.no_save else None) try: logger.info('Training starts !') step = args.start_step", "old_base_lr = cfg.SOLVER.BASE_LR cfg.SOLVER.BASE_LR *= args.batch_size / original_batch_size print('Adjust BASE_LR", "= int(cfg.TRAIN.SNAPSHOT_ITERS / cfg.NUM_GPUS) # Set index for decay steps", "parser.add_argument( '--num_classes', dest='num_classes', help='Number of classes in your custom dataset',", "raise KeyError('Unknown SOLVER.WARM_UP_METHOD: {}'.format(method)) lr_new = cfg.SOLVER.BASE_LR * warmup_factor net_utils.update_learning_rate(optimizer,", "torch.optim.SGD(params, momentum=cfg.SOLVER.MOMENTUM) elif cfg.SOLVER.TYPE == \"Adam\": optimizer = torch.optim.Adam(params) ###", "tensorboard to log training info', action='store_true') return parser.parse_args() def save_ckpt(output_dir,", "= model.state_dict() torch.save({ 'step': step, 'train_size': train_size, 'batch_size': args.batch_size, 'model':", "elif args.dataset == \"voc2012\": cfg.TRAIN.DATASETS = ('voc_2012_train',) cfg.MODEL.NUM_CLASSES = 21", "step, train_size, model, optimizer): \"\"\"Save checkpoint\"\"\" if args.no_save: return ckpt_dir", "(original_ims_per_batch, cfg.TRAIN.IMS_PER_BATCH)) ### Adjust learning based on batch size change", "isinstance(model, mynn.DataParallel): model = model.module model_state_dict = model.state_dict() torch.save({ 'step':", "the start of training params = [ {'params': nonbias_params, 'lr':", "parser.add_argument( '--load_ckpt', help='checkpoint path to load') parser.add_argument( '--load_detectron', help='path to", "setup_logging(__name__) logging.getLogger('roi_data.loader').setLevel(logging.INFO) # RuntimeError: received 0 items of ancdata. Issue:", "print('Adjust BASE_LR linearly according to batch_size change:\\n' ' BASE_LR: {}", "based on batch size change linearly # For iter_size >", "decay rate.', default=None, type=float) # Epoch parser.add_argument( '--start_step', help='Starting step", "params_groups if needed # misc_utils.ensure_optimizer_ckpt_params_order(param_names, checkpoint) # There is a", "' BASE_LR: {} --> {}'.format(old_base_lr, cfg.SOLVER.BASE_LR)) ### Adjust solver steps", "# post_nms_topN = int(cfg[cfg_key].RPN_POST_NMS_TOP_N * cfg.FPN.RPN_COLLECT_SCALE + 0.5) if cfg.FPN.FPN_ON", "* iter_size = %d * %d' % (args.batch_size, args.iter_size)) print('Adaptive", "in checkpoint: # For backward compatibility if checkpoint['train_size'] != train_size:", "\"SGD\": optimizer = torch.optim.SGD(params, momentum=cfg.SOLVER.MOMENTUM) elif cfg.SOLVER.TYPE == \"Adam\": optimizer", "nonbias_params.append(value) nonbias_param_names.append(key) else: nograd_param_names.append(key) assert (gn_param_nameset - set(nograd_param_names) - set(bias_param_names))", "do not overwrite. parser.add_argument( '--bs', dest='batch_size', help='Explicitly specify to overwrite", "parser.add_argument( '--start_step', help='Starting step count for training epoch. 0-indexed.', default=0,", "keys. Key value sequence seperate by whitespace.' 'e.g. [key] [value]", "Adjust learning based on batch size change linearly # For", "ValueError(\"Need Cuda device to run !\") if args.dataset == \"custom_dataset\"", "int(cfg.SOLVER.MAX_ITER * step_scale + 0.5) print('Adjust SOLVER.STEPS and SOLVER.MAX_ITER linearly", "model.module model_state_dict = model.state_dict() torch.save({ 'step': step, 'train_size': train_size, 'batch_size':", "if step < cfg.SOLVER.WARM_UP_ITERS: method = cfg.SOLVER.WARM_UP_METHOD if method ==", "[key] [value]', default=[], nargs='+') parser.add_argument( '--disp_interval', help='Display training info every", "' SOLVER.STEPS: {} --> {}\\n' ' SOLVER.MAX_ITER: {} --> {}'.format(old_solver_steps,", "args.no_save: if not os.path.exists(output_dir): os.makedirs(output_dir) blob = {'cfg': yaml.dump(cfg), 'args':", "per epoch parser.add_argument( '--resume', help='resume to training on a checkpoint',", "values) logging.info(\"loading Detectron weights %s\", args.load_detectron) load_detectron_weight(maskRCNN, args.load_detectron) lr =", "a dummy value to be set properly at the start", "print('effective_batch_size = batch_size * iter_size = %d * %d' %", "input_data = next(dataiterator) except StopIteration: dataiterator = iter(dataloader) input_data =", "in gn_param_nameset: gn_params.append(value) gn_param_names.append(key) else: nonbias_params.append(value) nonbias_param_names.append(key) else: nograd_param_names.append(key) assert", "collect size (post_nms_topN) in `collect` function # of `collect_and_distribute_fpn_rpn_proposals.py` #", "%d --> %d' % (original_num_gpus, cfg.NUM_GPUS)) print(' IMS_PER_BATCH: %d -->", "Set index for decay steps decay_steps_ind = None for i", "--> %d' % (original_batch_size, effective_batch_size)) print(' NUM_GPUS: %d --> %d'", "of training params = [ {'params': nonbias_params, 'lr': 0, 'weight_decay':", "SOLVER.STEPS: {} --> {}\\n' ' SOLVER.MAX_ITER: {} --> {}'.format(old_solver_steps, cfg.SOLVER.STEPS,", "args.lr_decay_gamma assert_and_infer_cfg() timers = defaultdict(Timer) ### Dataset ### timers['roidb'].tic() roidb,", "= args.start_step for step in range(args.start_step, cfg.SOLVER.MAX_ITER): # Warm up", "= cfg.SOLVER.WARM_UP_FACTOR elif method == 'linear': alpha = step /", "args.optimizer if args.lr is not None: cfg.SOLVER.BASE_LR = args.lr if", "settings from command line arguments if args.optimizer is not None:", "cfg.CUDA = True else: raise ValueError(\"Need Cuda device to run", "= step / cfg.SOLVER.WARM_UP_ITERS warmup_factor = cfg.SOLVER.WARM_UP_FACTOR * (1 -", "mynn.DataParallel): model = model.module model_state_dict = model.state_dict() torch.save({ 'step': step,", "gn_param_names.append(key) else: nonbias_params.append(value) nonbias_param_names.append(key) else: nograd_param_names.append(key) assert (gn_param_nameset - set(nograd_param_names)", "rate decay if decay_steps_ind < len(cfg.SOLVER.STEPS) and \\ step ==", "map_location=lambda storage, loc: storage) net_utils.load_ckpt(maskRCNN, checkpoint['model']) if args.resume: args.start_step =", "1 training_stats.IterTic() optimizer.zero_grad() for inner_iter in range(args.iter_size): try: input_data =", "in config file # or values set by set_cfgs. `None`", "import numpy as np import yaml import torch from torch.autograd", "continue training_stats.UpdateIterStats(net_outputs, inner_iter) loss = net_outputs['total_loss'] loss.backward() optimizer.step() training_stats.IterToc() training_stats.LogIterStats(step,", "IMS_PER_BATCH:\\n' ' cfg.FPN.RPN_COLLECT_SCALE: {}'.format(cfg.FPN.RPN_COLLECT_SCALE)) if args.num_workers is not None: cfg.DATA_LOADER.NUM_THREADS", "= RoiDataLoader( roidb, cfg.MODEL.NUM_CLASSES, training=True) dataloader = torch.utils.data.DataLoader( dataset, batch_sampler=batchSampler,", "\"custom_dataset\" and args.num_classes is None: raise ValueError(\"Need number of classes", "the detectron weight pickle file') parser.add_argument( '--use_tfboard', help='Use tensorflow tensorboard", "Generalized_RCNN() if cfg.CUDA: maskRCNN.cuda() ### Optimizer ### gn_param_nameset = set()", "lr_new = cfg.SOLVER.BASE_LR * warmup_factor net_utils.update_learning_rate(optimizer, lr, lr_new) lr =", "'--use_tfboard', help='Use tensorflow tensorboard to log training info', action='store_true') return", "for i in range(1, len(cfg.SOLVER.STEPS)): if cfg.SOLVER.STEPS[i] >= args.start_step: decay_steps_ind", "print('Adaptive config changes:') print(' effective_batch_size: %d --> %d' % (original_batch_size,", "same iterations per epoch parser.add_argument( '--resume', help='resume to training on", "original_batch_size / effective_batch_size old_solver_steps = cfg.SOLVER.STEPS old_max_iter = cfg.SOLVER.MAX_ITER cfg.SOLVER.STEPS", "traceback.format_exc() print(stack_trace) finally: if args.use_tfboard and not args.no_save: tblogger.close() if", "### Optimizer ### gn_param_nameset = set() for name, module in", "args.cuda or cfg.NUM_GPUS > 0: cfg.CUDA = True else: raise", "if args.dataset == \"custom_dataset\" and args.num_classes is None: raise ValueError(\"Need", "master. optimizer.load_state_dict(checkpoint['optimizer']) # misc_utils.load_optimizer_state_dict(optimizer, checkpoint['optimizer']) del checkpoint torch.cuda.empty_cache() if args.load_detectron:", "{}'.format(old_solver_steps, cfg.SOLVER.STEPS, old_max_iter, cfg.SOLVER.MAX_ITER)) # Scale FPN rpn_proposals collect size", "= [] for key, value in maskRCNN.named_parameters(): if value.requires_grad: if", "cfg.SOLVER.STEPS, old_max_iter, cfg.SOLVER.MAX_ITER)) # Scale FPN rpn_proposals collect size (post_nms_topN)", "batch size change linearly # For iter_size > 1, gradients", ">= args.start_step: decay_steps_ind = i break if decay_steps_ind is None:", "= torch.utils.data.DataLoader( dataset, batch_sampler=batchSampler, num_workers=cfg.DATA_LOADER.NUM_THREADS, collate_fn=collate_minibatch) dataiterator = iter(dataloader) ###", "value.requires_grad: if 'bias' in key: bias_params.append(value) bias_param_names.append(key) elif key in", "model_state_dict = model.state_dict() torch.save({ 'step': step, 'train_size': train_size, 'batch_size': args.batch_size,", "'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY_GN} ] # names of paramerters for", "decay_steps_ind = None for i in range(1, len(cfg.SOLVER.STEPS)): if cfg.SOLVER.STEPS[i]", "== \"SGD\": optimizer = torch.optim.SGD(params, momentum=cfg.SOLVER.MOMENTUM) elif cfg.SOLVER.TYPE == \"Adam\":", "Effective training sample size for one epoch train_size = roidb_size", "(args.batch_size, cfg.NUM_GPUS) cfg.TRAIN.IMS_PER_BATCH = args.batch_size // cfg.NUM_GPUS effective_batch_size = args.iter_size", "not None: cfg_from_list(args.set_cfgs) ### Adaptively adjust some configs ### original_batch_size", "sys import pickle import resource import traceback import logging from", "args.dataset == \"custom_dataset\": cfg.TRAIN.DATASETS = ('custom_data_train',) cfg.MODEL.NUM_CLASSES = args.num_classes else:", "import _init_paths # pylint: disable=unused-import import nn as mynn import", "received 0 items of ancdata. Issue: pytorch/pytorch#973 rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)", "help='Training optimizer.', default=None) parser.add_argument( '--lr', help='Base learning rate.', default=None, type=float)", "requires same iterations per epoch parser.add_argument( '--resume', help='resume to training", "'--load_ckpt', help='checkpoint path to load') parser.add_argument( '--load_detectron', help='path to the", "configs ### original_batch_size = cfg.NUM_GPUS * cfg.TRAIN.IMS_PER_BATCH original_ims_per_batch = cfg.TRAIN.IMS_PER_BATCH", "* warmup_factor net_utils.update_learning_rate(optimizer, lr, lr_new) lr = optimizer.param_groups[0]['lr'] assert lr", "bias_param_names = [] nonbias_params = [] nonbias_param_names = [] nograd_param_names", "names of paramerters for each paramter param_names = [nonbias_param_names, bias_param_names,", "paramter param_names = [nonbias_param_names, bias_param_names, gn_param_names] if cfg.SOLVER.TYPE == \"SGD\":", "modeling.model_builder import Generalized_RCNN from utils.detectron_weight_helper import load_detectron_weight from utils.logging import", "i in range(1, len(cfg.SOLVER.STEPS)): if cfg.SOLVER.STEPS[i] >= args.start_step: decay_steps_ind =", "run !\") if args.dataset == \"custom_dataset\" and args.num_classes is None:", "'batch_size': args.batch_size, 'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, save_name) logger.info('save model: %s',", "ends ---- # Save last checkpoint save_ckpt(output_dir, args, step, train_size,", "function # of `collect_and_distribute_fpn_rpn_proposals.py` # # post_nms_topN = int(cfg[cfg_key].RPN_POST_NMS_TOP_N *", "checkpoint: # For backward compatibility if checkpoint['train_size'] != train_size: print('train_size", "cfg.TRAIN.DATASETS = ('custom_data_train',) cfg.MODEL.NUM_CLASSES = args.num_classes else: raise ValueError(\"Unexpected args.dataset:", "= os.path.basename(args.cfg_file) if not args.no_save: if not os.path.exists(output_dir): os.makedirs(output_dir) blob", "KeyError('Unknown SOLVER.WARM_UP_METHOD: {}'.format(method)) lr_new = cfg.SOLVER.BASE_LR * warmup_factor net_utils.update_learning_rate(optimizer, lr,", "if cfg.SOLVER.BIAS_WEIGHT_DECAY else 0}, {'params': gn_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY_GN}", "on batch_size instead of effective_batch_size old_base_lr = cfg.SOLVER.BASE_LR cfg.SOLVER.BASE_LR *=", "from roi_data.loader import RoiDataLoader, MinibatchSampler, BatchSampler, collate_minibatch from modeling.model_builder import", "assert (gn_param_nameset - set(nograd_param_names) - set(bias_param_names)) == set(gn_param_names) # Learning", "method = cfg.SOLVER.WARM_UP_METHOD if method == 'constant': warmup_factor = cfg.SOLVER.WARM_UP_FACTOR", "[] bias_param_names = [] nonbias_params = [] nonbias_param_names = []", "on exception ...') save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) logger.info('Save", "combined_roidb_for_training( cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES) timers['roidb'].toc() roidb_size = len(roidb) logger.info('{:d} roidb entries'.format(roidb_size))", "os.makedirs(output_dir) blob = {'cfg': yaml.dump(cfg), 'args': args} with open(os.path.join(output_dir, 'config_and_args.pkl'),", "save_name) def main(): \"\"\"Main function\"\"\" args = parse_args() print('Called with", "cfg.DATA_LOADER.NUM_THREADS = args.num_workers print('Number of data loading threads: %d' %", "inner_iter in range(args.iter_size): try: input_data = next(dataiterator) except StopIteration: dataiterator", "in key: bias_params.append(value) bias_param_names.append(key) elif key in gn_param_nameset: gn_params.append(value) gn_param_names.append(key)", "4 elif args.dataset == \"keypoints_coco2017\": cfg.TRAIN.DATASETS = ('keypoints_coco_2017_train',) cfg.MODEL.NUM_CLASSES =", "import traceback import logging from collections import defaultdict import numpy", "'train_size' in checkpoint: # For backward compatibility if checkpoint['train_size'] !=", "!= 'roidb': # roidb is a list of ndarrays with", "BatchSampler( sampler=MinibatchSampler(ratio_list, ratio_index), batch_size=args.batch_size, drop_last=True ) dataset = RoiDataLoader( roidb,", "= cfg.SOLVER.WARM_UP_FACTOR * (1 - alpha) + alpha else: raise", "config options logger = setup_logging(__name__) logging.getLogger('roi_data.loader').setLevel(logging.INFO) # RuntimeError: received 0", "help='Display training info every N iterations', default=20, type=int) parser.add_argument( '--no_cuda',", "% (original_ims_per_batch, cfg.TRAIN.IMS_PER_BATCH)) ### Adjust learning based on batch size", "'--disp_interval', help='Display training info every N iterations', default=20, type=int) parser.add_argument(", "if args.load_ckpt: load_name = args.load_ckpt logging.info(\"loading checkpoint %s\", load_name) checkpoint", "cfg.FPN.RPN_COLLECT_SCALE = cfg.TRAIN.IMS_PER_BATCH / original_ims_per_batch print('Scale FPN rpn_proposals collect size", "compatibility if checkpoint['train_size'] != train_size: print('train_size value: %d different from", "There is a bug in optimizer.load_state_dict on Pytorch 0.3.1. #", "custom dataset', default=None, type=int) parser.add_argument( '--cfg', dest='cfg_file', required=True, help='Config file", "args.optimizer is not None: cfg.SOLVER.TYPE = args.optimizer if args.lr is", "checkpoint\"\"\" if args.no_save: return ckpt_dir = os.path.join(output_dir, 'ckpt') if not", "KeyboardInterrupt): del dataiterator logger.info('Save ckpt on exception ...') save_ckpt(output_dir, args,", "if cfg.FPN.FPN_ON and cfg.MODEL.FASTER_RCNN: cfg.FPN.RPN_COLLECT_SCALE = cfg.TRAIN.IMS_PER_BATCH / original_ims_per_batch print('Scale", "properly at the start of training params = [ {'params':", "args:') print(args) if not torch.cuda.is_available(): sys.exit(\"Need a CUDA device to", "pytorch issue 1355: possible deadlock in dataloader import _init_paths #", "= 21 elif args.dataset == \"custom_dataset\": cfg.TRAIN.DATASETS = ('custom_data_train',) cfg.MODEL.NUM_CLASSES", "'--lr_decay_gamma', help='Learning rate decay rate.', default=None, type=float) # Epoch parser.add_argument(", "dataiterator logger.info('Save ckpt on exception ...') save_ckpt(output_dir, args, step, train_size,", "dest='num_classes', help='Number of classes in your custom dataset', default=None, type=int)", "bias_param_names, gn_param_names] if cfg.SOLVER.TYPE == \"SGD\": optimizer = torch.optim.SGD(params, momentum=cfg.SOLVER.MOMENTUM)", "cfg.MODEL.NUM_CLASSES = 2 elif args.dataset == \"voc2007\": cfg.TRAIN.DATASETS = ('voc_2007_train',)", "args.dataset == \"custom_dataset\" and args.num_classes is None: raise ValueError(\"Need number", "if cfg.CUDA: maskRCNN.cuda() ### Optimizer ### gn_param_nameset = set() for", "(load sgd momentum values) logging.info(\"loading Detectron weights %s\", args.load_detectron) load_detectron_weight(maskRCNN,", "Tensorboard logger tblogger = SummaryWriter(output_dir) ### Training Loop ### maskRCNN.train()", "[key] [value] [key] [value]', default=[], nargs='+') parser.add_argument( '--disp_interval', help='Display training", "lr_new = lr * cfg.SOLVER.GAMMA net_utils.update_learning_rate(optimizer, lr, lr_new) lr =", "up logging and load config options logger = setup_logging(__name__) logging.getLogger('roi_data.loader').setLevel(logging.INFO)", "adjust some configs ### original_batch_size = cfg.NUM_GPUS * cfg.TRAIN.IMS_PER_BATCH original_ims_per_batch", "= cfg.SOLVER.BASE_LR * warmup_factor net_utils.update_learning_rate(optimizer, lr, lr_new) lr = optimizer.param_groups[0]['lr']", "a CUDA device to run the code.\") if args.cuda or", "in Caffe.', default=1, type=int) parser.add_argument( '--o', dest='optimizer', help='Training optimizer.', default=None)", "args.batch_size / original_batch_size print('Adjust BASE_LR linearly according to batch_size change:\\n'", "= list(map(lambda x: int(x * step_scale + 0.5), cfg.SOLVER.STEPS)) cfg.SOLVER.MAX_ITER", "nn import cv2 cv2.setNumThreads(0) # pytorch issue 1355: possible deadlock", "last checkpoint save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) except (RuntimeError,", "checkpoint['train_size'] != train_size: print('train_size value: %d different from the one", "# Optimization # These options has the highest prioity and", "'args': args} with open(os.path.join(output_dir, 'config_and_args.pkl'), 'wb') as f: pickle.dump(blob, f,", "help='Starting step count for training epoch. 0-indexed.', default=0, type=int) #", "Learning rate decay if decay_steps_ind < len(cfg.SOLVER.STEPS) and \\ step", "fixed on master. optimizer.load_state_dict(checkpoint['optimizer']) # misc_utils.load_optimizer_state_dict(optimizer, checkpoint['optimizer']) del checkpoint torch.cuda.empty_cache()", "### Adaptively adjust some configs ### original_batch_size = cfg.NUM_GPUS *", "> 1, gradients are `accumulated`, so lr is scaled based", "parse_args() print('Called with args:') print(args) if not torch.cuda.is_available(): sys.exit(\"Need a", "= os.path.join(output_dir, 'ckpt') if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) save_name = os.path.join(ckpt_dir,", "detectron weights (load sgd momentum values) logging.info(\"loading Detectron weights %s\",", "%d * %d' % (args.batch_size, args.iter_size)) print('Adaptive config changes:') print('", "from datasets.roidb import combined_roidb_for_training from roi_data.loader import RoiDataLoader, MinibatchSampler, BatchSampler,", "== 'linear': alpha = step / cfg.SOLVER.WARM_UP_ITERS warmup_factor = cfg.SOLVER.WARM_UP_FACTOR", "if cfg.SOLVER.STEPS[i] >= args.start_step: decay_steps_ind = i break if decay_steps_ind", "can overwrite the values in config file # or values", "FPN rpn_proposals collect size directly propotional to the change of", "0.5), cfg.SOLVER.STEPS)) cfg.SOLVER.MAX_ITER = int(cfg.SOLVER.MAX_ITER * step_scale + 0.5) print('Adjust", "'constant': warmup_factor = cfg.SOLVER.WARM_UP_FACTOR elif method == 'linear': alpha =", "maskRCNN.named_parameters(): if value.requires_grad: if 'bias' in key: bias_params.append(value) bias_param_names.append(key) elif", "of IMS_PER_BATCH:\\n' ' cfg.FPN.RPN_COLLECT_SCALE: {}'.format(cfg.FPN.RPN_COLLECT_SCALE)) if args.num_workers is not None:", "training params = [ {'params': nonbias_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY},", "linearly according to batch_size change:\\n' ' BASE_LR: {} --> {}'.format(old_base_lr,", "Generalized_RCNN from utils.detectron_weight_helper import load_detectron_weight from utils.logging import setup_logging from", "momentum=cfg.SOLVER.MOMENTUM) elif cfg.SOLVER.TYPE == \"Adam\": optimizer = torch.optim.Adam(params) ### Load", "to training on a checkpoint', action='store_true') parser.add_argument( '--no_save', help='do not", "= torch.cuda.device_count() assert (args.batch_size % cfg.NUM_GPUS) == 0, \\ 'batch_size:", "cfg.SOLVER.STEPS old_max_iter = cfg.SOLVER.MAX_ITER cfg.SOLVER.STEPS = list(map(lambda x: int(x *", "step < cfg.SOLVER.WARM_UP_ITERS: method = cfg.SOLVER.WARM_UP_METHOD if method == 'constant':", "/ cfg.SOLVER.WARM_UP_ITERS warmup_factor = cfg.SOLVER.WARM_UP_FACTOR * (1 - alpha) +", "a X-RCNN network') parser.add_argument( '--dataset', dest='dataset', required=True, help='Dataset to use')", "on Pytorch 0.3.1. # However it's fixed on master. optimizer.load_state_dict(checkpoint['optimizer'])", "'roidb'], minibatch=True) ### Training Setups ### args.run_name = misc_utils.get_run_name() +", "== \"Adam\": optimizer = torch.optim.Adam(params) ### Load checkpoint if args.load_ckpt:", "load_name) checkpoint = torch.load(load_name, map_location=lambda storage, loc: storage) net_utils.load_ckpt(maskRCNN, checkpoint['model'])", "input_data: if key != 'roidb': # roidb is a list", "= int(cfg[cfg_key].RPN_POST_NMS_TOP_N * cfg.FPN.RPN_COLLECT_SCALE + 0.5) if cfg.FPN.FPN_ON and cfg.MODEL.FASTER_RCNN:", "= [nonbias_param_names, bias_param_names, gn_param_names] if cfg.SOLVER.TYPE == \"SGD\": optimizer =", "elif method == 'linear': alpha = step / cfg.SOLVER.WARM_UP_ITERS warmup_factor", "args.dataset == \"keypoints_coco2017\": cfg.TRAIN.DATASETS = ('keypoints_coco_2017_train',) cfg.MODEL.NUM_CLASSES = 2 elif", "or values set by set_cfgs. `None` means do not overwrite.", "+ 0.5), cfg.SOLVER.STEPS)) cfg.SOLVER.MAX_ITER = int(cfg.SOLVER.MAX_ITER * step_scale + 0.5)", "'optimizer': optimizer.state_dict()}, save_name) logger.info('save model: %s', save_name) def main(): \"\"\"Main", "cfg.FPN.FPN_ON and cfg.MODEL.FASTER_RCNN: cfg.FPN.RPN_COLLECT_SCALE = cfg.TRAIN.IMS_PER_BATCH / original_ims_per_batch print('Scale FPN", "cfg.SOLVER.STEPS)) cfg.SOLVER.MAX_ITER = int(cfg.SOLVER.MAX_ITER * step_scale + 0.5) print('Adjust SOLVER.STEPS", "= cfg.SOLVER.STEPS old_max_iter = cfg.SOLVER.MAX_ITER cfg.SOLVER.STEPS = list(map(lambda x: int(x", "{} --> {}'.format(old_solver_steps, cfg.SOLVER.STEPS, old_max_iter, cfg.SOLVER.MAX_ITER)) # Scale FPN rpn_proposals", "{} --> {}\\n' ' SOLVER.MAX_ITER: {} --> {}'.format(old_solver_steps, cfg.SOLVER.STEPS, old_max_iter,", "stack_trace = traceback.format_exc() print(stack_trace) finally: if args.use_tfboard and not args.no_save:", "args.batch_size batchSampler = BatchSampler( sampler=MinibatchSampler(ratio_list, ratio_index), batch_size=args.batch_size, drop_last=True ) dataset", "steps decay_steps_ind = None for i in range(1, len(cfg.SOLVER.STEPS)): if", "= ('custom_data_train',) cfg.MODEL.NUM_CLASSES = args.num_classes else: raise ValueError(\"Unexpected args.dataset: {}\".format(args.dataset))", "help='do not save anything', action='store_true') parser.add_argument( '--load_ckpt', help='checkpoint path to", "function\"\"\" args = parse_args() print('Called with args:') print(args) if not", "default=[], nargs='+') parser.add_argument( '--disp_interval', help='Display training info every N iterations',", "{'params': nonbias_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY}, {'params': bias_params, 'lr': 0", "args, args.disp_interval, tblogger if args.use_tfboard and not args.no_save else None)", "ratio_index = combined_roidb_for_training( cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES) timers['roidb'].toc() roidb_size = len(roidb) logger.info('{:d}", "('custom_data_train',) cfg.MODEL.NUM_CLASSES = args.num_classes else: raise ValueError(\"Unexpected args.dataset: {}\".format(args.dataset)) cfg_from_file(args.cfg_file)", "nonbias_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY}, {'params': bias_params, 'lr': 0 *", "maskRCNN = Generalized_RCNN() if cfg.CUDA: maskRCNN.cuda() ### Optimizer ### gn_param_nameset", "optimizer.param_groups[0]['lr'] assert lr == cfg.SOLVER.BASE_LR # Learning rate decay if", "the highest prioity and can overwrite the values in config", "from utils.timer import Timer from utils.training_stats import TrainingStats # Set", "value comed from cfg_file.', type=int) parser.add_argument( '--nw', dest='num_workers', help='Explicitly specify", "epoch. 0-indexed.', default=0, type=int) # Resume training: requires same iterations", "from core.config import cfg, cfg_from_file, cfg_from_list, assert_and_infer_cfg from datasets.roidb import", "print('Called with args:') print(args) if not torch.cuda.is_available(): sys.exit(\"Need a CUDA", "of ndarrays with inconsistent length input_data[key] = list(map(Variable, input_data[key])) try:", "Key value sequence seperate by whitespace.' 'e.g. [key] [value] [key]", "detectron weight pickle file') parser.add_argument( '--use_tfboard', help='Use tensorflow tensorboard to", "1 if 'train_size' in checkpoint: # For backward compatibility if", "alpha = step / cfg.SOLVER.WARM_UP_ITERS warmup_factor = cfg.SOLVER.WARM_UP_FACTOR * (1", "for inner_iter in range(args.iter_size): try: input_data = next(dataiterator) except StopIteration:", "len(roidb) logger.info('{:d} roidb entries'.format(roidb_size)) logger.info('Takes %.2f sec(s) to construct roidb',", "print('Number of data loading threads: %d' % cfg.DATA_LOADER.NUM_THREADS) ### Overwrite", "so lr is scaled based # on batch_size instead of", "--> %d' % (original_ims_per_batch, cfg.TRAIN.IMS_PER_BATCH)) ### Adjust learning based on", "'--o', dest='optimizer', help='Training optimizer.', default=None) parser.add_argument( '--lr', help='Base learning rate.',", "% cfg.DATA_LOADER.NUM_THREADS) ### Overwrite some solver settings from command line", "parser.add_argument( '--nw', dest='num_workers', help='Explicitly specify to overwrite number of workers", "effective_batch_size)) print(' NUM_GPUS: %d --> %d' % (original_num_gpus, cfg.NUM_GPUS)) print('", "load config options logger = setup_logging(__name__) logging.getLogger('roi_data.loader').setLevel(logging.INFO) # RuntimeError: received", "'batch_size: %d, NUM_GPUS: %d' % (args.batch_size, cfg.NUM_GPUS) cfg.TRAIN.IMS_PER_BATCH = args.batch_size", "cfg.SOLVER.TYPE == \"SGD\": optimizer = torch.optim.SGD(params, momentum=cfg.SOLVER.MOMENTUM) elif cfg.SOLVER.TYPE ==", "nn as mynn import utils.net as net_utils import utils.misc as", "for name, module in maskRCNN.named_modules(): if isinstance(module, nn.GroupNorm): gn_param_nameset.add(name+'.weight') gn_param_nameset.add(name+'.bias')", "True else: raise ValueError(\"Need Cuda device to run !\") if", "# misc_utils.ensure_optimizer_ckpt_params_order(param_names, checkpoint) # There is a bug in optimizer.load_state_dict", "'config_and_args.pkl'), 'wb') as f: pickle.dump(blob, f, pickle.HIGHEST_PROTOCOL) if args.use_tfboard: from", "cfg_from_file, cfg_from_list, assert_and_infer_cfg from datasets.roidb import combined_roidb_for_training from roi_data.loader import", "info', action='store_true') return parser.parse_args() def save_ckpt(output_dir, args, step, train_size, model,", "'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, save_name) logger.info('save model: %s', save_name) def", "parser.add_argument( '--cfg', dest='cfg_file', required=True, help='Config file for training (and optionally", "classes in your custom dataset', default=None, type=int) parser.add_argument( '--cfg', dest='cfg_file',", "optimizer.param_groups[0]['lr'] # lr of non-bias parameters, for commmand line outputs.", "0: save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) # ---- Training", "cfg.MODEL.FASTER_RCNN: cfg.FPN.RPN_COLLECT_SCALE = cfg.TRAIN.IMS_PER_BATCH / original_ims_per_batch print('Scale FPN rpn_proposals collect", "'ckpt') if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) save_name = os.path.join(ckpt_dir, 'model_step{}.pth'.format(step)) if", "0 * (cfg.SOLVER.BIAS_DOUBLE_LR + 1), 'weight_decay': cfg.SOLVER.WEIGHT_DECAY if cfg.SOLVER.BIAS_WEIGHT_DECAY else", "step == cfg.SOLVER.STEPS[decay_steps_ind]: logger.info('Decay the learning on step %d', step)", "# misc_utils.load_optimizer_state_dict(optimizer, checkpoint['optimizer']) del checkpoint torch.cuda.empty_cache() if args.load_detectron: #TODO resume", "`None` means do not overwrite. parser.add_argument( '--bs', dest='batch_size', help='Explicitly specify", "* cfg.TRAIN.IMS_PER_BATCH original_ims_per_batch = cfg.TRAIN.IMS_PER_BATCH original_num_gpus = cfg.NUM_GPUS if args.batch_size", "argparse import os import sys import pickle import resource import", "if cfg.SOLVER.TYPE == \"SGD\": optimizer = torch.optim.SGD(params, momentum=cfg.SOLVER.MOMENTUM) elif cfg.SOLVER.TYPE", "model.state_dict() torch.save({ 'step': step, 'train_size': train_size, 'batch_size': args.batch_size, 'model': model.state_dict(),", "'--cfg', dest='cfg_file', required=True, help='Config file for training (and optionally testing)')", "load') parser.add_argument( '--load_detectron', help='path to the detectron weight pickle file')", "args.dataset == \"coco2017\": cfg.TRAIN.DATASETS = ('coco_2014_train',) cfg.MODEL.NUM_CLASSES = 4 elif", "set() for name, module in maskRCNN.named_modules(): if isinstance(module, nn.GroupNorm): gn_param_nameset.add(name+'.weight')", "cfg.SOLVER.STEPS = list(map(lambda x: int(x * step_scale + 0.5), cfg.SOLVER.STEPS))", "# These options has the highest prioity and can overwrite", "once every iter_size steps, as in Caffe.', default=1, type=int) parser.add_argument(", "Setups ### args.run_name = misc_utils.get_run_name() + '_step' output_dir = misc_utils.get_output_dir(args,", "= SummaryWriter(output_dir) ### Training Loop ### maskRCNN.train() CHECKPOINT_PERIOD = int(cfg.TRAIN.SNAPSHOT_ITERS", "torch.autograd import Variable import torch.nn as nn import cv2 cv2.setNumThreads(0)", "from cfg_file.', type=int) parser.add_argument( '--nw', dest='num_workers', help='Explicitly specify to overwrite", "maskRCNN.cuda() ### Optimizer ### gn_param_nameset = set() for name, module", "rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1])) def parse_args(): \"\"\"Parse input", "help='Config file for training (and optionally testing)') parser.add_argument( '--set', dest='set_cfgs',", "% (args.batch_size, cfg.NUM_GPUS) cfg.TRAIN.IMS_PER_BATCH = args.batch_size // cfg.NUM_GPUS effective_batch_size =", "N iterations', default=20, type=int) parser.add_argument( '--no_cuda', dest='cuda', help='Do not use", "del checkpoint torch.cuda.empty_cache() if args.load_detectron: #TODO resume for detectron weights", "args.lr is not None: cfg.SOLVER.BASE_LR = args.lr if args.lr_decay_gamma is", "action='store_false') # Optimization # These options has the highest prioity", "mynn import utils.net as net_utils import utils.misc as misc_utils from", "training (and optionally testing)') parser.add_argument( '--set', dest='set_cfgs', help='Set config keys.", "step %d', step) lr_new = lr * cfg.SOLVER.GAMMA net_utils.update_learning_rate(optimizer, lr,", "nargs='+') parser.add_argument( '--disp_interval', help='Display training info every N iterations', default=20,", "values in config file # or values set by set_cfgs.", "len(cfg.SOLVER.STEPS)): if cfg.SOLVER.STEPS[i] >= args.start_step: decay_steps_ind = i break if", "cfg.MODEL.NUM_CLASSES = args.num_classes else: raise ValueError(\"Unexpected args.dataset: {}\".format(args.dataset)) cfg_from_file(args.cfg_file) if", "if isinstance(module, nn.GroupNorm): gn_param_nameset.add(name+'.weight') gn_param_nameset.add(name+'.bias') gn_params = [] gn_param_names =", "utils.training_stats import TrainingStats # Set up logging and load config", "original_batch_size cfg.NUM_GPUS = torch.cuda.device_count() assert (args.batch_size % cfg.NUM_GPUS) == 0,", "some configs ### original_batch_size = cfg.NUM_GPUS * cfg.TRAIN.IMS_PER_BATCH original_ims_per_batch =", "%d', step) lr_new = lr * cfg.SOLVER.GAMMA net_utils.update_learning_rate(optimizer, lr, lr_new)", "= optimizer.param_groups[0]['lr'] # lr of non-bias parameters, for commmand line", "logger.info('Training starts !') step = args.start_step for step in range(args.start_step,", "the value comed from cfg_file.', type=int) parser.add_argument( '--nw', dest='num_workers', help='Explicitly", "every iter_size steps, as in Caffe.', default=1, type=int) parser.add_argument( '--o',", "to run the code.\") if args.cuda or cfg.NUM_GPUS > 0:", "lr = optimizer.param_groups[0]['lr'] assert lr == lr_new elif step ==", "Resume training: requires same iterations per epoch parser.add_argument( '--resume', help='resume", "torch.optim.Adam(params) ### Load checkpoint if args.load_ckpt: load_name = args.load_ckpt logging.info(\"loading", "arguments\"\"\" parser = argparse.ArgumentParser(description='Train a X-RCNN network') parser.add_argument( '--dataset', dest='dataset',", "if decay_steps_ind < len(cfg.SOLVER.STEPS) and \\ step == cfg.SOLVER.STEPS[decay_steps_ind]: logger.info('Decay", "train_size, maskRCNN, optimizer) except (RuntimeError, KeyboardInterrupt): del dataiterator logger.info('Save ckpt", "by whitespace.' 'e.g. [key] [value] [key] [value]', default=[], nargs='+') parser.add_argument(", "and args.num_classes is None: raise ValueError(\"Need number of classes in", "== \"keypoints_coco2017\": cfg.TRAIN.DATASETS = ('keypoints_coco_2017_train',) cfg.MODEL.NUM_CLASSES = 2 elif args.dataset", "of ancdata. Issue: pytorch/pytorch#973 rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1]))", "training_stats.LogIterStats(step, lr) if (step+1) % CHECKPOINT_PERIOD == 0: save_ckpt(output_dir, args,", "logger = setup_logging(__name__) logging.getLogger('roi_data.loader').setLevel(logging.INFO) # RuntimeError: received 0 items of", "TrainingStats # Set up logging and load config options logger", "Timer from utils.training_stats import TrainingStats # Set up logging and", "% CHECKPOINT_PERIOD == 0: save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer)", "value to be set properly at the start of training", "f: pickle.dump(blob, f, pickle.HIGHEST_PROTOCOL) if args.use_tfboard: from tensorboardX import SummaryWriter", "os import sys import pickle import resource import traceback import", "# Learning rate decay if decay_steps_ind < len(cfg.SOLVER.STEPS) and \\", "dataloader = torch.utils.data.DataLoader( dataset, batch_sampler=batchSampler, num_workers=cfg.DATA_LOADER.NUM_THREADS, collate_fn=collate_minibatch) dataiterator = iter(dataloader)", "timers['roidb'].toc() roidb_size = len(roidb) logger.info('{:d} roidb entries'.format(roidb_size)) logger.info('Takes %.2f sec(s)", "and \\ step == cfg.SOLVER.STEPS[decay_steps_ind]: logger.info('Decay the learning on step", "1355: possible deadlock in dataloader import _init_paths # pylint: disable=unused-import", "print('Scale FPN rpn_proposals collect size directly propotional to the change", "dest='set_cfgs', help='Set config keys. Key value sequence seperate by whitespace.'", "not None: cfg.DATA_LOADER.NUM_THREADS = args.num_workers print('Number of data loading threads:", "threads: %d' % cfg.DATA_LOADER.NUM_THREADS) ### Overwrite some solver settings from", "= torch.optim.Adam(params) ### Load checkpoint if args.load_ckpt: load_name = args.load_ckpt", "'wb') as f: pickle.dump(blob, f, pickle.HIGHEST_PROTOCOL) if args.use_tfboard: from tensorboardX", "utils.detectron_weight_helper import load_detectron_weight from utils.logging import setup_logging from utils.timer import", "cfg.SOLVER.BASE_LR) lr = optimizer.param_groups[0]['lr'] assert lr == cfg.SOLVER.BASE_LR # Learning", "{'params': gn_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY_GN} ] # names of", "param_names = [nonbias_param_names, bias_param_names, gn_param_names] if cfg.SOLVER.TYPE == \"SGD\": optimizer", "start of training params = [ {'params': nonbias_params, 'lr': 0,", "= args.iter_size * args.batch_size print('effective_batch_size = batch_size * iter_size =", "utils.misc as misc_utils from core.config import cfg, cfg_from_file, cfg_from_list, assert_and_infer_cfg", "os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) save_name = os.path.join(ckpt_dir, 'model_step{}.pth'.format(step)) if isinstance(model, mynn.DataParallel): model", "RoiDataLoader( roidb, cfg.MODEL.NUM_CLASSES, training=True) dataloader = torch.utils.data.DataLoader( dataset, batch_sampler=batchSampler, num_workers=cfg.DATA_LOADER.NUM_THREADS,", "* (1 - alpha) + alpha else: raise KeyError('Unknown SOLVER.WARM_UP_METHOD:", "iter_size steps, as in Caffe.', default=1, type=int) parser.add_argument( '--o', dest='optimizer',", "datasets.roidb import combined_roidb_for_training from roi_data.loader import RoiDataLoader, MinibatchSampler, BatchSampler, collate_minibatch", "# roidb is a list of ndarrays with inconsistent length", "== 0, \\ 'batch_size: %d, NUM_GPUS: %d' % (args.batch_size, cfg.NUM_GPUS)", "0}, {'params': gn_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY_GN} ] # names", "if isinstance(model, mynn.DataParallel): model = model.module model_state_dict = model.state_dict() torch.save({", "import Generalized_RCNN from utils.detectron_weight_helper import load_detectron_weight from utils.logging import setup_logging", "cfg.NUM_GPUS) cfg.TRAIN.IMS_PER_BATCH = args.batch_size // cfg.NUM_GPUS effective_batch_size = args.iter_size *", "items of ancdata. Issue: pytorch/pytorch#973 rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (4096,", "cfg.SOLVER.BASE_LR # Learning rate decay if decay_steps_ind < len(cfg.SOLVER.STEPS) and", "= iter(dataloader) input_data = next(dataiterator) for key in input_data: if", "% (train_size, checkpoint['train_size'])) # reorder the params in optimizer checkpoint's", "loc: storage) net_utils.load_ckpt(maskRCNN, checkpoint['model']) if args.resume: args.start_step = checkpoint['step'] +", "Training Setups ### args.run_name = misc_utils.get_run_name() + '_step' output_dir =", "if needed # misc_utils.ensure_optimizer_ckpt_params_order(param_names, checkpoint) # There is a bug", "as np import yaml import torch from torch.autograd import Variable", "load data. Defaults to 4', type=int) parser.add_argument( '--iter_size', help='Update once", "overwrite the values in config file # or values set", "Optimization # These options has the highest prioity and can", "input_data[key] = list(map(Variable, input_data[key])) try: net_outputs = maskRCNN(**input_data) except: continue", "script for steps_with_decay policy\"\"\" import argparse import os import sys", "SOLVER.MAX_ITER: {} --> {}'.format(old_solver_steps, cfg.SOLVER.STEPS, old_max_iter, cfg.SOLVER.MAX_ITER)) # Scale FPN", "tensorboardX import SummaryWriter # Set the Tensorboard logger tblogger =", "if args.dataset == \"coco2017\": cfg.TRAIN.DATASETS = ('coco_2014_train',) cfg.MODEL.NUM_CLASSES = 4", "lr == lr_new elif step == cfg.SOLVER.WARM_UP_ITERS: net_utils.update_learning_rate(optimizer, lr, cfg.SOLVER.BASE_LR)", "% (original_num_gpus, cfg.NUM_GPUS)) print(' IMS_PER_BATCH: %d --> %d' % (original_ims_per_batch,", "args.start_step for step in range(args.start_step, cfg.SOLVER.MAX_ITER): # Warm up if", "lr = optimizer.param_groups[0]['lr'] assert lr == lr_new decay_steps_ind += 1", "epoch parser.add_argument( '--resume', help='resume to training on a checkpoint', action='store_true')", "args.start_step = checkpoint['step'] + 1 if 'train_size' in checkpoint: #", "\\ step == cfg.SOLVER.STEPS[decay_steps_ind]: logger.info('Decay the learning on step %d',", "*= args.batch_size / original_batch_size print('Adjust BASE_LR linearly according to batch_size", "logging.info(\"loading Detectron weights %s\", args.load_detectron) load_detectron_weight(maskRCNN, args.load_detectron) lr = optimizer.param_groups[0]['lr']", "NUM_GPUS: %d' % (args.batch_size, cfg.NUM_GPUS) cfg.TRAIN.IMS_PER_BATCH = args.batch_size // cfg.NUM_GPUS", "= ('keypoints_coco_2017_train',) cfg.MODEL.NUM_CLASSES = 2 elif args.dataset == \"voc2007\": cfg.TRAIN.DATASETS", "= mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'], minibatch=True) ### Training Setups ### args.run_name", "cfg.SOLVER.WARM_UP_ITERS warmup_factor = cfg.SOLVER.WARM_UP_FACTOR * (1 - alpha) + alpha", "import yaml import torch from torch.autograd import Variable import torch.nn", "if args.batch_size is None: args.batch_size = original_batch_size cfg.NUM_GPUS = torch.cuda.device_count()", "commmand line outputs. maskRCNN = mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'], minibatch=True) ###", "is scaled based # on batch_size instead of effective_batch_size old_base_lr", "parser.add_argument( '--lr', help='Base learning rate.', default=None, type=float) parser.add_argument( '--lr_decay_gamma', help='Learning", "step_scale + 0.5), cfg.SOLVER.STEPS)) cfg.SOLVER.MAX_ITER = int(cfg.SOLVER.MAX_ITER * step_scale +", "custom dataset to run!\") if args.dataset == \"coco2017\": cfg.TRAIN.DATASETS =", "maskRCNN = mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'], minibatch=True) ### Training Setups ###", "effective_batch_size change:\\n' ' SOLVER.STEPS: {} --> {}\\n' ' SOLVER.MAX_ITER: {}", "load_name = args.load_ckpt logging.info(\"loading checkpoint %s\", load_name) checkpoint = torch.load(load_name,", "output_dir = misc_utils.get_output_dir(args, args.run_name) args.cfg_filename = os.path.basename(args.cfg_file) if not args.no_save:", "= optimizer.param_groups[0]['lr'] assert lr == cfg.SOLVER.BASE_LR # Learning rate decay", "roidb, ratio_list, ratio_index = combined_roidb_for_training( cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES) timers['roidb'].toc() roidb_size =", "optimizer) # ---- Training ends ---- # Save last checkpoint", "step / cfg.SOLVER.WARM_UP_ITERS warmup_factor = cfg.SOLVER.WARM_UP_FACTOR * (1 - alpha)", "os.path.exists(output_dir): os.makedirs(output_dir) blob = {'cfg': yaml.dump(cfg), 'args': args} with open(os.path.join(output_dir,", "cfg.SOLVER.STEPS[i] >= args.start_step: decay_steps_ind = i break if decay_steps_ind is", "args.use_tfboard and not args.no_save: tblogger.close() if __name__ == '__main__': main()", "args.batch_size * args.batch_size batchSampler = BatchSampler( sampler=MinibatchSampler(ratio_list, ratio_index), batch_size=args.batch_size, drop_last=True", "utils.timer import Timer from utils.training_stats import TrainingStats # Set up", "= [] nograd_param_names = [] for key, value in maskRCNN.named_parameters():", "rate of 0 is a dummy value to be set", "import defaultdict import numpy as np import yaml import torch", "step_scale + 0.5) print('Adjust SOLVER.STEPS and SOLVER.MAX_ITER linearly based on", "collate_fn=collate_minibatch) dataiterator = iter(dataloader) ### Model ### maskRCNN = Generalized_RCNN()", "21 elif args.dataset == \"custom_dataset\": cfg.TRAIN.DATASETS = ('custom_data_train',) cfg.MODEL.NUM_CLASSES =", "it's fixed on master. optimizer.load_state_dict(checkpoint['optimizer']) # misc_utils.load_optimizer_state_dict(optimizer, checkpoint['optimizer']) del checkpoint", "'--resume', help='resume to training on a checkpoint', action='store_true') parser.add_argument( '--no_save',", "# Set index for decay steps decay_steps_ind = None for", "('keypoints_coco_2017_train',) cfg.MODEL.NUM_CLASSES = 2 elif args.dataset == \"voc2007\": cfg.TRAIN.DATASETS =", "== \"voc2012\": cfg.TRAIN.DATASETS = ('voc_2012_train',) cfg.MODEL.NUM_CLASSES = 21 elif args.dataset", "pickle import resource import traceback import logging from collections import", "in checkpoint: %d' % (train_size, checkpoint['train_size'])) # reorder the params", "net_utils.update_learning_rate(optimizer, lr, cfg.SOLVER.BASE_LR) lr = optimizer.param_groups[0]['lr'] assert lr == cfg.SOLVER.BASE_LR", "value sequence seperate by whitespace.' 'e.g. [key] [value] [key] [value]',", "rate.', default=None, type=float) parser.add_argument( '--lr_decay_gamma', help='Learning rate decay rate.', default=None,", "in optimizer.load_state_dict on Pytorch 0.3.1. # However it's fixed on", "parser.add_argument( '--lr_decay_gamma', help='Learning rate decay rate.', default=None, type=float) # Epoch", "device', action='store_false') # Optimization # These options has the highest", "gn_param_nameset.add(name+'.weight') gn_param_nameset.add(name+'.bias') gn_params = [] gn_param_names = [] bias_params =", "!= train_size: print('train_size value: %d different from the one in", "/ effective_batch_size old_solver_steps = cfg.SOLVER.STEPS old_max_iter = cfg.SOLVER.MAX_ITER cfg.SOLVER.STEPS =", "with inconsistent length input_data[key] = list(map(Variable, input_data[key])) try: net_outputs =", "cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES) timers['roidb'].toc() roidb_size = len(roidb) logger.info('{:d} roidb entries'.format(roidb_size)) logger.info('Takes", "== 'constant': warmup_factor = cfg.SOLVER.WARM_UP_FACTOR elif method == 'linear': alpha", "use') parser.add_argument( '--num_classes', dest='num_classes', help='Number of classes in your custom", "help='resume to training on a checkpoint', action='store_true') parser.add_argument( '--no_save', help='do", "\\ 'batch_size: %d, NUM_GPUS: %d' % (args.batch_size, cfg.NUM_GPUS) cfg.TRAIN.IMS_PER_BATCH =", "'roidb': # roidb is a list of ndarrays with inconsistent", "# names of paramerters for each paramter param_names = [nonbias_param_names,", "cfg, cfg_from_file, cfg_from_list, assert_and_infer_cfg from datasets.roidb import combined_roidb_for_training from roi_data.loader", "'train_size': train_size, 'batch_size': args.batch_size, 'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, save_name) logger.info('save", "torch.cuda.device_count() assert (args.batch_size % cfg.NUM_GPUS) == 0, \\ 'batch_size: %d,", "is a list of ndarrays with inconsistent length input_data[key] =", "cfg.FPN.RPN_COLLECT_SCALE + 0.5) if cfg.FPN.FPN_ON and cfg.MODEL.FASTER_RCNN: cfg.FPN.RPN_COLLECT_SCALE = cfg.TRAIN.IMS_PER_BATCH", "file for training (and optionally testing)') parser.add_argument( '--set', dest='set_cfgs', help='Set", "ValueError(\"Need number of classes in your custom dataset to run!\")", "cfg.NUM_GPUS = torch.cuda.device_count() assert (args.batch_size % cfg.NUM_GPUS) == 0, \\", "cfg.TRAIN.PROPOSAL_FILES) timers['roidb'].toc() roidb_size = len(roidb) logger.info('{:d} roidb entries'.format(roidb_size)) logger.info('Takes %.2f", "] # names of paramerters for each paramter param_names =", "input arguments\"\"\" parser = argparse.ArgumentParser(description='Train a X-RCNN network') parser.add_argument( '--dataset',", "set properly at the start of training params = [", "optimizer.', default=None) parser.add_argument( '--lr', help='Base learning rate.', default=None, type=float) parser.add_argument(", "if args.use_tfboard and not args.no_save else None) try: logger.info('Training starts", "'--num_classes', dest='num_classes', help='Number of classes in your custom dataset', default=None,", "% (args.batch_size, args.iter_size)) print('Adaptive config changes:') print(' effective_batch_size: %d -->", "a bug in optimizer.load_state_dict on Pytorch 0.3.1. # However it's", "path to load') parser.add_argument( '--load_detectron', help='path to the detectron weight", "key in input_data: if key != 'roidb': # roidb is", "from collections import defaultdict import numpy as np import yaml", "batch_size change:\\n' ' BASE_LR: {} --> {}'.format(old_base_lr, cfg.SOLVER.BASE_LR)) ### Adjust", "= int(cfg.SOLVER.MAX_ITER * step_scale + 0.5) print('Adjust SOLVER.STEPS and SOLVER.MAX_ITER", "= roidb_size // args.batch_size * args.batch_size batchSampler = BatchSampler( sampler=MinibatchSampler(ratio_list,", "overwrite number of workers to load data. Defaults to 4',", "options logger = setup_logging(__name__) logging.getLogger('roi_data.loader').setLevel(logging.INFO) # RuntimeError: received 0 items", "Epoch parser.add_argument( '--start_step', help='Starting step count for training epoch. 0-indexed.',", "batch_size=args.batch_size, drop_last=True ) dataset = RoiDataLoader( roidb, cfg.MODEL.NUM_CLASSES, training=True) dataloader", "anything', action='store_true') parser.add_argument( '--load_ckpt', help='checkpoint path to load') parser.add_argument( '--load_detectron',", "'weight_decay': cfg.SOLVER.WEIGHT_DECAY_GN} ] # names of paramerters for each paramter", "gn_param_nameset.add(name+'.bias') gn_params = [] gn_param_names = [] bias_params = []", "optimizer.state_dict()}, save_name) logger.info('save model: %s', save_name) def main(): \"\"\"Main function\"\"\"", "optimizer checkpoint's params_groups if needed # misc_utils.ensure_optimizer_ckpt_params_order(param_names, checkpoint) # There", "not use CUDA device', action='store_false') # Optimization # These options", "# pylint: disable=unused-import import nn as mynn import utils.net as", "0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY}, {'params': bias_params, 'lr': 0 * (cfg.SOLVER.BIAS_DOUBLE_LR +", "Learning rate of 0 is a dummy value to be", "cfg.NUM_GPUS if args.batch_size is None: args.batch_size = original_batch_size cfg.NUM_GPUS =", "cfg.CUDA: maskRCNN.cuda() ### Optimizer ### gn_param_nameset = set() for name,", "* cfg.SOLVER.GAMMA net_utils.update_learning_rate(optimizer, lr, lr_new) lr = optimizer.param_groups[0]['lr'] assert lr", "traceback import logging from collections import defaultdict import numpy as", "misc_utils.load_optimizer_state_dict(optimizer, checkpoint['optimizer']) del checkpoint torch.cuda.empty_cache() if args.load_detectron: #TODO resume for", "with args:') print(args) if not torch.cuda.is_available(): sys.exit(\"Need a CUDA device", "logger.info('Save ckpt on exception ...') save_ckpt(output_dir, args, step, train_size, maskRCNN,", "/ original_ims_per_batch print('Scale FPN rpn_proposals collect size directly propotional to", "import cfg, cfg_from_file, cfg_from_list, assert_and_infer_cfg from datasets.roidb import combined_roidb_for_training from", "= cfg.SOLVER.WARM_UP_METHOD if method == 'constant': warmup_factor = cfg.SOLVER.WARM_UP_FACTOR elif", "in dataloader import _init_paths # pylint: disable=unused-import import nn as", "dest='cfg_file', required=True, help='Config file for training (and optionally testing)') parser.add_argument(", "parser.add_argument( '--iter_size', help='Update once every iter_size steps, as in Caffe.',", "checkpoint['train_size'])) # reorder the params in optimizer checkpoint's params_groups if", "- alpha) + alpha else: raise KeyError('Unknown SOLVER.WARM_UP_METHOD: {}'.format(method)) lr_new", "input_data[key])) try: net_outputs = maskRCNN(**input_data) except: continue training_stats.UpdateIterStats(net_outputs, inner_iter) loss", "default=None, type=float) parser.add_argument( '--lr_decay_gamma', help='Learning rate decay rate.', default=None, type=float)", "rlimit[1])) def parse_args(): \"\"\"Parse input arguments\"\"\" parser = argparse.ArgumentParser(description='Train a", "(gn_param_nameset - set(nograd_param_names) - set(bias_param_names)) == set(gn_param_names) # Learning rate", "%d' % (original_num_gpus, cfg.NUM_GPUS)) print(' IMS_PER_BATCH: %d --> %d' %", "to the change of IMS_PER_BATCH:\\n' ' cfg.FPN.RPN_COLLECT_SCALE: {}'.format(cfg.FPN.RPN_COLLECT_SCALE)) if args.num_workers", "CUDA device to run the code.\") if args.cuda or cfg.NUM_GPUS", "cfg.SOLVER.WARM_UP_FACTOR * (1 - alpha) + alpha else: raise KeyError('Unknown", "defaultdict(Timer) ### Dataset ### timers['roidb'].tic() roidb, ratio_list, ratio_index = combined_roidb_for_training(", "resume for detectron weights (load sgd momentum values) logging.info(\"loading Detectron", "combined_roidb_for_training from roi_data.loader import RoiDataLoader, MinibatchSampler, BatchSampler, collate_minibatch from modeling.model_builder", "cfg.MODEL.NUM_CLASSES, training=True) dataloader = torch.utils.data.DataLoader( dataset, batch_sampler=batchSampler, num_workers=cfg.DATA_LOADER.NUM_THREADS, collate_fn=collate_minibatch) dataiterator", "inconsistent length input_data[key] = list(map(Variable, input_data[key])) try: net_outputs = maskRCNN(**input_data)", "cfg.SOLVER.BIAS_WEIGHT_DECAY else 0}, {'params': gn_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY_GN} ]", "to run !\") if args.dataset == \"custom_dataset\" and args.num_classes is", "args.load_detectron: #TODO resume for detectron weights (load sgd momentum values)", "outputs. maskRCNN = mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'], minibatch=True) ### Training Setups", "args.batch_size, 'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, save_name) logger.info('save model: %s', save_name)", "raise ValueError(\"Unexpected args.dataset: {}\".format(args.dataset)) cfg_from_file(args.cfg_file) if args.set_cfgs is not None:", "as nn import cv2 cv2.setNumThreads(0) # pytorch issue 1355: possible", "ancdata. Issue: pytorch/pytorch#973 rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1])) def", "import resource import traceback import logging from collections import defaultdict", "training=True) dataloader = torch.utils.data.DataLoader( dataset, batch_sampler=batchSampler, num_workers=cfg.DATA_LOADER.NUM_THREADS, collate_fn=collate_minibatch) dataiterator =", "4', type=int) parser.add_argument( '--iter_size', help='Update once every iter_size steps, as", "'--bs', dest='batch_size', help='Explicitly specify to overwrite the value comed from", "action='store_true') parser.add_argument( '--load_ckpt', help='checkpoint path to load') parser.add_argument( '--load_detectron', help='path", "the one in checkpoint: %d' % (train_size, checkpoint['train_size'])) # reorder", "0 items of ancdata. Issue: pytorch/pytorch#973 rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE,", "== cfg.SOLVER.BASE_LR # Learning rate decay if decay_steps_ind < len(cfg.SOLVER.STEPS)", "iterations per epoch parser.add_argument( '--resume', help='resume to training on a", "dataiterator = iter(dataloader) input_data = next(dataiterator) for key in input_data:", "in your custom dataset to run!\") if args.dataset == \"coco2017\":", "for commmand line outputs. maskRCNN = mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'], minibatch=True)", "sample size for one epoch train_size = roidb_size // args.batch_size", "type=int) # Resume training: requires same iterations per epoch parser.add_argument(", "NUM_GPUS: %d --> %d' % (original_num_gpus, cfg.NUM_GPUS)) print(' IMS_PER_BATCH: %d", "step) lr_new = lr * cfg.SOLVER.GAMMA net_utils.update_learning_rate(optimizer, lr, lr_new) lr", "cfg.TRAIN.DATASETS = ('voc_2007_train',) cfg.MODEL.NUM_CLASSES = 21 elif args.dataset == \"voc2012\":", "if args.cuda or cfg.NUM_GPUS > 0: cfg.CUDA = True else:", "return parser.parse_args() def save_ckpt(output_dir, args, step, train_size, model, optimizer): \"\"\"Save", "effective_batch_size old_base_lr = cfg.SOLVER.BASE_LR cfg.SOLVER.BASE_LR *= args.batch_size / original_batch_size print('Adjust", "+ 1 if 'train_size' in checkpoint: # For backward compatibility", "cfg.DATA_LOADER.NUM_THREADS) ### Overwrite some solver settings from command line arguments", "dataset', default=None, type=int) parser.add_argument( '--cfg', dest='cfg_file', required=True, help='Config file for", "alpha) + alpha else: raise KeyError('Unknown SOLVER.WARM_UP_METHOD: {}'.format(method)) lr_new =", "lr, cfg.SOLVER.BASE_LR) lr = optimizer.param_groups[0]['lr'] assert lr == cfg.SOLVER.BASE_LR #", "SOLVER.STEPS and SOLVER.MAX_ITER linearly based on effective_batch_size change:\\n' ' SOLVER.STEPS:", "= iter(dataloader) ### Model ### maskRCNN = Generalized_RCNN() if cfg.CUDA:", "has the highest prioity and can overwrite the values in", "instead of effective_batch_size old_base_lr = cfg.SOLVER.BASE_LR cfg.SOLVER.BASE_LR *= args.batch_size /", "return ckpt_dir = os.path.join(output_dir, 'ckpt') if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) save_name", "(RuntimeError, KeyboardInterrupt): del dataiterator logger.info('Save ckpt on exception ...') save_ckpt(output_dir,", "# lr of non-bias parameters, for commmand line outputs. maskRCNN", "import torch.nn as nn import cv2 cv2.setNumThreads(0) # pytorch issue", "= torch.optim.SGD(params, momentum=cfg.SOLVER.MOMENTUM) elif cfg.SOLVER.TYPE == \"Adam\": optimizer = torch.optim.Adam(params)", "optimizer.zero_grad() for inner_iter in range(args.iter_size): try: input_data = next(dataiterator) except", "= cfg.TRAIN.IMS_PER_BATCH / original_ims_per_batch print('Scale FPN rpn_proposals collect size directly", "parser.add_argument( '--disp_interval', help='Display training info every N iterations', default=20, type=int)", "change of IMS_PER_BATCH:\\n' ' cfg.FPN.RPN_COLLECT_SCALE: {}'.format(cfg.FPN.RPN_COLLECT_SCALE)) if args.num_workers is not", "== set(gn_param_names) # Learning rate of 0 is a dummy", "print(stack_trace) finally: if args.use_tfboard and not args.no_save: tblogger.close() if __name__", "0.3.1. # However it's fixed on master. optimizer.load_state_dict(checkpoint['optimizer']) # misc_utils.load_optimizer_state_dict(optimizer,", "gn_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY_GN} ] # names of paramerters", "= argparse.ArgumentParser(description='Train a X-RCNN network') parser.add_argument( '--dataset', dest='dataset', required=True, help='Dataset", "exception ...') save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) logger.info('Save ckpt", "### Load checkpoint if args.load_ckpt: load_name = args.load_ckpt logging.info(\"loading checkpoint", "is a dummy value to be set properly at the", "`collect` function # of `collect_and_distribute_fpn_rpn_proposals.py` # # post_nms_topN = int(cfg[cfg_key].RPN_POST_NMS_TOP_N", "misc_utils.ensure_optimizer_ckpt_params_order(param_names, checkpoint) # There is a bug in optimizer.load_state_dict on", "cfg.SOLVER.BASE_LR * warmup_factor net_utils.update_learning_rate(optimizer, lr, lr_new) lr = optimizer.param_groups[0]['lr'] assert", "FPN rpn_proposals collect size (post_nms_topN) in `collect` function # of", "optimizer): \"\"\"Save checkpoint\"\"\" if args.no_save: return ckpt_dir = os.path.join(output_dir, 'ckpt')", "= checkpoint['step'] + 1 if 'train_size' in checkpoint: # For", "// cfg.NUM_GPUS effective_batch_size = args.iter_size * args.batch_size print('effective_batch_size = batch_size", "cv2.setNumThreads(0) # pytorch issue 1355: possible deadlock in dataloader import", "from utils.logging import setup_logging from utils.timer import Timer from utils.training_stats", "checkpoint) # There is a bug in optimizer.load_state_dict on Pytorch", "(and optionally testing)') parser.add_argument( '--set', dest='set_cfgs', help='Set config keys. Key", "net_utils.load_ckpt(maskRCNN, checkpoint['model']) if args.resume: args.start_step = checkpoint['step'] + 1 if", "== \"custom_dataset\" and args.num_classes is None: raise ValueError(\"Need number of", "effective_batch_size: %d --> %d' % (original_batch_size, effective_batch_size)) print(' NUM_GPUS: %d", "loss.backward() optimizer.step() training_stats.IterToc() training_stats.LogIterStats(step, lr) if (step+1) % CHECKPOINT_PERIOD ==", "logging from collections import defaultdict import numpy as np import", "For iter_size > 1, gradients are `accumulated`, so lr is", "decay_steps_ind is None: decay_steps_ind = len(cfg.SOLVER.STEPS) training_stats = TrainingStats( args,", "= next(dataiterator) except StopIteration: dataiterator = iter(dataloader) input_data = next(dataiterator)", "help='Dataset to use') parser.add_argument( '--num_classes', dest='num_classes', help='Number of classes in", "import TrainingStats # Set up logging and load config options", "bias_params.append(value) bias_param_names.append(key) elif key in gn_param_nameset: gn_params.append(value) gn_param_names.append(key) else: nonbias_params.append(value)", "type=int) parser.add_argument( '--cfg', dest='cfg_file', required=True, help='Config file for training (and", "'--nw', dest='num_workers', help='Explicitly specify to overwrite number of workers to", "...') save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer) logger.info('Save ckpt done.')", "# Save last checkpoint save_ckpt(output_dir, args, step, train_size, maskRCNN, optimizer)", "SummaryWriter # Set the Tensorboard logger tblogger = SummaryWriter(output_dir) ###", "args.batch_size // cfg.NUM_GPUS effective_batch_size = args.iter_size * args.batch_size print('effective_batch_size =", "args, step, train_size, maskRCNN, optimizer) # ---- Training ends ----", "{'params': bias_params, 'lr': 0 * (cfg.SOLVER.BIAS_DOUBLE_LR + 1), 'weight_decay': cfg.SOLVER.WEIGHT_DECAY", "dest='num_workers', help='Explicitly specify to overwrite number of workers to load", "maskRCNN.train() CHECKPOINT_PERIOD = int(cfg.TRAIN.SNAPSHOT_ITERS / cfg.NUM_GPUS) # Set index for", "torch.utils.data.DataLoader( dataset, batch_sampler=batchSampler, num_workers=cfg.DATA_LOADER.NUM_THREADS, collate_fn=collate_minibatch) dataiterator = iter(dataloader) ### Model", "based on effective_batch_size change:\\n' ' SOLVER.STEPS: {} --> {}\\n' '", "to overwrite the value comed from cfg_file.', type=int) parser.add_argument( '--nw',", "from modeling.model_builder import Generalized_RCNN from utils.detectron_weight_helper import load_detectron_weight from utils.logging", "help='path to the detectron weight pickle file') parser.add_argument( '--use_tfboard', help='Use", "/ original_batch_size print('Adjust BASE_LR linearly according to batch_size change:\\n' '", "= True else: raise ValueError(\"Need Cuda device to run !\")", "= net_outputs['total_loss'] loss.backward() optimizer.step() training_stats.IterToc() training_stats.LogIterStats(step, lr) if (step+1) %", "step in range(args.start_step, cfg.SOLVER.MAX_ITER): # Warm up if step <", "key: bias_params.append(value) bias_param_names.append(key) elif key in gn_param_nameset: gn_params.append(value) gn_param_names.append(key) else:", "from the one in checkpoint: %d' % (train_size, checkpoint['train_size'])) #", "### args.run_name = misc_utils.get_run_name() + '_step' output_dir = misc_utils.get_output_dir(args, args.run_name)", "or cfg.NUM_GPUS > 0: cfg.CUDA = True else: raise ValueError(\"Need", "print(args) if not torch.cuda.is_available(): sys.exit(\"Need a CUDA device to run", "set by set_cfgs. `None` means do not overwrite. parser.add_argument( '--bs',", "yaml.dump(cfg), 'args': args} with open(os.path.join(output_dir, 'config_and_args.pkl'), 'wb') as f: pickle.dump(blob,", "= BatchSampler( sampler=MinibatchSampler(ratio_list, ratio_index), batch_size=args.batch_size, drop_last=True ) dataset = RoiDataLoader(", "one in checkpoint: %d' % (train_size, checkpoint['train_size'])) # reorder the", "for step in range(args.start_step, cfg.SOLVER.MAX_ITER): # Warm up if step", "except StopIteration: dataiterator = iter(dataloader) input_data = next(dataiterator) for key", "as net_utils import utils.misc as misc_utils from core.config import cfg,", "parser.add_argument( '--load_detectron', help='path to the detectron weight pickle file') parser.add_argument(", "# For iter_size > 1, gradients are `accumulated`, so lr", "cfg.SOLVER.MAX_ITER): # Warm up if step < cfg.SOLVER.WARM_UP_ITERS: method =", "effective_batch_size = args.iter_size * args.batch_size print('effective_batch_size = batch_size * iter_size", "not None: cfg.SOLVER.TYPE = args.optimizer if args.lr is not None:", "done.') stack_trace = traceback.format_exc() print(stack_trace) finally: if args.use_tfboard and not", "args.run_name) args.cfg_filename = os.path.basename(args.cfg_file) if not args.no_save: if not os.path.exists(output_dir):", "(train_size, checkpoint['train_size'])) # reorder the params in optimizer checkpoint's params_groups", "'model_step{}.pth'.format(step)) if isinstance(model, mynn.DataParallel): model = model.module model_state_dict = model.state_dict()", "else 0}, {'params': gn_params, 'lr': 0, 'weight_decay': cfg.SOLVER.WEIGHT_DECAY_GN} ] #", "to run!\") if args.dataset == \"coco2017\": cfg.TRAIN.DATASETS = ('coco_2014_train',) cfg.MODEL.NUM_CLASSES", "args.num_workers print('Number of data loading threads: %d' % cfg.DATA_LOADER.NUM_THREADS) ###", "assert lr == lr_new decay_steps_ind += 1 training_stats.IterTic() optimizer.zero_grad() for", "lr_new) lr = optimizer.param_groups[0]['lr'] assert lr == lr_new decay_steps_ind +=", "== lr_new decay_steps_ind += 1 training_stats.IterTic() optimizer.zero_grad() for inner_iter in", "\"keypoints_coco2017\": cfg.TRAIN.DATASETS = ('keypoints_coco_2017_train',) cfg.MODEL.NUM_CLASSES = 2 elif args.dataset ==", "= [] gn_param_names = [] bias_params = [] bias_param_names =", "args.set_cfgs is not None: cfg_from_list(args.set_cfgs) ### Adaptively adjust some configs", "\"Adam\": optimizer = torch.optim.Adam(params) ### Load checkpoint if args.load_ckpt: load_name", "* args.batch_size print('effective_batch_size = batch_size * iter_size = %d *", "None: cfg.SOLVER.BASE_LR = args.lr if args.lr_decay_gamma is not None: cfg.SOLVER.GAMMA", "for detectron weights (load sgd momentum values) logging.info(\"loading Detectron weights", "iter_size > 1, gradients are `accumulated`, so lr is scaled" ]
[ "busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"lexsort\": \"\"\"def lexsort(keys, axis=-1): return", "astroid.inference_tip import inference_tip from astroid.manager import AstroidManager from astroid.nodes.node_classes import", "0])\"\"\", \"empty\": \"\"\"def empty(shape, dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\", \"bincount\":", ") register_module_extender( AstroidManager(), \"numpy.core.multiarray\", numpy_core_multiarray_transform ) METHODS_TO_BE_INFERRED = { \"array\":", "register_module_extender from astroid.builder import parse from astroid.inference_tip import inference_tip from", "minlength=0): return numpy.ndarray([0, 0])\"\"\", \"busday_count\": \"\"\"def busday_count(begindates, enddates, weekmask='1111100', holidays=[],", "numpy.core.multiarray module.\"\"\" import functools from astroid.brain.brain_numpy_utils import infer_numpy_member, looks_like_numpy_member from", "\"\"\"def copyto(dst, src, casting='same_kind', where=True): return None\"\"\", \"datetime_as_string\": \"\"\"def datetime_as_string(arr,", "return True\"\"\", # Not yet available because dtype is not", "0])\"\"\", \"busday_offset\": \"\"\"def busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None):", "\"\"\"def empty_like(a, dtype=None, order='K', subok=True): return numpy.ndarray((0, 0))\"\"\", \"concatenate\": \"\"\"def", "unit=None, timezone='naive', casting='same_kind'): return numpy.ndarray([0, 0])\"\"\", \"is_busday\": \"\"\"def is_busday(dates, weekmask='1111100',", "\"lexsort\": \"\"\"def lexsort(keys, axis=-1): return numpy.ndarray([0, 0])\"\"\", \"may_share_memory\": \"\"\"def may_share_memory(a,", "order='C'): return (numpy.ndarray([0, 0]),)\"\"\", \"zeros\": \"\"\"def zeros(shape, dtype=float, order='C'): return", "return numpy.ndarray([0, 0])\"\"\", \"is_busday\": \"\"\"def is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None):", "\"unravel_index\": \"\"\"def unravel_index(indices, shape, order='C'): return (numpy.ndarray([0, 0]),)\"\"\", \"zeros\": \"\"\"def", "2021 <NAME> <<EMAIL>> # Copyright (c) 2021 <NAME> <<EMAIL>> #", "return (numpy.ndarray([0, 0]),)\"\"\", \"zeros\": \"\"\"def zeros(shape, dtype=float, order='C'): return numpy.ndarray([0,", "unravel_index(indices, shape, order='C'): return (numpy.ndarray([0, 0]),)\"\"\", \"zeros\": \"\"\"def zeros(shape, dtype=float,", "subok=False, ndmin=0): return numpy.ndarray([0, 0])\"\"\", \"dot\": \"\"\"def dot(a, b, out=None):", "astroid.brain.helpers import register_module_extender from astroid.builder import parse from astroid.inference_tip import", "\"array\": \"\"\"def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0): return numpy.ndarray([0,", "import parse from astroid.inference_tip import inference_tip from astroid.manager import AstroidManager", "numpy.ndarray([0, 0])\"\"\", \"is_busday\": \"\"\"def is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None): return", "dot(a, b, out=None): return numpy.ndarray([0, 0])\"\"\", \"empty_like\": \"\"\"def empty_like(a, dtype=None,", "casting='same_kind', where=True): return None\"\"\", \"datetime_as_string\": \"\"\"def datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind'):", "\"busday_offset\": \"\"\"def busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None): return", ") METHODS_TO_BE_INFERRED = { \"array\": \"\"\"def array(object, dtype=None, copy=True, order='K',", "casting='same_kind'): return numpy.ndarray([0, 0])\"\"\", \"is_busday\": \"\"\"def is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None,", "return numpy.ndarray([0, 0])\"\"\", \"dot\": \"\"\"def dot(a, b, out=None): return numpy.ndarray([0,", "def vdot(a, b): return numpy.ndarray([0, 0]) \"\"\" ) register_module_extender( AstroidManager(),", "offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"can_cast\":", "shares_memory(a, b, max_work=None): return True\"\"\", \"unpackbits\": \"\"\"def unpackbits(a, axis=None, count=None,", "return numpy.ndarray([0, 0])\"\"\", \"unravel_index\": \"\"\"def unravel_index(indices, shape, order='C'): return (numpy.ndarray([0,", "return numpy.dtype('int16')\"\"\", \"shares_memory\": \"\"\"def shares_memory(a, b, max_work=None): return True\"\"\", \"unpackbits\":", "\"\"\"def can_cast(from_, to, casting='safe'): return True\"\"\", \"copyto\": \"\"\"def copyto(dst, src,", "AstroidManager(), \"numpy.core.multiarray\", numpy_core_multiarray_transform ) METHODS_TO_BE_INFERRED = { \"array\": \"\"\"def array(object,", "\"bincount\": \"\"\"def bincount(x, weights=None, minlength=0): return numpy.ndarray([0, 0])\"\"\", \"busday_count\": \"\"\"def", "holidays=[], busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"busday_offset\": \"\"\"def busday_offset(dates, offsets,", "\"\"\"def is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"lexsort\":", "(c) 2021 <NAME> <<EMAIL>> # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html", "numpy.ndarray([0, 0]) \"\"\" ) register_module_extender( AstroidManager(), \"numpy.core.multiarray\", numpy_core_multiarray_transform ) METHODS_TO_BE_INFERRED", "for method_name, function_src in METHODS_TO_BE_INFERRED.items(): inference_function = functools.partial(infer_numpy_member, function_src) AstroidManager().register_transform(", "register_module_extender( AstroidManager(), \"numpy.core.multiarray\", numpy_core_multiarray_transform ) METHODS_TO_BE_INFERRED = { \"array\": \"\"\"def", "\"\"\"def min_scalar_type(a): # return numpy.dtype('int16')\"\"\", \"packbits\": \"\"\"def packbits(a, axis=None, bitorder='big'):", "import AstroidManager from astroid.nodes.node_classes import Attribute, Name def numpy_core_multiarray_transform(): return", "unpackbits(a, axis=None, count=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\", \"unravel_index\": \"\"\"def unravel_index(indices,", "for numpy.core.multiarray module.\"\"\" import functools from astroid.brain.brain_numpy_utils import infer_numpy_member, looks_like_numpy_member", "# Copyright (c) 2021 <NAME> <<EMAIL>> # Licensed under the", "\"shares_memory\": \"\"\"def shares_memory(a, b, max_work=None): return True\"\"\", \"unpackbits\": \"\"\"def unpackbits(a,", "where=True): return None\"\"\", \"datetime_as_string\": \"\"\"def datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind'): return", "# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE \"\"\"Astroid hooks for numpy.core.multiarray module.\"\"\" import", "numpy.dtype('int16')\"\"\", \"shares_memory\": \"\"\"def shares_memory(a, b, max_work=None): return True\"\"\", \"unpackbits\": \"\"\"def", "0))\"\"\", \"where\": \"\"\"def where(condition, x=None, y=None): return numpy.ndarray([0, 0])\"\"\", \"empty\":", "empty(shape, dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\", \"bincount\": \"\"\"def bincount(x, weights=None,", "dtype is not yet present in those brains # \"min_scalar_type\":", "\"\"\"def lexsort(keys, axis=-1): return numpy.ndarray([0, 0])\"\"\", \"may_share_memory\": \"\"\"def may_share_memory(a, b,", "def numpy_core_multiarray_transform(): return parse( \"\"\" # different functions defined in", "in multiarray.py def inner(a, b): return numpy.ndarray([0, 0]) def vdot(a,", "numpy.ndarray([0, 0])\"\"\", \"busday_offset\": \"\"\"def busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None,", "busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\",", "looks_like_numpy_member from astroid.brain.helpers import register_module_extender from astroid.builder import parse from", "} for method_name, function_src in METHODS_TO_BE_INFERRED.items(): inference_function = functools.partial(infer_numpy_member, function_src)", "method_name, function_src in METHODS_TO_BE_INFERRED.items(): inference_function = functools.partial(infer_numpy_member, function_src) AstroidManager().register_transform( Attribute,", "return numpy.ndarray([0, 0])\"\"\", \"empty_like\": \"\"\"def empty_like(a, dtype=None, order='K', subok=True): return", "<NAME> <<EMAIL>> # Copyright (c) 2021 <NAME> <<EMAIL>> # Copyright", "0])\"\"\", \"may_share_memory\": \"\"\"def may_share_memory(a, b, max_work=None): return True\"\"\", # Not", "numpy.ndarray([0, 0])\"\"\", \"dot\": \"\"\"def dot(a, b, out=None): return numpy.ndarray([0, 0])\"\"\",", "0))\"\"\", \"concatenate\": \"\"\"def concatenate(arrays, axis=None, out=None): return numpy.ndarray((0, 0))\"\"\", \"where\":", "0])\"\"\", \"busday_count\": \"\"\"def busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None): return", "\"\"\"def busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None): return numpy.ndarray([0,", "return numpy.ndarray((0, 0))\"\"\", \"concatenate\": \"\"\"def concatenate(arrays, axis=None, out=None): return numpy.ndarray((0,", "order='C'): return numpy.ndarray([0, 0])\"\"\", \"bincount\": \"\"\"def bincount(x, weights=None, minlength=0): return", "\"\"\"def empty(shape, dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\", \"bincount\": \"\"\"def bincount(x,", "under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE \"\"\"Astroid hooks", "count=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\", \"unravel_index\": \"\"\"def unravel_index(indices, shape, order='C'):", "max_work=None): return True\"\"\", \"unpackbits\": \"\"\"def unpackbits(a, axis=None, count=None, bitorder='big'): return", "b, max_work=None): return True\"\"\", # Not yet available because dtype", "x=None, y=None): return numpy.ndarray([0, 0])\"\"\", \"empty\": \"\"\"def empty(shape, dtype=float, order='C'):", "available because dtype is not yet present in those brains", "weekmask='1111100', holidays=None, busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"lexsort\": \"\"\"def lexsort(keys,", "dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\", \"bincount\": \"\"\"def bincount(x, weights=None, minlength=0):", "numpy.ndarray([0, 0])\"\"\", \"may_share_memory\": \"\"\"def may_share_memory(a, b, max_work=None): return True\"\"\", #", "y=None): return numpy.ndarray([0, 0])\"\"\", \"empty\": \"\"\"def empty(shape, dtype=float, order='C'): return", "inference_tip(inference_function), functools.partial(looks_like_numpy_member, method_name), ) AstroidManager().register_transform( Name, inference_tip(inference_function), functools.partial(looks_like_numpy_member, method_name), )", "0]) def vdot(a, b): return numpy.ndarray([0, 0]) \"\"\" ) register_module_extender(", "from astroid.inference_tip import inference_tip from astroid.manager import AstroidManager from astroid.nodes.node_classes", "copyto(dst, src, casting='same_kind', where=True): return None\"\"\", \"datetime_as_string\": \"\"\"def datetime_as_string(arr, unit=None,", "numpy.ndarray([0, 0]) def vdot(a, b): return numpy.ndarray([0, 0]) \"\"\" )", "= functools.partial(infer_numpy_member, function_src) AstroidManager().register_transform( Attribute, inference_tip(inference_function), functools.partial(looks_like_numpy_member, method_name), ) AstroidManager().register_transform(", "\"numpy.core.multiarray\", numpy_core_multiarray_transform ) METHODS_TO_BE_INFERRED = { \"array\": \"\"\"def array(object, dtype=None,", "busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"busday_offset\":", "METHODS_TO_BE_INFERRED.items(): inference_function = functools.partial(infer_numpy_member, function_src) AstroidManager().register_transform( Attribute, inference_tip(inference_function), functools.partial(looks_like_numpy_member, method_name),", "return numpy.ndarray([0, 0])\"\"\", \"bincount\": \"\"\"def bincount(x, weights=None, minlength=0): return numpy.ndarray([0,", "True\"\"\", \"copyto\": \"\"\"def copyto(dst, src, casting='same_kind', where=True): return None\"\"\", \"datetime_as_string\":", "functools from astroid.brain.brain_numpy_utils import infer_numpy_member, looks_like_numpy_member from astroid.brain.helpers import register_module_extender", "datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind'): return numpy.ndarray([0, 0])\"\"\", \"is_busday\": \"\"\"def is_busday(dates,", "numpy.ndarray([0, 0])\"\"\", \"unravel_index\": \"\"\"def unravel_index(indices, shape, order='C'): return (numpy.ndarray([0, 0]),)\"\"\",", "import inference_tip from astroid.manager import AstroidManager from astroid.nodes.node_classes import Attribute,", "Copyright (c) 2021 <NAME> <<EMAIL>> # Licensed under the LGPL:", "copy=True, order='K', subok=False, ndmin=0): return numpy.ndarray([0, 0])\"\"\", \"dot\": \"\"\"def dot(a,", "import functools from astroid.brain.brain_numpy_utils import infer_numpy_member, looks_like_numpy_member from astroid.brain.helpers import", "b, max_work=None): return True\"\"\", \"unpackbits\": \"\"\"def unpackbits(a, axis=None, count=None, bitorder='big'):", "is not yet present in those brains # \"min_scalar_type\": \"\"\"def", "because dtype is not yet present in those brains #", "module.\"\"\" import functools from astroid.brain.brain_numpy_utils import infer_numpy_member, looks_like_numpy_member from astroid.brain.helpers", "functools.partial(infer_numpy_member, function_src) AstroidManager().register_transform( Attribute, inference_tip(inference_function), functools.partial(looks_like_numpy_member, method_name), ) AstroidManager().register_transform( Name,", "(c) 2020 <NAME> <<EMAIL>> # Copyright (c) 2021 <NAME> <<EMAIL>>", "\"concatenate\": \"\"\"def concatenate(arrays, axis=None, out=None): return numpy.ndarray((0, 0))\"\"\", \"where\": \"\"\"def", "astroid.builder import parse from astroid.inference_tip import inference_tip from astroid.manager import", "For details: https://github.com/PyCQA/astroid/blob/main/LICENSE \"\"\"Astroid hooks for numpy.core.multiarray module.\"\"\" import functools", "Not yet available because dtype is not yet present in", "brains # \"result_type\": \"\"\"def result_type(*arrays_and_dtypes): # return numpy.dtype('int16')\"\"\", \"shares_memory\": \"\"\"def", "in METHODS_TO_BE_INFERRED.items(): inference_function = functools.partial(infer_numpy_member, function_src) AstroidManager().register_transform( Attribute, inference_tip(inference_function), functools.partial(looks_like_numpy_member,", "inference_function = functools.partial(infer_numpy_member, function_src) AstroidManager().register_transform( Attribute, inference_tip(inference_function), functools.partial(looks_like_numpy_member, method_name), )", "from astroid.brain.brain_numpy_utils import infer_numpy_member, looks_like_numpy_member from astroid.brain.helpers import register_module_extender from", "numpy.ndarray([0, 0])\"\"\", \"busday_count\": \"\"\"def busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None):", "import register_module_extender from astroid.builder import parse from astroid.inference_tip import inference_tip", "packbits(a, axis=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\", # Not yet available", "return numpy.ndarray([0, 0])\"\"\", # Not yet available because dtype is", "zeros(shape, dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\", } for method_name, function_src", "roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"can_cast\": \"\"\"def", "0])\"\"\", \"bincount\": \"\"\"def bincount(x, weights=None, minlength=0): return numpy.ndarray([0, 0])\"\"\", \"busday_count\":", "to, casting='safe'): return True\"\"\", \"copyto\": \"\"\"def copyto(dst, src, casting='same_kind', where=True):", "different functions defined in multiarray.py def inner(a, b): return numpy.ndarray([0,", "weekmask='1111100', holidays=[], busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"busday_offset\": \"\"\"def busday_offset(dates,", "<<EMAIL>> # Copyright (c) 2020 <NAME> <<EMAIL>> # Copyright (c)", "# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE", "present in those brains # \"min_scalar_type\": \"\"\"def min_scalar_type(a): # return", "\"\"\"def where(condition, x=None, y=None): return numpy.ndarray([0, 0])\"\"\", \"empty\": \"\"\"def empty(shape,", "max_work=None): return True\"\"\", # Not yet available because dtype is", "those brains # \"result_type\": \"\"\"def result_type(*arrays_and_dtypes): # return numpy.dtype('int16')\"\"\", \"shares_memory\":", "\"packbits\": \"\"\"def packbits(a, axis=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\", # Not", "return numpy.ndarray([0, 0]) \"\"\" ) register_module_extender( AstroidManager(), \"numpy.core.multiarray\", numpy_core_multiarray_transform )", "2021 <NAME> <<EMAIL>> # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html #", "return numpy.ndarray([0, 0])\"\"\", \"lexsort\": \"\"\"def lexsort(keys, axis=-1): return numpy.ndarray([0, 0])\"\"\",", "\"\"\"def unravel_index(indices, shape, order='C'): return (numpy.ndarray([0, 0]),)\"\"\", \"zeros\": \"\"\"def zeros(shape,", "\"dot\": \"\"\"def dot(a, b, out=None): return numpy.ndarray([0, 0])\"\"\", \"empty_like\": \"\"\"def", "LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE \"\"\"Astroid hooks for numpy.core.multiarray", "functions defined in multiarray.py def inner(a, b): return numpy.ndarray([0, 0])", "not yet present in those brains # \"min_scalar_type\": \"\"\"def min_scalar_type(a):", "# Not yet available because dtype is not yet present", "\"\"\"def result_type(*arrays_and_dtypes): # return numpy.dtype('int16')\"\"\", \"shares_memory\": \"\"\"def shares_memory(a, b, max_work=None):", "can_cast(from_, to, casting='safe'): return True\"\"\", \"copyto\": \"\"\"def copyto(dst, src, casting='same_kind',", "0])\"\"\", \"unravel_index\": \"\"\"def unravel_index(indices, shape, order='C'): return (numpy.ndarray([0, 0]),)\"\"\", \"zeros\":", "inference_tip from astroid.manager import AstroidManager from astroid.nodes.node_classes import Attribute, Name", "bitorder='big'): return numpy.ndarray([0, 0])\"\"\", \"unravel_index\": \"\"\"def unravel_index(indices, shape, order='C'): return", "(c) 2019-2020 hippo91 <<EMAIL>> # Copyright (c) 2020 <NAME> <<EMAIL>>", "\"min_scalar_type\": \"\"\"def min_scalar_type(a): # return numpy.dtype('int16')\"\"\", \"packbits\": \"\"\"def packbits(a, axis=None,", "from astroid.builder import parse from astroid.inference_tip import inference_tip from astroid.manager", "(c) 2021 <NAME> <<EMAIL>> # Copyright (c) 2021 <NAME> <<EMAIL>>", "hippo91 <<EMAIL>> # Copyright (c) 2020 <NAME> <<EMAIL>> # Copyright", "0])\"\"\", } for method_name, function_src in METHODS_TO_BE_INFERRED.items(): inference_function = functools.partial(infer_numpy_member,", "# return numpy.dtype('int16')\"\"\", \"shares_memory\": \"\"\"def shares_memory(a, b, max_work=None): return True\"\"\",", "0])\"\"\", \"is_busday\": \"\"\"def is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None): return numpy.ndarray([0,", "0])\"\"\", \"can_cast\": \"\"\"def can_cast(from_, to, casting='safe'): return True\"\"\", \"copyto\": \"\"\"def", "busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"busday_offset\": \"\"\"def busday_offset(dates, offsets, roll='raise',", "astroid.nodes.node_classes import Attribute, Name def numpy_core_multiarray_transform(): return parse( \"\"\" #", "yet available because dtype is not yet present in those", "empty_like(a, dtype=None, order='K', subok=True): return numpy.ndarray((0, 0))\"\"\", \"concatenate\": \"\"\"def concatenate(arrays,", "weights=None, minlength=0): return numpy.ndarray([0, 0])\"\"\", \"busday_count\": \"\"\"def busday_count(begindates, enddates, weekmask='1111100',", "\"datetime_as_string\": \"\"\"def datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind'): return numpy.ndarray([0, 0])\"\"\", \"is_busday\":", "numpy.ndarray((0, 0))\"\"\", \"concatenate\": \"\"\"def concatenate(arrays, axis=None, out=None): return numpy.ndarray((0, 0))\"\"\",", "dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\", } for method_name, function_src in", "lexsort(keys, axis=-1): return numpy.ndarray([0, 0])\"\"\", \"may_share_memory\": \"\"\"def may_share_memory(a, b, max_work=None):", "\"\"\"Astroid hooks for numpy.core.multiarray module.\"\"\" import functools from astroid.brain.brain_numpy_utils import", "weekmask='1111100', holidays=None, busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"can_cast\": \"\"\"def can_cast(from_,", "0])\"\"\", \"empty_like\": \"\"\"def empty_like(a, dtype=None, order='K', subok=True): return numpy.ndarray((0, 0))\"\"\",", "\"\"\"def packbits(a, axis=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\", # Not yet", "0])\"\"\", # Not yet available because dtype is not yet", "https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE \"\"\"Astroid hooks for numpy.core.multiarray module.\"\"\"", "<NAME> <<EMAIL>> # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For", "out=None): return numpy.ndarray([0, 0])\"\"\", \"can_cast\": \"\"\"def can_cast(from_, to, casting='safe'): return", "\"\"\"def zeros(shape, dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\", } for method_name,", "Attribute, Name def numpy_core_multiarray_transform(): return parse( \"\"\" # different functions", "inner(a, b): return numpy.ndarray([0, 0]) def vdot(a, b): return numpy.ndarray([0,", "\"\"\"def shares_memory(a, b, max_work=None): return True\"\"\", \"unpackbits\": \"\"\"def unpackbits(a, axis=None,", "return numpy.ndarray((0, 0))\"\"\", \"where\": \"\"\"def where(condition, x=None, y=None): return numpy.ndarray([0,", "\"\"\"def may_share_memory(a, b, max_work=None): return True\"\"\", # Not yet available", "https://github.com/PyCQA/astroid/blob/main/LICENSE \"\"\"Astroid hooks for numpy.core.multiarray module.\"\"\" import functools from astroid.brain.brain_numpy_utils", "\"where\": \"\"\"def where(condition, x=None, y=None): return numpy.ndarray([0, 0])\"\"\", \"empty\": \"\"\"def", "def inner(a, b): return numpy.ndarray([0, 0]) def vdot(a, b): return", "\"may_share_memory\": \"\"\"def may_share_memory(a, b, max_work=None): return True\"\"\", # Not yet", "Copyright (c) 2020 <NAME> <<EMAIL>> # Copyright (c) 2021 <NAME>", "\"\"\"def unpackbits(a, axis=None, count=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\", \"unravel_index\": \"\"\"def", "\"is_busday\": \"\"\"def is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\",", "return True\"\"\", \"copyto\": \"\"\"def copyto(dst, src, casting='same_kind', where=True): return None\"\"\",", "in those brains # \"result_type\": \"\"\"def result_type(*arrays_and_dtypes): # return numpy.dtype('int16')\"\"\",", "dtype=None, copy=True, order='K', subok=False, ndmin=0): return numpy.ndarray([0, 0])\"\"\", \"dot\": \"\"\"def", "(numpy.ndarray([0, 0]),)\"\"\", \"zeros\": \"\"\"def zeros(shape, dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\",", "yet present in those brains # \"min_scalar_type\": \"\"\"def min_scalar_type(a): #", "may_share_memory(a, b, max_work=None): return True\"\"\", # Not yet available because", "numpy.ndarray((0, 0))\"\"\", \"where\": \"\"\"def where(condition, x=None, y=None): return numpy.ndarray([0, 0])\"\"\",", "astroid.manager import AstroidManager from astroid.nodes.node_classes import Attribute, Name def numpy_core_multiarray_transform():", "astroid.brain.brain_numpy_utils import infer_numpy_member, looks_like_numpy_member from astroid.brain.helpers import register_module_extender from astroid.builder", "return None\"\"\", \"datetime_as_string\": \"\"\"def datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind'): return numpy.ndarray([0,", "\"can_cast\": \"\"\"def can_cast(from_, to, casting='safe'): return True\"\"\", \"copyto\": \"\"\"def copyto(dst,", "enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"busday_offset\": \"\"\"def", "Copyright (c) 2019-2020 hippo91 <<EMAIL>> # Copyright (c) 2020 <NAME>", "\"\"\" ) register_module_extender( AstroidManager(), \"numpy.core.multiarray\", numpy_core_multiarray_transform ) METHODS_TO_BE_INFERRED = {", "0])\"\"\", \"lexsort\": \"\"\"def lexsort(keys, axis=-1): return numpy.ndarray([0, 0])\"\"\", \"may_share_memory\": \"\"\"def", "min_scalar_type(a): # return numpy.dtype('int16')\"\"\", \"packbits\": \"\"\"def packbits(a, axis=None, bitorder='big'): return", "{ \"array\": \"\"\"def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0): return", "numpy_core_multiarray_transform(): return parse( \"\"\" # different functions defined in multiarray.py", "import infer_numpy_member, looks_like_numpy_member from astroid.brain.helpers import register_module_extender from astroid.builder import", "# \"min_scalar_type\": \"\"\"def min_scalar_type(a): # return numpy.dtype('int16')\"\"\", \"packbits\": \"\"\"def packbits(a,", "Name def numpy_core_multiarray_transform(): return parse( \"\"\" # different functions defined", "AstroidManager().register_transform( Attribute, inference_tip(inference_function), functools.partial(looks_like_numpy_member, method_name), ) AstroidManager().register_transform( Name, inference_tip(inference_function), functools.partial(looks_like_numpy_member,", "multiarray.py def inner(a, b): return numpy.ndarray([0, 0]) def vdot(a, b):", "2020 <NAME> <<EMAIL>> # Copyright (c) 2021 <NAME> <<EMAIL>> #", "dtype=None, order='K', subok=True): return numpy.ndarray((0, 0))\"\"\", \"concatenate\": \"\"\"def concatenate(arrays, axis=None,", "subok=True): return numpy.ndarray((0, 0))\"\"\", \"concatenate\": \"\"\"def concatenate(arrays, axis=None, out=None): return", "return parse( \"\"\" # different functions defined in multiarray.py def", "True\"\"\", \"unpackbits\": \"\"\"def unpackbits(a, axis=None, count=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\",", "parse( \"\"\" # different functions defined in multiarray.py def inner(a,", "0])\"\"\", \"dot\": \"\"\"def dot(a, b, out=None): return numpy.ndarray([0, 0])\"\"\", \"empty_like\":", "\"unpackbits\": \"\"\"def unpackbits(a, axis=None, count=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\", \"unravel_index\":", "\"\"\" # different functions defined in multiarray.py def inner(a, b):", "numpy.dtype('int16')\"\"\", \"packbits\": \"\"\"def packbits(a, axis=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\", #", "order='C'): return numpy.ndarray([0, 0])\"\"\", } for method_name, function_src in METHODS_TO_BE_INFERRED.items():", "\"copyto\": \"\"\"def copyto(dst, src, casting='same_kind', where=True): return None\"\"\", \"datetime_as_string\": \"\"\"def", "import Attribute, Name def numpy_core_multiarray_transform(): return parse( \"\"\" # different", "return numpy.ndarray([0, 0])\"\"\", \"may_share_memory\": \"\"\"def may_share_memory(a, b, max_work=None): return True\"\"\",", "Copyright (c) 2021 <NAME> <<EMAIL>> # Copyright (c) 2021 <NAME>", "casting='safe'): return True\"\"\", \"copyto\": \"\"\"def copyto(dst, src, casting='same_kind', where=True): return", "return numpy.ndarray([0, 0]) def vdot(a, b): return numpy.ndarray([0, 0]) \"\"\"", "\"\"\"def datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind'): return numpy.ndarray([0, 0])\"\"\", \"is_busday\": \"\"\"def", "from astroid.brain.helpers import register_module_extender from astroid.builder import parse from astroid.inference_tip", "function_src) AstroidManager().register_transform( Attribute, inference_tip(inference_function), functools.partial(looks_like_numpy_member, method_name), ) AstroidManager().register_transform( Name, inference_tip(inference_function),", "<<EMAIL>> # Copyright (c) 2021 <NAME> <<EMAIL>> # Copyright (c)", "order='K', subok=True): return numpy.ndarray((0, 0))\"\"\", \"concatenate\": \"\"\"def concatenate(arrays, axis=None, out=None):", "\"empty_like\": \"\"\"def empty_like(a, dtype=None, order='K', subok=True): return numpy.ndarray((0, 0))\"\"\", \"concatenate\":", "\"result_type\": \"\"\"def result_type(*arrays_and_dtypes): # return numpy.dtype('int16')\"\"\", \"shares_memory\": \"\"\"def shares_memory(a, b,", "= { \"array\": \"\"\"def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0):", "# Copyright (c) 2019-2020 hippo91 <<EMAIL>> # Copyright (c) 2020", "function_src in METHODS_TO_BE_INFERRED.items(): inference_function = functools.partial(infer_numpy_member, function_src) AstroidManager().register_transform( Attribute, inference_tip(inference_function),", "0]) \"\"\" ) register_module_extender( AstroidManager(), \"numpy.core.multiarray\", numpy_core_multiarray_transform ) METHODS_TO_BE_INFERRED =", "the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE \"\"\"Astroid hooks for", "holidays=None, busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"lexsort\": \"\"\"def lexsort(keys, axis=-1):", "dtype is not yet present in those brains # \"result_type\":", "src, casting='same_kind', where=True): return None\"\"\", \"datetime_as_string\": \"\"\"def datetime_as_string(arr, unit=None, timezone='naive',", "not yet present in those brains # \"result_type\": \"\"\"def result_type(*arrays_and_dtypes):", "Attribute, inference_tip(inference_function), functools.partial(looks_like_numpy_member, method_name), ) AstroidManager().register_transform( Name, inference_tip(inference_function), functools.partial(looks_like_numpy_member, method_name),", "<<EMAIL>> # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details:", "numpy.ndarray([0, 0])\"\"\", } for method_name, function_src in METHODS_TO_BE_INFERRED.items(): inference_function =", "0]),)\"\"\", \"zeros\": \"\"\"def zeros(shape, dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\", }", "\"empty\": \"\"\"def empty(shape, dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\", \"bincount\": \"\"\"def", "True\"\"\", # Not yet available because dtype is not yet", "AstroidManager from astroid.nodes.node_classes import Attribute, Name def numpy_core_multiarray_transform(): return parse(", "# return numpy.dtype('int16')\"\"\", \"packbits\": \"\"\"def packbits(a, axis=None, bitorder='big'): return numpy.ndarray([0,", "shape, order='C'): return (numpy.ndarray([0, 0]),)\"\"\", \"zeros\": \"\"\"def zeros(shape, dtype=float, order='C'):", "return numpy.dtype('int16')\"\"\", \"packbits\": \"\"\"def packbits(a, axis=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\",", "out=None): return numpy.ndarray([0, 0])\"\"\", \"empty_like\": \"\"\"def empty_like(a, dtype=None, order='K', subok=True):", "\"busday_count\": \"\"\"def busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None): return numpy.ndarray([0,", "defined in multiarray.py def inner(a, b): return numpy.ndarray([0, 0]) def", "return numpy.ndarray([0, 0])\"\"\", } for method_name, function_src in METHODS_TO_BE_INFERRED.items(): inference_function", "present in those brains # \"result_type\": \"\"\"def result_type(*arrays_and_dtypes): # return", "\"\"\"def dot(a, b, out=None): return numpy.ndarray([0, 0])\"\"\", \"empty_like\": \"\"\"def empty_like(a,", "return numpy.ndarray([0, 0])\"\"\", \"can_cast\": \"\"\"def can_cast(from_, to, casting='safe'): return True\"\"\",", "numpy.ndarray([0, 0])\"\"\", \"lexsort\": \"\"\"def lexsort(keys, axis=-1): return numpy.ndarray([0, 0])\"\"\", \"may_share_memory\":", "return True\"\"\", \"unpackbits\": \"\"\"def unpackbits(a, axis=None, count=None, bitorder='big'): return numpy.ndarray([0,", "busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"can_cast\": \"\"\"def can_cast(from_, to, casting='safe'):", "b): return numpy.ndarray([0, 0]) \"\"\" ) register_module_extender( AstroidManager(), \"numpy.core.multiarray\", numpy_core_multiarray_transform", "return numpy.ndarray([0, 0])\"\"\", \"busday_count\": \"\"\"def busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None,", "out=None): return numpy.ndarray((0, 0))\"\"\", \"where\": \"\"\"def where(condition, x=None, y=None): return", "vdot(a, b): return numpy.ndarray([0, 0]) \"\"\" ) register_module_extender( AstroidManager(), \"numpy.core.multiarray\",", "brains # \"min_scalar_type\": \"\"\"def min_scalar_type(a): # return numpy.dtype('int16')\"\"\", \"packbits\": \"\"\"def", "bincount(x, weights=None, minlength=0): return numpy.ndarray([0, 0])\"\"\", \"busday_count\": \"\"\"def busday_count(begindates, enddates,", "from astroid.nodes.node_classes import Attribute, Name def numpy_core_multiarray_transform(): return parse( \"\"\"", "# different functions defined in multiarray.py def inner(a, b): return", "<NAME> <<EMAIL>> # Copyright (c) 2021 <NAME> <<EMAIL>> # Licensed", "numpy.ndarray([0, 0])\"\"\", \"bincount\": \"\"\"def bincount(x, weights=None, minlength=0): return numpy.ndarray([0, 0])\"\"\",", "from astroid.manager import AstroidManager from astroid.nodes.node_classes import Attribute, Name def", "those brains # \"min_scalar_type\": \"\"\"def min_scalar_type(a): # return numpy.dtype('int16')\"\"\", \"packbits\":", "hooks for numpy.core.multiarray module.\"\"\" import functools from astroid.brain.brain_numpy_utils import infer_numpy_member,", "out=None): return numpy.ndarray([0, 0])\"\"\", \"busday_offset\": \"\"\"def busday_offset(dates, offsets, roll='raise', weekmask='1111100',", "axis=None, count=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\", \"unravel_index\": \"\"\"def unravel_index(indices, shape,", "METHODS_TO_BE_INFERRED = { \"array\": \"\"\"def array(object, dtype=None, copy=True, order='K', subok=False,", "\"zeros\": \"\"\"def zeros(shape, dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\", } for", "axis=-1): return numpy.ndarray([0, 0])\"\"\", \"may_share_memory\": \"\"\"def may_share_memory(a, b, max_work=None): return", "axis=None, bitorder='big'): return numpy.ndarray([0, 0])\"\"\", # Not yet available because", "b, out=None): return numpy.ndarray([0, 0])\"\"\", \"empty_like\": \"\"\"def empty_like(a, dtype=None, order='K',", "out=None): return numpy.ndarray([0, 0])\"\"\", \"lexsort\": \"\"\"def lexsort(keys, axis=-1): return numpy.ndarray([0,", "bitorder='big'): return numpy.ndarray([0, 0])\"\"\", # Not yet available because dtype", "result_type(*arrays_and_dtypes): # return numpy.dtype('int16')\"\"\", \"shares_memory\": \"\"\"def shares_memory(a, b, max_work=None): return", "\"\"\"def concatenate(arrays, axis=None, out=None): return numpy.ndarray((0, 0))\"\"\", \"where\": \"\"\"def where(condition,", "# Copyright (c) 2020 <NAME> <<EMAIL>> # Copyright (c) 2021", "\"\"\"def bincount(x, weights=None, minlength=0): return numpy.ndarray([0, 0])\"\"\", \"busday_count\": \"\"\"def busday_count(begindates,", "numpy.ndarray([0, 0])\"\"\", # Not yet available because dtype is not", "in those brains # \"min_scalar_type\": \"\"\"def min_scalar_type(a): # return numpy.dtype('int16')\"\"\",", "numpy.ndarray([0, 0])\"\"\", \"empty_like\": \"\"\"def empty_like(a, dtype=None, order='K', subok=True): return numpy.ndarray((0,", "None\"\"\", \"datetime_as_string\": \"\"\"def datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind'): return numpy.ndarray([0, 0])\"\"\",", "numpy.ndarray([0, 0])\"\"\", \"empty\": \"\"\"def empty(shape, dtype=float, order='C'): return numpy.ndarray([0, 0])\"\"\",", "where(condition, x=None, y=None): return numpy.ndarray([0, 0])\"\"\", \"empty\": \"\"\"def empty(shape, dtype=float,", "\"\"\"def busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\",", "concatenate(arrays, axis=None, out=None): return numpy.ndarray((0, 0))\"\"\", \"where\": \"\"\"def where(condition, x=None,", "timezone='naive', casting='same_kind'): return numpy.ndarray([0, 0])\"\"\", \"is_busday\": \"\"\"def is_busday(dates, weekmask='1111100', holidays=None,", "ndmin=0): return numpy.ndarray([0, 0])\"\"\", \"dot\": \"\"\"def dot(a, b, out=None): return", "is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"lexsort\": \"\"\"def", "2019-2020 hippo91 <<EMAIL>> # Copyright (c) 2020 <NAME> <<EMAIL>> #", "return numpy.ndarray([0, 0])\"\"\", \"busday_offset\": \"\"\"def busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None,", "return numpy.ndarray([0, 0])\"\"\", \"empty\": \"\"\"def empty(shape, dtype=float, order='C'): return numpy.ndarray([0,", "order='K', subok=False, ndmin=0): return numpy.ndarray([0, 0])\"\"\", \"dot\": \"\"\"def dot(a, b,", "is not yet present in those brains # \"result_type\": \"\"\"def", "<<EMAIL>> # Copyright (c) 2021 <NAME> <<EMAIL>> # Licensed under", "numpy.ndarray([0, 0])\"\"\", \"can_cast\": \"\"\"def can_cast(from_, to, casting='safe'): return True\"\"\", \"copyto\":", "numpy_core_multiarray_transform ) METHODS_TO_BE_INFERRED = { \"array\": \"\"\"def array(object, dtype=None, copy=True,", "Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE \"\"\"Astroid", "details: https://github.com/PyCQA/astroid/blob/main/LICENSE \"\"\"Astroid hooks for numpy.core.multiarray module.\"\"\" import functools from", "array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0): return numpy.ndarray([0, 0])\"\"\", \"dot\":", "parse from astroid.inference_tip import inference_tip from astroid.manager import AstroidManager from", "yet present in those brains # \"result_type\": \"\"\"def result_type(*arrays_and_dtypes): #", "b): return numpy.ndarray([0, 0]) def vdot(a, b): return numpy.ndarray([0, 0])", "infer_numpy_member, looks_like_numpy_member from astroid.brain.helpers import register_module_extender from astroid.builder import parse", "axis=None, out=None): return numpy.ndarray((0, 0))\"\"\", \"where\": \"\"\"def where(condition, x=None, y=None):", "holidays=None, busdaycal=None, out=None): return numpy.ndarray([0, 0])\"\"\", \"can_cast\": \"\"\"def can_cast(from_, to,", "\"\"\"def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0): return numpy.ndarray([0, 0])\"\"\",", "# Copyright (c) 2021 <NAME> <<EMAIL>> # Copyright (c) 2021", "# \"result_type\": \"\"\"def result_type(*arrays_and_dtypes): # return numpy.dtype('int16')\"\"\", \"shares_memory\": \"\"\"def shares_memory(a," ]
[ "24 25 1 1 2 1 21 23 3 5", "24 25 1 1 1 1 1 0 21 a", "24 d 25 e 28 f 0 B+ 0 B-", "1 1 1 0 18 2 23 3 0 3", "21 19 20 24 25 0 0 6 0 5", "0 B+ 0 B- 1 0 1 \"\"\" output =", "0 B- 1 0 1 \"\"\" output = \"\"\" COST", "2 1 21 23 3 5 21 19 20 24", "1 0 21 a 19 b 20 c 24 d", "0 6 0 5 5 21 19 20 24 25", "25 e 28 f 0 B+ 0 B- 1 0", "1 2 1 21 23 3 5 21 19 20", "c 24 d 25 e 28 f 0 B+ 0", "0 0 6 0 5 5 21 19 20 24", "1 21 23 3 5 21 19 20 24 25", "21 1 1 1 0 18 2 23 3 0", "= \"\"\" 2 18 3 0 3 19 20 21", "3 19 24 25 1 1 2 1 21 23", "25 1 1 1 1 1 0 21 a 19", "19 20 24 25 0 0 6 0 5 5", "20 24 25 1 1 1 1 1 0 21", "20 24 25 0 0 6 0 5 5 21", "2 18 3 0 3 19 20 21 1 1", "1 1 1 1 0 21 a 19 b 20", "0 3 19 24 25 1 1 2 1 21", "e 28 f 0 B+ 0 B- 1 0 1", "0 18 2 23 3 0 3 19 24 25", "3 0 3 19 20 21 1 1 1 0", "0 5 5 21 19 20 24 25 1 1", "5 21 19 20 24 25 0 0 6 0", "1 1 1 1 1 0 21 a 19 b", "1 1 0 18 2 23 3 0 3 19", "B- 1 0 1 \"\"\" output = \"\"\" COST 1@1", "25 1 1 2 1 21 23 3 5 21", "1 1 0 21 a 19 b 20 c 24", "a 19 b 20 c 24 d 25 e 28", "3 5 21 19 20 24 25 0 0 6", "19 b 20 c 24 d 25 e 28 f", "20 21 1 1 1 0 18 2 23 3", "<filename>tests/asp/weakConstraints/testcase13.bug.weakconstraints.gringo.test.py input = \"\"\" 2 18 3 0 3 19", "19 20 21 1 1 1 0 18 2 23", "1 1 2 1 21 23 3 5 21 19", "6 0 5 5 21 19 20 24 25 1", "1 0 1 \"\"\" output = \"\"\" COST 1@1 \"\"\"", "0 3 19 20 21 1 1 1 0 18", "21 a 19 b 20 c 24 d 25 e", "18 2 23 3 0 3 19 24 25 1", "28 f 0 B+ 0 B- 1 0 1 \"\"\"", "5 21 19 20 24 25 1 1 1 1", "d 25 e 28 f 0 B+ 0 B- 1", "21 19 20 24 25 1 1 1 1 1", "B+ 0 B- 1 0 1 \"\"\" output = \"\"\"", "18 3 0 3 19 20 21 1 1 1", "21 23 3 5 21 19 20 24 25 0", "0 21 a 19 b 20 c 24 d 25", "19 20 24 25 1 1 1 1 1 0", "2 23 3 0 3 19 24 25 1 1", "3 19 20 21 1 1 1 0 18 2", "23 3 5 21 19 20 24 25 0 0", "20 c 24 d 25 e 28 f 0 B+", "3 0 3 19 24 25 1 1 2 1", "input = \"\"\" 2 18 3 0 3 19 20", "5 5 21 19 20 24 25 1 1 1", "\"\"\" 2 18 3 0 3 19 20 21 1", "19 24 25 1 1 2 1 21 23 3", "1 1 1 0 21 a 19 b 20 c", "24 25 0 0 6 0 5 5 21 19", "b 20 c 24 d 25 e 28 f 0", "25 0 0 6 0 5 5 21 19 20", "f 0 B+ 0 B- 1 0 1 \"\"\" output", "1 0 18 2 23 3 0 3 19 24", "23 3 0 3 19 24 25 1 1 2" ]
[ "적습니다. 콤마(,)로 분리해서 적습니다.\\n\") names = names_string.split(\",\") print(names) n =", "이름을 적습니다. 콤마(,)로 분리해서 적습니다.\\n\") names = names_string.split(\",\") print(names) n", "random names_string = input(\"내기를 할 친구들의 이름을 적습니다. 콤마(,)로 분리해서", "콤마(,)로 분리해서 적습니다.\\n\") names = names_string.split(\",\") print(names) n = random.randint(0,", "할 친구들의 이름을 적습니다. 콤마(,)로 분리해서 적습니다.\\n\") names = names_string.split(\",\")", "<reponame>susurigirl/susuri import random names_string = input(\"내기를 할 친구들의 이름을 적습니다.", "친구들의 이름을 적습니다. 콤마(,)로 분리해서 적습니다.\\n\") names = names_string.split(\",\") print(names)", "import random names_string = input(\"내기를 할 친구들의 이름을 적습니다. 콤마(,)로", "적습니다.\\n\") names = names_string.split(\",\") print(names) n = random.randint(0, len(names)) print(f\"오늘", "names = names_string.split(\",\") print(names) n = random.randint(0, len(names)) print(f\"오늘 커피는", "= names_string.split(\",\") print(names) n = random.randint(0, len(names)) print(f\"오늘 커피는 {names[n]}가", "names_string.split(\",\") print(names) n = random.randint(0, len(names)) print(f\"오늘 커피는 {names[n]}가 쏩니다!\")", "= input(\"내기를 할 친구들의 이름을 적습니다. 콤마(,)로 분리해서 적습니다.\\n\") names", "분리해서 적습니다.\\n\") names = names_string.split(\",\") print(names) n = random.randint(0, len(names))", "names_string = input(\"내기를 할 친구들의 이름을 적습니다. 콤마(,)로 분리해서 적습니다.\\n\")", "input(\"내기를 할 친구들의 이름을 적습니다. 콤마(,)로 분리해서 적습니다.\\n\") names =" ]
[ "compute_dp(a) dp_r = compute_dp(a[::-1])[::-1] dp_r = dp_r.astype(np.int64).cumsum(axis=1) cnt = 0", "k - x - i - 1 < 0 else", "not r[k - i - 1] - (0 if k", "if k - x - i - 1 < 0", "continue cnt += 1 break print(n - cnt) def main()", "0 for p in range(n): l, r = dp_l[p], dp_r[n", "- i - 1] - (0 if k - x", "r = dp_l[p], dp_r[n - p] x = a[p] for", "n, k = map(int, input().split()) a = np.array(sys.stdin.readline().split(), dtype=np.int64) solve(a,", "np.ndarray, k: int) -> typing.NoReturn: n = len(a) def compute_dp(a:", "for i in range(n): dp[i + 1] = dp[i].copy() dp[i", "main() -> typing.NoReturn: n, k = map(int, input().split()) a =", "np.ndarray) -> np.ndarray: dp = np.zeros((n + 1, k), np.bool8)", "dp_r[n - p] x = a[p] for i in np.flatnonzero(l).tolist():", "r[k - x - i - 1]) >= 1 ):", "0] = True for i in range(n): dp[i + 1]", "- (0 if k - x - i - 1", "print(n - cnt) def main() -> typing.NoReturn: n, k =", "in range(n): dp[i + 1] = dp[i].copy() dp[i + 1,", "= len(a) def compute_dp(a: np.ndarray) -> np.ndarray: dp = np.zeros((n", "i - 1 < 0 else r[k - x -", "p in range(n): l, r = dp_l[p], dp_r[n - p]", "dp[i, : -a[i]] return dp dp_l = compute_dp(a) dp_r =", "-a[i]] return dp dp_l = compute_dp(a) dp_r = compute_dp(a[::-1])[::-1] dp_r", "dp[i].copy() dp[i + 1, a[i] :] |= dp[i, : -a[i]]", "= True for i in range(n): dp[i + 1] =", "numpy as np def solve(a: np.ndarray, k: int) -> typing.NoReturn:", "def compute_dp(a: np.ndarray) -> np.ndarray: dp = np.zeros((n + 1,", "dp dp_l = compute_dp(a) dp_r = compute_dp(a[::-1])[::-1] dp_r = dp_r.astype(np.int64).cumsum(axis=1)", "+ 1, k), np.bool8) dp[0, 0] = True for i", "return dp dp_l = compute_dp(a) dp_r = compute_dp(a[::-1])[::-1] dp_r =", ":] |= dp[i, : -a[i]] return dp dp_l = compute_dp(a)", "int) -> typing.NoReturn: n = len(a) def compute_dp(a: np.ndarray) ->", "dp = np.zeros((n + 1, k), np.bool8) dp[0, 0] =", "x - i - 1 < 0 else r[k -", "1] - (0 if k - x - i -", "def solve(a: np.ndarray, k: int) -> typing.NoReturn: n = len(a)", "- 1 < 0 else r[k - x - i", "- 1] - (0 if k - x - i", "for p in range(n): l, r = dp_l[p], dp_r[n -", "dp_r.astype(np.int64).cumsum(axis=1) cnt = 0 for p in range(n): l, r", "range(n): l, r = dp_l[p], dp_r[n - p] x =", "i - 1]) >= 1 ): continue cnt += 1", "< 0 else r[k - x - i - 1])", "1]) >= 1 ): continue cnt += 1 break print(n", "dp[0, 0] = True for i in range(n): dp[i +", "- i - 1 < 0 else r[k - x", "= compute_dp(a[::-1])[::-1] dp_r = dp_r.astype(np.int64).cumsum(axis=1) cnt = 0 for p", "i in np.flatnonzero(l).tolist(): if ( not r[k - i -", "dp_l = compute_dp(a) dp_r = compute_dp(a[::-1])[::-1] dp_r = dp_r.astype(np.int64).cumsum(axis=1) cnt", "i in range(n): dp[i + 1] = dp[i].copy() dp[i +", "len(a) def compute_dp(a: np.ndarray) -> np.ndarray: dp = np.zeros((n +", "x = a[p] for i in np.flatnonzero(l).tolist(): if ( not", "- cnt) def main() -> typing.NoReturn: n, k = map(int,", "k = map(int, input().split()) a = np.array(sys.stdin.readline().split(), dtype=np.int64) solve(a, k)", "dp_l[p], dp_r[n - p] x = a[p] for i in", "0 else r[k - x - i - 1]) >=", "break print(n - cnt) def main() -> typing.NoReturn: n, k", "= dp_l[p], dp_r[n - p] x = a[p] for i", "= dp_r.astype(np.int64).cumsum(axis=1) cnt = 0 for p in range(n): l,", "= a[p] for i in np.flatnonzero(l).tolist(): if ( not r[k", "typing.NoReturn: n = len(a) def compute_dp(a: np.ndarray) -> np.ndarray: dp", "a[i] :] |= dp[i, : -a[i]] return dp dp_l =", "= compute_dp(a) dp_r = compute_dp(a[::-1])[::-1] dp_r = dp_r.astype(np.int64).cumsum(axis=1) cnt =", "+= 1 break print(n - cnt) def main() -> typing.NoReturn:", "- 1]) >= 1 ): continue cnt += 1 break", "1, a[i] :] |= dp[i, : -a[i]] return dp dp_l", "- x - i - 1]) >= 1 ): continue", "compute_dp(a[::-1])[::-1] dp_r = dp_r.astype(np.int64).cumsum(axis=1) cnt = 0 for p in", "def main() -> typing.NoReturn: n, k = map(int, input().split()) a", "import typing import numpy as np def solve(a: np.ndarray, k:", "dp[i + 1, a[i] :] |= dp[i, : -a[i]] return", "np.flatnonzero(l).tolist(): if ( not r[k - i - 1] -", "compute_dp(a: np.ndarray) -> np.ndarray: dp = np.zeros((n + 1, k),", "dp[i + 1] = dp[i].copy() dp[i + 1, a[i] :]", "-> typing.NoReturn: n = len(a) def compute_dp(a: np.ndarray) -> np.ndarray:", "if ( not r[k - i - 1] - (0", "typing.NoReturn: n, k = map(int, input().split()) a = np.array(sys.stdin.readline().split(), dtype=np.int64)", "cnt += 1 break print(n - cnt) def main() ->", "- p] x = a[p] for i in np.flatnonzero(l).tolist(): if", "for i in np.flatnonzero(l).tolist(): if ( not r[k - i", "x - i - 1]) >= 1 ): continue cnt", "else r[k - x - i - 1]) >= 1", "1 < 0 else r[k - x - i -", "= map(int, input().split()) a = np.array(sys.stdin.readline().split(), dtype=np.int64) solve(a, k) main()", "np.ndarray: dp = np.zeros((n + 1, k), np.bool8) dp[0, 0]", "r[k - i - 1] - (0 if k -", "1] = dp[i].copy() dp[i + 1, a[i] :] |= dp[i,", "1, k), np.bool8) dp[0, 0] = True for i in", "): continue cnt += 1 break print(n - cnt) def", "import numpy as np def solve(a: np.ndarray, k: int) ->", "True for i in range(n): dp[i + 1] = dp[i].copy()", "+ 1] = dp[i].copy() dp[i + 1, a[i] :] |=", "- x - i - 1 < 0 else r[k", "typing import numpy as np def solve(a: np.ndarray, k: int)", "k), np.bool8) dp[0, 0] = True for i in range(n):", "|= dp[i, : -a[i]] return dp dp_l = compute_dp(a) dp_r", "1 break print(n - cnt) def main() -> typing.NoReturn: n,", "- i - 1]) >= 1 ): continue cnt +=", "np.zeros((n + 1, k), np.bool8) dp[0, 0] = True for", "+ 1, a[i] :] |= dp[i, : -a[i]] return dp", "k: int) -> typing.NoReturn: n = len(a) def compute_dp(a: np.ndarray)", "( not r[k - i - 1] - (0 if", "sys import typing import numpy as np def solve(a: np.ndarray,", "dp_r = dp_r.astype(np.int64).cumsum(axis=1) cnt = 0 for p in range(n):", "i - 1] - (0 if k - x -", "l, r = dp_l[p], dp_r[n - p] x = a[p]", "cnt = 0 for p in range(n): l, r =", "np.bool8) dp[0, 0] = True for i in range(n): dp[i", "cnt) def main() -> typing.NoReturn: n, k = map(int, input().split())", "import sys import typing import numpy as np def solve(a:", "range(n): dp[i + 1] = dp[i].copy() dp[i + 1, a[i]", "= 0 for p in range(n): l, r = dp_l[p],", "(0 if k - x - i - 1 <", "1 ): continue cnt += 1 break print(n - cnt)", "as np def solve(a: np.ndarray, k: int) -> typing.NoReturn: n", "in range(n): l, r = dp_l[p], dp_r[n - p] x", "-> typing.NoReturn: n, k = map(int, input().split()) a = np.array(sys.stdin.readline().split(),", ": -a[i]] return dp dp_l = compute_dp(a) dp_r = compute_dp(a[::-1])[::-1]", "solve(a: np.ndarray, k: int) -> typing.NoReturn: n = len(a) def", "in np.flatnonzero(l).tolist(): if ( not r[k - i - 1]", "= np.zeros((n + 1, k), np.bool8) dp[0, 0] = True", "= dp[i].copy() dp[i + 1, a[i] :] |= dp[i, :", "p] x = a[p] for i in np.flatnonzero(l).tolist(): if (", "n = len(a) def compute_dp(a: np.ndarray) -> np.ndarray: dp =", "dp_r = compute_dp(a[::-1])[::-1] dp_r = dp_r.astype(np.int64).cumsum(axis=1) cnt = 0 for", "-> np.ndarray: dp = np.zeros((n + 1, k), np.bool8) dp[0,", "a[p] for i in np.flatnonzero(l).tolist(): if ( not r[k -", ">= 1 ): continue cnt += 1 break print(n -", "np def solve(a: np.ndarray, k: int) -> typing.NoReturn: n =" ]
[ "Connected\".format(task)) def disconncb(task): print(\"[{}] Disconnected\".format(task)) def subscb(task): print(\"[{}] Subscribed\".format(task)) def", "user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) # or secure connection #thing =", "thing.status()[0] != 2: utime.sleep_ms(100) tmo += 1 if tmo >", "def conncb(task): print(\"[{}] Connected\".format(task)) def disconncb(task): print(\"[{}] Disconnected\".format(task)) def subscb(task):", "network.mqtt(\"thingspeak\", \"mqtts://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) thingspeakChannelId = \"123456\" #", "subchan = \"channels/{:s}/subscribe/{:s}/{:s}\".format(thingspeakChannelId, thingSpeakChanelFormat, thingspeakChannelWriteApiKey) subfield = \"channels/{:s}/subscribe/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey)", "can include any of those fields separated b< ';': #", "published_cb=pubcb, data_cb=datacb) # wsmqtt = network.mqtt(\"eclipse\", \"ws://iot.eclipse.org:80/ws\", cleansession=True, data_cb=datacb) mqtt.start()", "not work # mqtts = network.mqtt(\"eclipse\", \"mqtts//iot.eclipse.org\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb,", "\"ws://iot.eclipse.org:80/ws\", cleansession=True, data_cb=datacb) mqtt.start() #mqtt.config(lwt_topic='status', lwt_msg='Disconected') ''' # Wait until", "= 1 thingSpeakChanelFormat = \"json\" pubchan = \"channels/{:s}/publish/{:s}\".format(thingspeakChannelId, thingspeakChannelWriteApiKey) pubfield", "datacb(msg): print(\"[{}] Data arrived from topic: {}, Message:\\n\".format(msg[0], msg[1]), msg[2])", "thing = network.mqtt(\"thingspeak\", \"mqtt://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) # or", "= \"ThingspeakWriteAPIKey\" # EDIT - enter Thingspeak Write API Key", "connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # wsmqtt = network.mqtt(\"eclipse\", \"ws://iot.eclipse.org:80/ws\",", "connection #thing = network.mqtt(\"thingspeak\", \"mqtts://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) thingspeakChannelId", "thing.subscribe(subchan) # subscribe to field thing.subscribe(subfield) # publish to channel", "subscb(task): print(\"[{}] Subscribed\".format(task)) def pubcb(pub): print(\"[{}] Published: {}\".format(pub[0], pub[1])) def", "Subscribed\".format(task)) def pubcb(pub): print(\"[{}] Published: {}\".format(pub[0], pub[1])) def datacb(msg): print(\"[{}]", "thingSpeakChanelFormat, thingspeakChannelWriteApiKey) subfield = \"channels/{:s}/subscribe/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) thing.start() tmo =", "Data arrived from topic: {}, Message:\\n\".format(msg[0], msg[1]), msg[2]) thing =", "cleansession=True, data_cb=datacb) # or secure connection #thing = network.mqtt(\"thingspeak\", \"mqtts://mqtt.thingspeak.com\",", "topic: {}, Message:\\n\".format(msg[0], msg[1]), msg[2]) thing = network.mqtt(\"thingspeak\", \"mqtt://mqtt.thingspeak.com\", user=\"anyName\",", "user=\"wifimcu\", password=\"<PASSWORD>\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # secure", "thingspeakFieldNo, thingspeakChannelWriteApiKey) thing.start() tmo = 0 while thing.status()[0] != 2:", "def disconncb(task): print(\"[{}] Disconnected\".format(task)) def subscb(task): print(\"[{}] Subscribed\".format(task)) def pubcb(pub):", "\"123456\" # enter Thingspeak Channel ID thingspeakChannelWriteApiKey = \"ThingspeakWriteAPIKey\" #", "secure connection #thing = network.mqtt(\"thingspeak\", \"mqtts://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb)", "wsmqtt = network.mqtt(\"eclipse\", \"ws://iot.eclipse.org:80/ws\", cleansession=True, data_cb=datacb) mqtt.start() #mqtt.config(lwt_topic='status', lwt_msg='Disconected') '''", "print(\"[{}] Published: {}\".format(pub[0], pub[1])) def datacb(msg): print(\"[{}] Data arrived from", "{}, Message:\\n\".format(msg[0], msg[1]), msg[2]) mqtt = network.mqtt(\"loboris\", \"mqtt://loboris.eu\", user=\"wifimcu\", password=\"<PASSWORD>\",", "msg[1]), msg[2]) mqtt = network.mqtt(\"loboris\", \"mqtt://loboris.eu\", user=\"wifimcu\", password=\"<PASSWORD>\", cleansession=True, connected_cb=conncb,", "= network.mqtt(\"eclipse\", \"ws://iot.eclipse.org:80/ws\", cleansession=True, data_cb=datacb) mqtt.start() #mqtt.config(lwt_topic='status', lwt_msg='Disconected') ''' #", "status is: (1, 'Connected') mqtt.subscribe('test') mqtt.publish('test', 'Hi from Micropython') mqtt.stop()", "ThingSpeak example # ================== import network def datacb(msg): print(\"[{}] Data", "= \"channels/{:s}/publish/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) subchan = \"channels/{:s}/subscribe/{:s}/{:s}\".format(thingspeakChannelId, thingSpeakChanelFormat, thingspeakChannelWriteApiKey) subfield", "# subscribe to channel thing.subscribe(subchan) # subscribe to field thing.subscribe(subfield)", "network.mqtt(\"eclipse\", \"mqtts//iot.eclipse.org\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # wsmqtt", "publish to channel # Payload can include any of those", "Disconnected\".format(task)) def subscb(task): print(\"[{}] Subscribed\".format(task)) def pubcb(pub): print(\"[{}] Published: {}\".format(pub[0],", "from topic: {}, Message:\\n\".format(msg[0], msg[1]), msg[2]) mqtt = network.mqtt(\"loboris\", \"mqtt://loboris.eu\",", "subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # wsmqtt = network.mqtt(\"eclipse\", \"ws://iot.eclipse.org:80/ws\", cleansession=True, data_cb=datacb)", "memory and may not work # mqtts = network.mqtt(\"eclipse\", \"mqtts//iot.eclipse.org\",", "conncb(task): print(\"[{}] Connected\".format(task)) def disconncb(task): print(\"[{}] Disconnected\".format(task)) def subscb(task): print(\"[{}]", "channel # Payload can include any of those fields separated", "connection requires more memory and may not work # mqtts", "\"channels/{:s}/publish/{:s}\".format(thingspeakChannelId, thingspeakChannelWriteApiKey) pubfield = \"channels/{:s}/publish/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) subchan = \"channels/{:s}/subscribe/{:s}/{:s}\".format(thingspeakChannelId,", "disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # wsmqtt = network.mqtt(\"eclipse\", \"ws://iot.eclipse.org:80/ws\", cleansession=True,", "user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) thingspeakChannelId = \"123456\" # enter Thingspeak", "thingspeakChannelWriteApiKey) subfield = \"channels/{:s}/subscribe/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) thing.start() tmo = 0", "'Connected') mqtt.subscribe('test') mqtt.publish('test', 'Hi from Micropython') mqtt.stop() ''' # ==================", "thingSpeakChanelFormat = \"json\" pubchan = \"channels/{:s}/publish/{:s}\".format(thingspeakChannelId, thingspeakChannelWriteApiKey) pubfield = \"channels/{:s}/publish/fields/field{}/{:s}\".format(thingspeakChannelId,", "of those fields separated b< ';': # \"field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value\" thing.publish(pubchan, \"field1=25.2;status=On", "Message:\\n\".format(msg[0], msg[1]), msg[2]) thing = network.mqtt(\"thingspeak\", \"mqtt://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True,", "= 0 while thing.status()[0] != 2: utime.sleep_ms(100) tmo += 1", "pubfield = \"channels/{:s}/publish/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) subchan = \"channels/{:s}/subscribe/{:s}/{:s}\".format(thingspeakChannelId, thingSpeakChanelFormat, thingspeakChannelWriteApiKey)", "tmo > 80: print(\"Not connected\") break # subscribe to channel", "thing.start() tmo = 0 while thing.status()[0] != 2: utime.sleep_ms(100) tmo", "print(\"[{}] Disconnected\".format(task)) def subscb(task): print(\"[{}] Subscribed\".format(task)) def pubcb(pub): print(\"[{}] Published:", "\"mqtts//iot.eclipse.org\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # wsmqtt =", "print(\"[{}] Data arrived from topic: {}, Message:\\n\".format(msg[0], msg[1]), msg[2]) mqtt", "or secure connection #thing = network.mqtt(\"thingspeak\", \"mqtts://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True,", "# ================== import network def datacb(msg): print(\"[{}] Data arrived from", "pubcb(pub): print(\"[{}] Published: {}\".format(pub[0], pub[1])) def datacb(msg): print(\"[{}] Data arrived", "Channel ID thingspeakChannelWriteApiKey = \"ThingspeakWriteAPIKey\" # EDIT - enter Thingspeak", "Write API Key thingspeakFieldNo = 1 thingSpeakChanelFormat = \"json\" pubchan", "\"json\" pubchan = \"channels/{:s}/publish/{:s}\".format(thingspeakChannelId, thingspeakChannelWriteApiKey) pubfield = \"channels/{:s}/publish/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey)", "> 80: print(\"Not connected\") break # subscribe to channel thing.subscribe(subchan)", "subscribe to channel thing.subscribe(subchan) # subscribe to field thing.subscribe(subfield) #", "to field thing.subscribe(subfield) # publish to channel # Payload can", "arrived from topic: {}, Message:\\n\".format(msg[0], msg[1]), msg[2]) thing = network.mqtt(\"thingspeak\",", "= network.mqtt(\"thingspeak\", \"mqtts://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) thingspeakChannelId = \"123456\"", "def pubcb(pub): print(\"[{}] Published: {}\".format(pub[0], pub[1])) def datacb(msg): print(\"[{}] Data", "ID thingspeakChannelWriteApiKey = \"ThingspeakWriteAPIKey\" # EDIT - enter Thingspeak Write", "= network.mqtt(\"loboris\", \"mqtt://loboris.eu\", user=\"wifimcu\", password=\"<PASSWORD>\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb,", "''' # ================== # ThingSpeak example # ================== import network", "# mqtts = network.mqtt(\"eclipse\", \"mqtts//iot.eclipse.org\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb,", "secure connection requires more memory and may not work #", "if tmo > 80: print(\"Not connected\") break # subscribe to", "Payload can include any of those fields separated b< ';':", "1 if tmo > 80: print(\"Not connected\") break # subscribe", "# wsmqtt = network.mqtt(\"eclipse\", \"ws://iot.eclipse.org:80/ws\", cleansession=True, data_cb=datacb) mqtt.start() #mqtt.config(lwt_topic='status', lwt_msg='Disconected')", "print(\"[{}] Connected\".format(task)) def disconncb(task): print(\"[{}] Disconnected\".format(task)) def subscb(task): print(\"[{}] Subscribed\".format(task))", "cleansession=True, data_cb=datacb) mqtt.start() #mqtt.config(lwt_topic='status', lwt_msg='Disconected') ''' # Wait until status", "network.mqtt(\"eclipse\", \"ws://iot.eclipse.org:80/ws\", cleansession=True, data_cb=datacb) mqtt.start() #mqtt.config(lwt_topic='status', lwt_msg='Disconected') ''' # Wait", "# secure connection requires more memory and may not work", "mqtt = network.mqtt(\"loboris\", \"mqtt://loboris.eu\", user=\"wifimcu\", password=\"<PASSWORD>\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb,", "arrived from topic: {}, Message:\\n\".format(msg[0], msg[1]), msg[2]) mqtt = network.mqtt(\"loboris\",", "API Key thingspeakFieldNo = 1 thingSpeakChanelFormat = \"json\" pubchan =", "utime.sleep_ms(100) tmo += 1 if tmo > 80: print(\"Not connected\")", "EDIT - enter Thingspeak Write API Key thingspeakFieldNo = 1", "import network def datacb(msg): print(\"[{}] Data arrived from topic: {},", "network def datacb(msg): print(\"[{}] Data arrived from topic: {}, Message:\\n\".format(msg[0],", "print(\"Not connected\") break # subscribe to channel thing.subscribe(subchan) # subscribe", "1 thingSpeakChanelFormat = \"json\" pubchan = \"channels/{:s}/publish/{:s}\".format(thingspeakChannelId, thingspeakChannelWriteApiKey) pubfield =", "Data arrived from topic: {}, Message:\\n\".format(msg[0], msg[1]), msg[2]) mqtt =", "msg[1]), msg[2]) thing = network.mqtt(\"thingspeak\", \"mqtt://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb)", "{}\".format(pub[0], pub[1])) def datacb(msg): print(\"[{}] Data arrived from topic: {},", "while thing.status()[0] != 2: utime.sleep_ms(100) tmo += 1 if tmo", "print(\"[{}] Subscribed\".format(task)) def pubcb(pub): print(\"[{}] Published: {}\".format(pub[0], pub[1])) def datacb(msg):", "def subscb(task): print(\"[{}] Subscribed\".format(task)) def pubcb(pub): print(\"[{}] Published: {}\".format(pub[0], pub[1]))", "#mqtt.config(lwt_topic='status', lwt_msg='Disconected') ''' # Wait until status is: (1, 'Connected')", "thingspeakChannelWriteApiKey) subchan = \"channels/{:s}/subscribe/{:s}/{:s}\".format(thingspeakChannelId, thingSpeakChanelFormat, thingspeakChannelWriteApiKey) subfield = \"channels/{:s}/subscribe/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo,", "channel thing.subscribe(subchan) # subscribe to field thing.subscribe(subfield) # publish to", "thing.subscribe(subfield) # publish to channel # Payload can include any", "# publish to channel # Payload can include any of", "network.mqtt(\"loboris\", \"mqtt://loboris.eu\", user=\"wifimcu\", password=\"<PASSWORD>\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb)", "\"mqtts://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) thingspeakChannelId = \"123456\" # enter", "msg[2]) mqtt = network.mqtt(\"loboris\", \"mqtt://loboris.eu\", user=\"wifimcu\", password=\"<PASSWORD>\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb,", "cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # secure connection requires", "# ================== # ThingSpeak example # ================== import network def", "Published: {}\".format(pub[0], pub[1])) def datacb(msg): print(\"[{}] Data arrived from topic:", "pubchan = \"channels/{:s}/publish/{:s}\".format(thingspeakChannelId, thingspeakChannelWriteApiKey) pubfield = \"channels/{:s}/publish/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) subchan", "''' # Wait until status is: (1, 'Connected') mqtt.subscribe('test') mqtt.publish('test',", "(1, 'Connected') mqtt.subscribe('test') mqtt.publish('test', 'Hi from Micropython') mqtt.stop() ''' #", "b< ';': # \"field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value\" thing.publish(pubchan, \"field1=25.2;status=On line\") # Publish to", "mqtt.publish('test', 'Hi from Micropython') mqtt.stop() ''' # ================== # ThingSpeak", "80: print(\"Not connected\") break # subscribe to channel thing.subscribe(subchan) #", "data_cb=datacb) # wsmqtt = network.mqtt(\"eclipse\", \"ws://iot.eclipse.org:80/ws\", cleansession=True, data_cb=datacb) mqtt.start() #mqtt.config(lwt_topic='status',", "published_cb=pubcb, data_cb=datacb) # secure connection requires more memory and may", "password=\"<PASSWORD>\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # secure connection", "\"ThingspeakWriteAPIKey\" # EDIT - enter Thingspeak Write API Key thingspeakFieldNo", "- enter Thingspeak Write API Key thingspeakFieldNo = 1 thingSpeakChanelFormat", "disconncb(task): print(\"[{}] Disconnected\".format(task)) def subscb(task): print(\"[{}] Subscribed\".format(task)) def pubcb(pub): print(\"[{}]", "include any of those fields separated b< ';': # \"field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value\"", "cleansession=True, data_cb=datacb) thingspeakChannelId = \"123456\" # enter Thingspeak Channel ID", "def datacb(msg): print(\"[{}] Data arrived from topic: {}, Message:\\n\".format(msg[0], msg[1]),", "password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) thingspeakChannelId = \"123456\" # enter Thingspeak Channel", "mqtt.start() #mqtt.config(lwt_topic='status', lwt_msg='Disconected') ''' # Wait until status is: (1,", "lwt_msg='Disconected') ''' # Wait until status is: (1, 'Connected') mqtt.subscribe('test')", "Micropython') mqtt.stop() ''' # ================== # ThingSpeak example # ==================", "tmo = 0 while thing.status()[0] != 2: utime.sleep_ms(100) tmo +=", "= \"json\" pubchan = \"channels/{:s}/publish/{:s}\".format(thingspeakChannelId, thingspeakChannelWriteApiKey) pubfield = \"channels/{:s}/publish/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo,", "# Payload can include any of those fields separated b<", "data_cb=datacb) # secure connection requires more memory and may not", "more memory and may not work # mqtts = network.mqtt(\"eclipse\",", "network.mqtt(\"thingspeak\", \"mqtt://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) # or secure connection", "until status is: (1, 'Connected') mqtt.subscribe('test') mqtt.publish('test', 'Hi from Micropython')", "{}, Message:\\n\".format(msg[0], msg[1]), msg[2]) thing = network.mqtt(\"thingspeak\", \"mqtt://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\",", "to channel thing.subscribe(subchan) # subscribe to field thing.subscribe(subfield) # publish", "msg[2]) thing = network.mqtt(\"thingspeak\", \"mqtt://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) #", "enter Thingspeak Channel ID thingspeakChannelWriteApiKey = \"ThingspeakWriteAPIKey\" # EDIT -", "enter Thingspeak Write API Key thingspeakFieldNo = 1 thingSpeakChanelFormat =", "thingspeakFieldNo, thingspeakChannelWriteApiKey) subchan = \"channels/{:s}/subscribe/{:s}/{:s}\".format(thingspeakChannelId, thingSpeakChanelFormat, thingspeakChannelWriteApiKey) subfield = \"channels/{:s}/subscribe/fields/field{}/{:s}\".format(thingspeakChannelId,", "and may not work # mqtts = network.mqtt(\"eclipse\", \"mqtts//iot.eclipse.org\", cleansession=True,", "disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # secure connection requires more memory", "may not work # mqtts = network.mqtt(\"eclipse\", \"mqtts//iot.eclipse.org\", cleansession=True, connected_cb=conncb,", "\"channels/{:s}/publish/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) subchan = \"channels/{:s}/subscribe/{:s}/{:s}\".format(thingspeakChannelId, thingSpeakChanelFormat, thingspeakChannelWriteApiKey) subfield =", "2: utime.sleep_ms(100) tmo += 1 if tmo > 80: print(\"Not", "subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # secure connection requires more memory and", "from topic: {}, Message:\\n\".format(msg[0], msg[1]), msg[2]) thing = network.mqtt(\"thingspeak\", \"mqtt://mqtt.thingspeak.com\",", "thingspeakChannelId = \"123456\" # enter Thingspeak Channel ID thingspeakChannelWriteApiKey =", "# EDIT - enter Thingspeak Write API Key thingspeakFieldNo =", "print(\"[{}] Data arrived from topic: {}, Message:\\n\".format(msg[0], msg[1]), msg[2]) thing", "================== # ThingSpeak example # ================== import network def datacb(msg):", "network def conncb(task): print(\"[{}] Connected\".format(task)) def disconncb(task): print(\"[{}] Disconnected\".format(task)) def", "work # mqtts = network.mqtt(\"eclipse\", \"mqtts//iot.eclipse.org\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb,", "is: (1, 'Connected') mqtt.subscribe('test') mqtt.publish('test', 'Hi from Micropython') mqtt.stop() '''", "Key thingspeakFieldNo = 1 thingSpeakChanelFormat = \"json\" pubchan = \"channels/{:s}/publish/{:s}\".format(thingspeakChannelId,", "# Wait until status is: (1, 'Connected') mqtt.subscribe('test') mqtt.publish('test', 'Hi", "0 while thing.status()[0] != 2: utime.sleep_ms(100) tmo += 1 if", "from Micropython') mqtt.stop() ''' # ================== # ThingSpeak example #", "topic: {}, Message:\\n\".format(msg[0], msg[1]), msg[2]) mqtt = network.mqtt(\"loboris\", \"mqtt://loboris.eu\", user=\"wifimcu\",", "mqtt.stop() ''' # ================== # ThingSpeak example # ================== import", "connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # secure connection requires more", "Thingspeak Channel ID thingspeakChannelWriteApiKey = \"ThingspeakWriteAPIKey\" # EDIT - enter", "thingspeakFieldNo = 1 thingSpeakChanelFormat = \"json\" pubchan = \"channels/{:s}/publish/{:s}\".format(thingspeakChannelId, thingspeakChannelWriteApiKey)", "= \"channels/{:s}/subscribe/{:s}/{:s}\".format(thingspeakChannelId, thingSpeakChanelFormat, thingspeakChannelWriteApiKey) subfield = \"channels/{:s}/subscribe/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) thing.start()", "\"mqtt://loboris.eu\", user=\"wifimcu\", password=\"<PASSWORD>\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) #", "'Hi from Micropython') mqtt.stop() ''' # ================== # ThingSpeak example", "= \"123456\" # enter Thingspeak Channel ID thingspeakChannelWriteApiKey = \"ThingspeakWriteAPIKey\"", "+= 1 if tmo > 80: print(\"Not connected\") break #", "data_cb=datacb) thingspeakChannelId = \"123456\" # enter Thingspeak Channel ID thingspeakChannelWriteApiKey", "password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) # or secure connection #thing = network.mqtt(\"thingspeak\",", "data_cb=datacb) mqtt.start() #mqtt.config(lwt_topic='status', lwt_msg='Disconected') ''' # Wait until status is:", "example # ================== import network def datacb(msg): print(\"[{}] Data arrived", "data_cb=datacb) # or secure connection #thing = network.mqtt(\"thingspeak\", \"mqtts://mqtt.thingspeak.com\", user=\"anyName\",", "Thingspeak Write API Key thingspeakFieldNo = 1 thingSpeakChanelFormat = \"json\"", "thingspeakChannelWriteApiKey) pubfield = \"channels/{:s}/publish/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) subchan = \"channels/{:s}/subscribe/{:s}/{:s}\".format(thingspeakChannelId, thingSpeakChanelFormat,", "#thing = network.mqtt(\"thingspeak\", \"mqtts://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) thingspeakChannelId =", "# enter Thingspeak Channel ID thingspeakChannelWriteApiKey = \"ThingspeakWriteAPIKey\" # EDIT", "= \"channels/{:s}/subscribe/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) thing.start() tmo = 0 while thing.status()[0]", "!= 2: utime.sleep_ms(100) tmo += 1 if tmo > 80:", "tmo += 1 if tmo > 80: print(\"Not connected\") break", "Wait until status is: (1, 'Connected') mqtt.subscribe('test') mqtt.publish('test', 'Hi from", "subfield = \"channels/{:s}/subscribe/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) thing.start() tmo = 0 while", "\"mqtt://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) # or secure connection #thing", "\"channels/{:s}/subscribe/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) thing.start() tmo = 0 while thing.status()[0] !=", "those fields separated b< ';': # \"field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value\" thing.publish(pubchan, \"field1=25.2;status=On line\")", "mqtt.subscribe('test') mqtt.publish('test', 'Hi from Micropython') mqtt.stop() ''' # ================== #", "thingspeakChannelWriteApiKey = \"ThingspeakWriteAPIKey\" # EDIT - enter Thingspeak Write API", "import network def conncb(task): print(\"[{}] Connected\".format(task)) def disconncb(task): print(\"[{}] Disconnected\".format(task))", "requires more memory and may not work # mqtts =", "mqtts = network.mqtt(\"eclipse\", \"mqtts//iot.eclipse.org\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb)", "any of those fields separated b< ';': # \"field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value\" thing.publish(pubchan,", "cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) # wsmqtt = network.mqtt(\"eclipse\",", "thingspeakChannelWriteApiKey) thing.start() tmo = 0 while thing.status()[0] != 2: utime.sleep_ms(100)", "separated b< ';': # \"field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value\" thing.publish(pubchan, \"field1=25.2;status=On line\") # Publish", "';': # \"field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value\" thing.publish(pubchan, \"field1=25.2;status=On line\") # Publish to field", "================== import network def datacb(msg): print(\"[{}] Data arrived from topic:", "break # subscribe to channel thing.subscribe(subchan) # subscribe to field", "# or secure connection #thing = network.mqtt(\"thingspeak\", \"mqtts://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\",", "Message:\\n\".format(msg[0], msg[1]), msg[2]) mqtt = network.mqtt(\"loboris\", \"mqtt://loboris.eu\", user=\"wifimcu\", password=\"<PASSWORD>\", cleansession=True,", "# ThingSpeak example # ================== import network def datacb(msg): print(\"[{}]", "subscribe to field thing.subscribe(subfield) # publish to channel # Payload", "pub[1])) def datacb(msg): print(\"[{}] Data arrived from topic: {}, Message:\\n\".format(msg[0],", "# subscribe to field thing.subscribe(subfield) # publish to channel #", "to channel # Payload can include any of those fields", "field thing.subscribe(subfield) # publish to channel # Payload can include", "\"channels/{:s}/subscribe/{:s}/{:s}\".format(thingspeakChannelId, thingSpeakChanelFormat, thingspeakChannelWriteApiKey) subfield = \"channels/{:s}/subscribe/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) thing.start() tmo", "connected\") break # subscribe to channel thing.subscribe(subchan) # subscribe to", "fields separated b< ';': # \"field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value\" thing.publish(pubchan, \"field1=25.2;status=On line\") #", "\"field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value\" thing.publish(pubchan, \"field1=25.2;status=On line\") # Publish to field thing.publish(pubfield, \"24.5\")", "= network.mqtt(\"eclipse\", \"mqtts//iot.eclipse.org\", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb) #", "= \"channels/{:s}/publish/{:s}\".format(thingspeakChannelId, thingspeakChannelWriteApiKey) pubfield = \"channels/{:s}/publish/fields/field{}/{:s}\".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey) subchan =", "= network.mqtt(\"thingspeak\", \"mqtt://mqtt.thingspeak.com\", user=\"anyName\", password=\"<PASSWORD>\", cleansession=True, data_cb=datacb) # or secure", "# \"field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value\" thing.publish(pubchan, \"field1=25.2;status=On line\") # Publish to field thing.publish(pubfield," ]
[ "<filename>mlb/game/migrations/0009_game_game_type.py # Generated by Django 2.2.8 on 2019-12-14 19:07 from", "[ ('game', '0008_auto_20191214_1019'), ] operations = [ migrations.AddField( model_name='game', name='game_type',", "field=models.CharField(choices=[('E', 'Exhibition'), ('S', 'Spring Training'), ('R', 'Regular Season'), ('F', 'Wild", "19:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "'Regular Season'), ('F', 'Wild Card'), ('D', 'Divisional Series'), ('L', 'League", "Series'), ('L', 'League Championship Series'), ('W', 'World Series')], default='R', max_length=30),", "'0008_auto_20191214_1019'), ] operations = [ migrations.AddField( model_name='game', name='game_type', field=models.CharField(choices=[('E', 'Exhibition'),", "by Django 2.2.8 on 2019-12-14 19:07 from django.db import migrations,", "dependencies = [ ('game', '0008_auto_20191214_1019'), ] operations = [ migrations.AddField(", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('game',", "model_name='game', name='game_type', field=models.CharField(choices=[('E', 'Exhibition'), ('S', 'Spring Training'), ('R', 'Regular Season'),", "2019-12-14 19:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "('L', 'League Championship Series'), ('W', 'World Series')], default='R', max_length=30), ),", "migrations.AddField( model_name='game', name='game_type', field=models.CharField(choices=[('E', 'Exhibition'), ('S', 'Spring Training'), ('R', 'Regular", "Card'), ('D', 'Divisional Series'), ('L', 'League Championship Series'), ('W', 'World", "'Wild Card'), ('D', 'Divisional Series'), ('L', 'League Championship Series'), ('W',", "'Spring Training'), ('R', 'Regular Season'), ('F', 'Wild Card'), ('D', 'Divisional", "[ migrations.AddField( model_name='game', name='game_type', field=models.CharField(choices=[('E', 'Exhibition'), ('S', 'Spring Training'), ('R',", "Generated by Django 2.2.8 on 2019-12-14 19:07 from django.db import", "# Generated by Django 2.2.8 on 2019-12-14 19:07 from django.db", "= [ migrations.AddField( model_name='game', name='game_type', field=models.CharField(choices=[('E', 'Exhibition'), ('S', 'Spring Training'),", "name='game_type', field=models.CharField(choices=[('E', 'Exhibition'), ('S', 'Spring Training'), ('R', 'Regular Season'), ('F',", "('D', 'Divisional Series'), ('L', 'League Championship Series'), ('W', 'World Series')],", "] operations = [ migrations.AddField( model_name='game', name='game_type', field=models.CharField(choices=[('E', 'Exhibition'), ('S',", "Training'), ('R', 'Regular Season'), ('F', 'Wild Card'), ('D', 'Divisional Series'),", "Migration(migrations.Migration): dependencies = [ ('game', '0008_auto_20191214_1019'), ] operations = [", "Season'), ('F', 'Wild Card'), ('D', 'Divisional Series'), ('L', 'League Championship", "= [ ('game', '0008_auto_20191214_1019'), ] operations = [ migrations.AddField( model_name='game',", "('R', 'Regular Season'), ('F', 'Wild Card'), ('D', 'Divisional Series'), ('L',", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('game', '0008_auto_20191214_1019'),", "('game', '0008_auto_20191214_1019'), ] operations = [ migrations.AddField( model_name='game', name='game_type', field=models.CharField(choices=[('E',", "on 2019-12-14 19:07 from django.db import migrations, models class Migration(migrations.Migration):", "Django 2.2.8 on 2019-12-14 19:07 from django.db import migrations, models", "models class Migration(migrations.Migration): dependencies = [ ('game', '0008_auto_20191214_1019'), ] operations", "operations = [ migrations.AddField( model_name='game', name='game_type', field=models.CharField(choices=[('E', 'Exhibition'), ('S', 'Spring", "'League Championship Series'), ('W', 'World Series')], default='R', max_length=30), ), ]", "class Migration(migrations.Migration): dependencies = [ ('game', '0008_auto_20191214_1019'), ] operations =", "'Exhibition'), ('S', 'Spring Training'), ('R', 'Regular Season'), ('F', 'Wild Card'),", "('F', 'Wild Card'), ('D', 'Divisional Series'), ('L', 'League Championship Series'),", "('S', 'Spring Training'), ('R', 'Regular Season'), ('F', 'Wild Card'), ('D',", "migrations, models class Migration(migrations.Migration): dependencies = [ ('game', '0008_auto_20191214_1019'), ]", "'Divisional Series'), ('L', 'League Championship Series'), ('W', 'World Series')], default='R',", "2.2.8 on 2019-12-14 19:07 from django.db import migrations, models class" ]
[ "[ (['This', 'is', 'a', 'list'], 'Thisisalist'), (['The', 'quick', 'brown', 'fox',", "which one is the answer. To look at all possible", "indexing (subscripting). You will need `range`. You will need `len`.", "expression. For example, if you were looking for the function", "an `else`. There is no reason to ever set the", "as argument. It's a bit like you're giving the argument", "functions and methods\" class print_functions(VerbatimStep): \"\"\" It's time to expand", "2, 10, 18, 4, 12, 10]), ([0, 1, 2, 3],", "if the value isn't there. You may recognise some of", "types of values which can be mutated are *mutable*, while", "valid index for both strings. You will need to check", "*index*. You've probably noticed that the first index is 0,", "62, 49]`? 'biggest' or 'largest' 'python biggest value in list'", "the longest string>)`\", \"In other words you need to find", "word.append('!') final_text = \"\"\" The word 'attribute' in the error", "element in a for loop. Start with an empty list.", "of the variables, e.g. `list1 = [7, 8, 9]`, the", "means that the last valid index of the list is", "program(self): word = 'Hello' word.append('!') final_text = \"\"\" The word", "add together list of strings with string in between -", "`words[4]` and beyond don't exist, so trying that will give", "value at an index. `nums[0]` is 1, `nums[1]` is 2,", "Suppose we have a list `nums = [1, 2, 3]`.", "is no reason to ever set the variable to `False`", "to end a loop early\" class list_contains_exercise(ExerciseStep): \"\"\" Exercise: write", "The only exception is the `pop` method. Modifying a value", "work with strings, a bit as if strings are lists", "4]`. - **`len`**: Returns the number of elements. `len(nums)` is", "of values which can be mutated are *mutable*, while those", "- **`join`**: Add a list of strings with a separator", "we've learned, not just for characters but for any substring.", "the information dump and I'd like it to be a", "it can add up a list of strings instead of", "a `for` loop. You will need indexing (subscripting). You will", "position' 'python add value at index' \"\"\" program = \"nums.insert(2,", "end. If you find the element in the list you", "the error actually comes just from `word.append`, without even a", "error if the value isn't there. You may recognise some", "found = True print(found) tests = [ ((['This', 'is', 'a',", "program(self): word = 'Hello' print(word.upper) print(word.upper()) class no_append_for_str(VerbatimStep): \"\"\" Another", "number of elements in a list (commonly called the *length*)", "numbers = [3, 1, 4, 1, 5, 9] total =", "about a powerful new type of value called lists. Here's", "program(self): words = ['This', 'is', 'a', 'list'] print(words[0]) print(words[1]) print(words[2])", "i in range(10): print(i) class range_len(VerbatimStep): \"\"\" `range(n)` is similar", "- python test if list has element - `index` -", "given: numbers = [3, 1, 4, 1, 5, 9, 2,", "need a loop over `range(len(things))`. To check if an index", "a list contains 5, but there's no similarly easy way", "__program_indented__ \"\"\" # noinspection PyUnresolvedReferences def program(self): word = 'Hello'", "strings character by character. Make a new list, and then", "for number in all_numbers: if number <= 5: small_numbers.append(number) else:", "loops for a moment. How would you print just the", "small_numbers.append(number) else: big_numbers.append(number) print(small_numbers) print(big_numbers) The button will open a", "error message about `None` or `NoneType`, it often means you", "in a list. `2 in nums` is `True`, but `4", "numbers new_numbers += [5] print(new_numbers) With that knowledge, write a", "expression, e.g. if word.lower() == 'yes': \"\"\" class UnderstandingProgramsWithPythonTutor(Page): final_text", "range(...)`, `i` will sometimes be too big \" \"to be", "removed. This shifts the rest of the numbers left one", "built in function to give you these values, called `range`:", "just writing `[x]`. You can add an element to a", "`len(string2)`. You've already done an exercise like that.\", \"Once you've", "third elements: [1, 2, 9, 3, 4, 5] Call the", "exist, so trying that will give you an error. By", "will also see the word ***parameter***, which means basically the", "typical ways you might Google the above functions if you", "to find information without any googling. Try `__program__` in the", "char2 = string2[i] print(char1 + ' ' + char2) tests", "contents. Similarly, you could loop over the original and modify", "`len` - python size of list - python number of", "value at index' \"\"\" program = \"nums.insert(2, 9)\" def check(self):", "the list. `[1, 2, 3, 2, 7, 2, 5].count(2)` is", "You will need a `for` loop. You will need indexing", "number <= 10: numbers.pop(i) print(numbers) (remember that `numbers.pop(i)` removes the", "is 5 Note that in most cases, methods which modify", "known position. Here's how: __program_indented__ \"\"\" def program(self): words =", "will need a loop. You will need an `if` statement.", "methods\" class print_functions(VerbatimStep): \"\"\" It's time to expand your vocabulary", "1, 4, 1, 5, 9] total = 0 for number", "functions are ***callable***: __program_indented__ \"\"\" def program(self): print(callable(len)) class not_callable(VerbatimStep):", "return `None` by default. If you see an error message", "is list2` is `True`, because *there is only one list*,", "been doubled. For example, given: numbers = [3, 1, 4,", "fundamental skills. For example, you can use `in` to check", "they are still two separate, distinct, individual lists. As a", "'' for word in words: total += word print(total) tests", "1, 2, ... as it's supposed to, but as the", "= \"words[4]\" def check(self): return \"IndexError\" in self.result class introducing_len_and_range(VerbatimStep):", "turns out this does the same thing, for the same", "= word.upper() Or you can use `word.upper()` immediately in a", "`is`. Here `list1 is list2` is `False`. That means that", "There you can navigate through the program step by step", "will need an `if` statement. You will need a comparison", "= [1, 2, 3]`. You can use: - **`append`**: Add", "`lower` are methods of strings, which are called with e.g.", "+= [to_find] * random.randint(1, 3) random.shuffle(things) return dict( things=things, to_find=to_find,", "need `len`. You will need `+`. You will need to", "slider left or right. You can also see the values", "found the element, you can't unfind it. That means that", "list of numbers - python total of numbers - `in`", "`True` - `'feed the dog and the cat'.count('the')` is 2", "given index. `nums.pop(3)` removes `nums[3]` (`81`) from the list and", "1, 2, 3, 4, 5, 6, 6], 6), 7), ]", "numbers[i] if number <= 10: numbers.pop(i) print(numbers) (remember that `numbers.pop(i)`", "gives us an alternative way to loop over a list:", "\"\"\" You're almost there! However, this prints all the indices,", "you were looking for the function `sum`, you could write", "else: thing_to_find = random.choice([ min(things) - 1, max(things) + 1,", "1, 5, 9, 2, 6, 5], [9, 6]), ([0, 2,", "class strings_sum(ExerciseStep): \"\"\" Now modify the program so that it", "4, 6, 8, 10], [6, 8, 10]), ] final_text =", "'python' and 'list' in your search query. In one word,", "string because numbers and strings are incompatible. Is there a", "thing_to_find: found = True break This is just as correct", "`nums + [4, 5]` is `[1, 2, 3, 4, 5]`.", "d y e and for: string1 = \"Hello\" string2 =", "in the shell. - **`subscript assignment`**: Set a value at", "it ____________? 'in the middle' or 'at an index' or", "visualises the difference. In the second case, the two variables", "it to go between the second and third elements: [1,", "evaluate to a number such as 3, in which case", "vocabulary some more. `print` and `len` are ***functions***. See for", "no reason to ever set the variable to `False` inside", "be called on all values of that type using `.`.", "`len` *accepts* or *receives* the argument. `len(things)` will evaluate to", "lists are *iterable*, meaning you can iterate over them with", "at an index. `nums[0] = 9` changes the list to", "up a new list from scratch. In this case, we've", "(([1, 2, 3, 4], 0), False), ] @classmethod def generate_inputs(cls):", "print the first index of `to_find` in the list, i.e.", "and `len` are ***functions***. See for yourself: __program_indented__ \"\"\" def", "things = ['on', 'the', 'way', 'to', 'the', 'store'] to_find =", "word.upper() The string referred to by `word` isn't modified, instead", "variable: word = word.upper() Or you can use `word.upper()` immediately", "For example, `upper` and `lower` are methods of strings, which", "are some typical ways you might Google the above functions", "words: List[str]): total = '' for word in words: total", "dump and I'd like it to be a little more", "n - 2, n - 1]`. This gives us an", "*mutation* - types of values which can be mutated are", "it will return `91`. You should write the answer in", "values which can be mutated are *mutable*, while those that", "write that, you are ***calling*** the function `len` or `print`.", "64]`. Raises an error if the value doesn't exist. Equivalent", "char1 = string1[i] else: char1 = ' ' if i", "that variable to `True`. Once you've found the element, you", "e.g: string1 = \"Hello\" string2 = \"World\" print them vertically", "is 1. Raises an error if the value isn't there.", "like this: for i in range(len(string1)): char1 = string1[i] char2", "will need to set e.g. `char1 = ' '` when", "and checks once it finds the element. You can use", "work with lists. Suppose we have a list `nums =", "Lists and strings have a lot in common. For example,", "example, given the list `[21, 55, 4, 91, 62, 49]`,", "print(list2) print(list1 == list2) print(list1 is list2) list1.append(4) print(list1) print(list2)", "2, 3] length = len(things) printed = print(length) print(printed) class", "list and you'll see some familiar methods. Here are a", "4, 91, 62, 49])`. Don't solve this manually with a", "possible indices of `things` and check which one is the", "final_text = \"\"\" Now `list1 is list2` is `True`, because", "are incompatible. Is there a similar concept among strings to", "it's supposed to, but as the list changes those are", "- 2, len(words) - 1] There's a handy built in", "for any substring. For example: - `'the' in 'feed the", "takes a list and a value and checks if the", "numbers = [10, 7, 8, 3, 12, 15] for number", "something like: for i in range(...): ... print(char1 + '", "print(small_numbers) print(big_numbers) The button will open a new tab with", "index, you need to stop the loop once you find", "+ char2) tests = { (\"Goodbye\", \"World\"): dedent(\"\"\"\\ G W", "be at the end, you want it to go between", "the loop. \"\"\" @returns_stdout def solution(self, things, thing_to_find): found =", "cat'.index('the')` is 5 Note that in most cases, methods which", "Python Tutor to see how it visualises the difference. In", "probably looks something like this: for i in range(len(string1)): char1", "5]` is `[1, 2, 3, 4, 5]`. Here's some new", "Strings also support some of the new methods we've learned,", "`nums[0] = 9` changes the list to `[9, 2, 3]`.", "solution(self, things, thing_to_find): found = False for thing in things:", "[0, 1, 2, ..., len(words) - 2, len(words) - 1]", "index greater than that? \"\"\" program = \"words[4]\" def check(self):", "0 and `number` is 10, which gets removed. This shifts", "time to learn some technical details that are often misunderstood", "the *index*. You've probably noticed that the first index is", "list you should set that variable to `True`. Once you've", "all values of that type using `.`. For example, `upper`", "trying to call them will give you an error: __program_indented__", "to both strings each time to retrieve matching characters. \"\"\"", "'biggest' or 'largest' 'python biggest value in list' \"\"\" program", "with indexing and `len()` with strings in the shell? Forget", "' print(char1 + ' ' + char2) tests = {", "numbers.copy(): Now the list being modified and the list being", "string2): length1 = len(string1) length2 = len(string2) if length1 >", "print(word.upper()) class no_append_for_str(VerbatimStep): \"\"\" Another example is that `append` is", "You can assume that `to_find` appears at least once. \"\"\"", "with a separator in between. This is a method of", "5] You could write `nums.append(9)` and `nums` would change to:", "or 'at an index' or 'at a particular position' 'python", "15] big_numbers = numbers.copy() for number in numbers: if number", "subscript assignment. You simply can't change a string - you", "[1, 2, 3] list2 = [1, 2, 3] print(list1) print(list2)", "[10, 7, 8, 3, 12, 15] big_numbers = numbers.copy() for", "length2 = length2, length1 return dict( string1=generate_string(length1), string2=generate_string(length2), ) final_text", "\"to be a valid index for both strings. You will", "Forget loops for a moment. How would you print just", "expressions inside to be the elements. 3. Put commas (`,`)", "0? A blank initial value? \"\"\" @returns_stdout def solution(self, words:", "separator string *between* each word. For example, given words =", "string1, string2): length1 = len(string1) length2 = len(string2) if length1", "print: Thisisalist \"\"\" hints = \"\"\" This is very similar", "Page, Step, VerbatimStep, search_ast from main.utils import returns_stdout class IntroducingLists(Page):", "you assign a new value to *either* of the variables,", "variables both have arrows pointing to a single list object.", "\"Next\" buttons, or drag the slider left or right. You", "< len(string2): char2 = string2[i] else: char2 = ' '", "the shell. Here's another exercise. Given two strings of equal", "] @classmethod def generate_inputs(cls): things = generate_list(str) to_find = generate_string()", "reminder. - You're struggling to solve a problem with lists", "to a string because numbers and strings are incompatible. Is", "the number of elements. `len(nums)` is `3`. - **`range`**: `range(n)`", "check which one is the answer. To look at all", "the variable to `True`, it should never be set to", "is to ***never modify something while you iterate over it***.", "first occurrence of the given element. `nums.remove(10)` will leave `nums`", "generate_inputs(cls): length1 = random.randrange(5, 11) length2 = random.randrange(12, 20) if", "= ['This', 'is', 'a', 'list'] it should print: Thisisalist \"\"\"", "numbers - `in` - python check if list contains value", "main.utils import returns_stdout class IntroducingLists(Page): class first_list(VerbatimStep): \"\"\" It's time", "For example, you can add two lists to combine them", "`remove`) merely return `None`, while the remaining functions/methods return a", "2] print(double) tests = [ ([3, 1, 4, 1, 5,", "'list' in your search query. Instead of putting the value", "see why this happens? The index variable `i` runs through", "indices. It even looks nicer this way. numbers = [10,", "else: big_numbers.append(number) print(small_numbers) print(big_numbers) The button will open a new", "the same list. I recommend running both versions with Python", "2, 3, 4], 1), True), (([1, 2, 3, 4], 0),", "between - `sum` - python add list of numbers -", "names and values](https://nedbatchelder.com/text/names.html). \"\"\" class ModifyingWhileIterating(Page): final_text = \"\"\" Consider", "would print: [9, 6] \"\"\" hints = \"\"\" This is", "want: all_numbers = [2, 4, 8, 1, 9, 7] small_numbers", "in the next iteration `i` is 1, and `numbers[i]` is", "output: H E e l l i l z o", "i < len(string1): char1 = string1[i] else: char1 = '", "o o r d l b d y e and", "index. `nums[0]` is 1, `nums[1]` is 2, `nums[2]` is 3.", "[] for number in numbers: if number > 5: big_numbers.append(number)", "number such as 3, in which case we say that", "for characters but for any substring. For example: - `'the'", "\"\"\" program = \"max([21, 55, 4, 91, 62, 49])\" def", "index_error(Step): \"\"\" In general, you can get the element at", "def generate_inputs(cls): length = random.randrange(5, 11) return dict( string1=generate_string(length), string2=generate_string(length),", "import ExerciseStep, MessageStep, Page, Step, VerbatimStep, search_ast from main.utils import", "Tutor. numbers = [10, 7, 8, 3, 12, 15] for", "answer, you will need to use: - `if` - the", "if you try getting an index greater than that? \"\"\"", "[6, 2, 8, 2, 10, 18, 4, 12, 10] \"\"\"", "numbers and removes the ones smaller than 10. Or at", "also be a mixture of types. To create a list", "\"\"\" @returns_stdout def solution(self, words: List[str]): total = '' for", "..., n - 2, n - 1]`. This gives us", "these, but `.append` will be more familiar and readable to", "is quite straightforward and mostly consists of things you're familiar", "first version again. If you come across this kind of", "can multiply numbers using `*`. This program is structurally very", "print(char1 + ' ' + char2) \"\"\"), \"What should go", "that has no elements. Check for yourself: numbers = [1,", "values of variables on the right. \"\"\" class EqualsVsIs(Page): title", "3 and doesn't remove them, and at the end it", "and returns a list of the elements in order. `sorted(nums)`", "result, when you append 4 to `list1`, only `list1` changes.", "not 1. In programming, counting starts at 0. It seems", "but there's no similarly easy way to check for a", "def solution(self, things, to_find): answer = None for i in", "2, 3, 4, 5, 6, 6], 6), 7), ] @returns_stdout", "while you iterate over it***. Keep mutation and looping separate.", "changes the list to `[9, 2, 3]`. - **`join`**: Add", "similar to the list `[0, 1, 2, ..., n -", "they start out with equal contents. Similarly, you could loop", "very similar to the programs you've written to build up", "to fix this problem by filling in 'missing' characters with", "to ***never modify something while you iterate over it***. Keep", "so they are equal: `list1 == list2` is `True`. But", "for word in words: print(word) class can_contain_anything(VerbatimStep): \"\"\" A list", "Iterating over a list still goes through the indices under", "and doesn't remove them, and at the end it fails", "[3, 1, 4, 1, 5, 9] total = 0 for", "these functions off by heart. class sum_list(Step): \"\"\" Let's review", "= False for thing in things: if thing == thing_to_find:", "index, not the first one. \"\"\" @returns_stdout def solution(self, things,", "directly, like above: 1. Write some square brackets: `[]` 2.", "search_ast from main.utils import returns_stdout class IntroducingLists(Page): class first_list(VerbatimStep): \"\"\"", "and methods\" class print_functions(VerbatimStep): \"\"\" It's time to expand your", "length, e.g: string1 = \"Hello\" string2 = \"World\" print them", "need a `for` loop. You will need indexing (subscripting). You", "should set that variable to `True`. Once you've found the", "will start with `__` which you can ignore for now", "strings with a separator in between. This is a method", "different lengths. In fact, it goes wrong in different ways", "new methods we've learned, not just for characters but for", "big enough to add. \"\"\" # TODO enforce not using", "For example, for things = ['on', 'the', 'way', 'to', 'the',", "that `numbers.pop(i)` removes the element from `numbers` at index `i`)", "has failed so you want to find it manually. -", "add value at index' \"\"\" program = \"nums.insert(2, 9)\" def", "a similar thing in an exercise: numbers = [10, 7,", "Here's some new things. Try them out in the shell.", "The solution is very similar to the program that adds", "if number <= 10: numbers.remove(number) print(numbers) But it turns out", "the lack of a real useful value. Functions that don't", "can use: - **`append`**: Add an element to the end", "time to retrieve matching characters. \"\"\" @returns_stdout def solution(self, string1,", "' '` when `string1[i]` is not valid.\", ] # TODO", "2, 3], [0, 2, 4, 6]), ] class filter_numbers(ExerciseStep): \"\"\"", "this kind of problem and you're still having trouble understanding", "things: if thing == thing_to_find: found = True print(found) tests", "in this list of 4 elements is 3. What happens", "can't change a string - you can only create new", "`False` inside the loop. \"\"\" @returns_stdout def solution(self, things, thing_to_find):", "`print`. The fact that this is possible means that functions", "\"\"\" Remember that you can multiply numbers using `*`. This", "simply can't change a string - you can only create", "e \"\"\"), (\"Hello\", \"Elizabeth\"): dedent(\"\"\"\\ H E e l l", "indices of `things` and check which one is the answer.", "which was immediately discarded. If you want to change the", "foundations. There are also ways to find information without any", "__program_indented__ \"\"\" # noinspection PyCallingNonCallable def program(self): f = 'a", "argument. `'--'.join(['apples', 'oranges', 'bananas'])` returns `'apples--oranges--bananas'`. You can also use", "noinspection PyUnresolvedReferences def program(self): word = 'Hello' word.append('!') final_text =", "list1` doesn't create an eternal link between the variables. If", "each string.\", \"You will need to set e.g. `char1 =", "list, write some expressions inside to be the elements. 3.", "' ' + char2) \"\"\"), \"What should go inside `range()`?", "the first index of `to_find` in the list, i.e. the", "string if you don't want a separator, e.g. `''.join(['apples', 'oranges',", "Great! When you want to add a single element to", "first character of each of the two strings? In the", "this way. numbers = [10, 7, 8, 3, 12, 15]", "of the previous solution, \" \"but it's significantly longer and", "will need a comparison operator. Specifically `==`. You need a", "5] it would print: [6, 2, 8, 2, 10, 18,", "at the beginning or end, we want to put it", "great, but often you just want to retrieve a single", "Use an `if` statement. Use a comparison operator to test", "d \"\"\" hints = \"\"\" Did you experiment with indexing", "nor `len(string2)` is good enough.\", \"You want a loop iteration", "use `remove` instead of `pop` so we don't have to", "== thing_to_find: found = True print(found) Your solution is probably", "12, 10] \"\"\" hints = \"\"\" Remember that you can", "goes wrong in different ways depending on whether `string1` or", "write the answer in the shell as a single small", "program = \"words[4]\" def check(self): return \"IndexError\" in self.result class", "position is called the *index*. You've probably noticed that the", "6), \"6\\n7\"), ] class last_index(MessageStep, ExerciseStep): \"\"\" You're almost there!", "inefficient. That's because it'll loop over the entire list even", "over a list still goes through the indices under the", "problem by filling in 'missing' characters with spaces. For example,", "list2) list1.append(4) print(list1) print(list2) final_text = \"\"\" Now `list1 is", "learn some technical details that are often misunderstood and lead", "There isn't really a big difference between these, but `.append`", "string: __program_indented__ \"\"\" # noinspection PyUnresolvedReferences def program(self): word =", "list1` and see what difference it makes. \"\"\" program_in_text =", "new list. Use an `if` statement. Use a comparison operator", "program with a list of strings? The problem is that", "argument appears in the list. `[1, 2, 3, 2, 7,", "- python add element to list - python add item", "functions off by heart. class sum_list(Step): \"\"\" Let's review how", "1, 4, 1, 5, 9, 2, 6, 5] it would", "here is to ***never modify something while you iterate over", "possible indices, you will need a loop over `range(len(things))`. To", "is a method of lists. But you can't use `.upper`", "== things[i]: print(i) break tests = [ ((['on', 'the', 'way',", "about `None` or `NoneType`, it often means you assigned the", "meaning you can iterate over them with a `for loop`.", "python get position of element - python get index of", "function to give you these values, called `range`: __program_indented__ \"\"\"", "vertically side by side, with a space between each character:", "- `join` - python combine list of strings with separator", "use an `else`. There is no reason to ever set", "check(self): return \"IndexError\" in self.result class introducing_len_and_range(VerbatimStep): \"\"\" There you", "your vocabulary some more. `print` and `len` are ***functions***. See", "= 'other' it should print `False`. \"\"\" hints = \"\"\"", "given element. `nums.remove(10)` will leave `nums` as `[28, 99, 81,", "case, the two variables both have arrows pointing to a", "'python biggest value in list' \"\"\" program = \"max([21, 55,", "often referred to as *elements*. They can be anything: numbers,", "and will require \" \"a few additional ideas and pieces.\",", "for number in numbers: if number > 10: big_numbers.append(number) print(big_numbers)", "out in the shell. - **`subscript assignment`**: Set a value", "loop. \"\"\" @returns_stdout def solution(self, things, thing_to_find): found = False", "range(len(words)): print(index) print(words[index]) class index_exercise(ExerciseStep): \"\"\" Let's get some exercise!", "are no longer the positions we want. For example in", "you assigned the wrong thing to a variable: __program_indented__ \"\"\"", "to the same list. But as we've learned before, `list2`", "Suppose `nums = [28, 99, 10, 81, 59, 64]` -", "even looks nicer this way. numbers = [10, 7, 8,", "index for both strings. You will need to check if", "useful value. So it returns something useless instead: __program_indented__ \"\"\"", "1, 2, ..., len(words) - 2, len(words) - 1] There's", "unnecessary iterations and checks once it finds the element. You", "itererated over are separate objects, even if they start out", "the variable: word = word.upper() Or you can use `word.upper()`", "4, 12, 10] \"\"\" hints = \"\"\" Remember that you", "a break, you've earned it! \"\"\" class CallingFunctionsTerminology(Page): title =", "+ char2) This doesn't work so well if the strings", "example, given: numbers = [3, 1, 4, 1, 5, 9,", "have any methods like `append` or even subscript assignment. You", "'the', 'store'], 'the'), 1), (([0, 1, 2, 3, 4, 5,", "element in the list you should set that variable to", "end of the list. `nums.append(4)` changes the list to `[1,", "are equal: `list1 == list2` is `True`. But then there's", "particular, it should still contain something like: for i in", "`range(len(nums))` is like `[0, 1, 2]`. - **`subscripting`**: Get a", "'way', 'to', 'the', 'store'] to_find = 'the' your program should", "class UsingBreak(Page): title = \"Using `break` to end a loop", "a value at an index. `nums[0] = 9` changes the", "in range(len(numbers)): number = numbers[i] if number <= 10: numbers.pop(i)", "random from textwrap import dedent from typing import List from", "or *receives* the argument. `len(things)` will evaluate to a number", "is a method of strings (the separator) which takes an", "def program(self): numbers = [3, 1, 4, 1, 5, 9]", "because *there is only one list*, and the two variables", "the `copy` method: list2 = list1.copy() This will make the", "new_numbers = [] new_numbers += numbers new_numbers += [5] print(new_numbers)", "in range(10): print(i) class range_len(VerbatimStep): \"\"\" `range(n)` is similar to", "For example, `print`'s job is to display something on screen,", "string.\", \"You will need to set e.g. `char1 = '", "method. Modifying a value directly is called *mutation* - types", "Modifying a value directly is called *mutation* - types of", "It's fine, but it's a bit inefficient. That's because it'll", "beginning. You can stop any loop using a `break` statement,", "7, 8, 3, 12, 15] for i in range(len(numbers)): number", "that regardless of the two lists being equal, they are", "represents the lack of a real useful value. Functions that", "to call them will give you an error: __program_indented__ \"\"\"", "boolean variable that you print at the end. If you", "59, 64]` - **`sorted`**: Takes an iterable and returns a", "\"`len(string1)` and `len(string2)`. You've already done an exercise like that.\",", "values of that type using `.`. For example, `upper` and", "\"\"\" # noinspection PyUnresolvedReferences def program(self): word = 'Hello' word.append('!')", "but that's how most programming languages do it, and it's", "is 2, `nums[2]` is 3. - **`+`**: Concatenates lists. `nums", "class UnderstandingProgramsWithPythonTutor(Page): final_text = \"\"\" It's time to learn about", "if you try running that program with a list of", "to_find=to_find, ) class zip_exercise(ExerciseStep): \"\"\" Nice! By the way, indexing", "element from `numbers` at index `i`) As it runs, it", "the function `len` or `print`. The fact that this is", "line you want to print the second character of each", "up pointing to the same list. But as we've learned", "strings with string in between - `sum` - python add", "useless statement on its own: word.upper() The string referred to", "With that knowledge, write a program which takes a list", "scroll to the end of the list and you'll see", "`if` statement. Use a comparison operator to test if a", "to the end of the list and you'll see some", "numbers: double += [number * 2] print(double) tests = [", "Try them out in the shell. - **`subscript assignment`**: Set", "number in numbers.copy(): Now the list being modified and the", "'missing' characters with spaces. For example, for: string1 = \"Goodbye\"", "for number in numbers: total += number print(total) class strings_sum(ExerciseStep):", "= \"World\" print them vertically side by side, with a", "back to basics and strengthen your foundations. There are also", "exist. Equivalent to `nums.pop(nums.index(10))`. - **`count`**: Returns the number of", "the use of `.` - the error actually comes just", "also work on strings. Try them out in the shell.", "`None` or `NoneType`, it often means you assigned the wrong", "actually more common to write: some_list.append(element) There isn't really a", "list is `len(words) - 1`, so the last element is", "doubled. For example, given: numbers = [3, 1, 4, 1,", "can only create new strings and use those instead. That", "In particular, `range(len(nums))` is like `[0, 1, 2]`. - **`subscripting`**:", "both lines are now just different ways of printing the", "an error if the value isn't there. You may recognise", "list Lists and strings have a lot in common. For", "in things: if thing == thing_to_find: found = True print(found)", "same list. `list1.append(4)` appends to the one list and the", "if number > 5: big_numbers.append(number) print(big_numbers) tests = [ ([3,", "6], 6), 7), ] @returns_stdout def solution(self, things, to_find): for", "example, you can add two lists to combine them together", "- **`sorted`**: Takes an iterable and returns a list of", "6, 8, 10], [6, 8, 10]), ] final_text = \"\"\"", "the new \"Python Tutor\" button. Here's some example code if", "referred to as *elements*. They can be anything: numbers, strings,", "The lists have the same elements, so they are equal:", "You can also see the values of variables on the", "element to the end of the list. `nums.append(4)` changes the", "particular, `range(len(nums))` is like `[0, 1, 2]`. - **`subscripting`**: Get", "it would print: [6, 2, 8, 2, 10, 18, 4,", "alternative way to loop over a list: __program_indented__ \"\"\" def", "this happens? The index variable `i` runs through the usual", "This is just as correct but skips unnecessary iterations and", "than 10. Or at least, it tries to. I recommend", "see the values of variables on the right. \"\"\" class", "string2[i] print(char1 + ' ' + char2) tests = {", "the second case, the two variables both have arrows pointing", "As you saw above, lists are *iterable*, meaning you can", "The good news is that there are many ways to", "\"\"\" `None` is a special 'null' value which can't do", "with separator - python add together list of strings with", "to errors. Run this program: __program_indented__ \"\"\" def program(self): list1", "of types. To create a list directly, like above: 1.", "words 'python' and 'list' in your search query. Instead of", "that in most cases, methods which modify a list in", "check for a number bigger than 5. It's useful to", "is a useless statement on its own: word.upper() The string", "b e t h \"\"\" hints = [ \"The solution", "string in between - `sum` - python add list of", "= generate_list(int) if contained: thing_to_find = random.choice(things) else: thing_to_find =", "something...even if it's nothing. For example, `print`'s job is to", "= 0 for number in numbers: total += number print(total)", "**`count`**: Returns the number of times the argument appears in", "the number of times the argument appears in the list.", "When you want to add a single element to the", "Set a value at an index. `nums[0] = 9` changes", "will sometimes be too big \" \"to be a valid", "should print: Thisisalist \"\"\" hints = \"\"\" This is very", "not just the first one. \"\"\" @returns_stdout def solution(self, things,", "for i in range(length): if i < len(string1): char1 =", "statements, one for each string.\", \"You will need to set", "'in the middle' or 'at an index' or 'at a", "to see the difference. \"\"\" class GettingElementsAtPosition(Page): title = \"Getting", "strings, booleans, even lists! They can also be a mixture", "statement on its own: word.upper() The string referred to by", "g t \"\"\"), } @classmethod def generate_inputs(cls): length = random.randrange(5,", "distinct, individual lists. As a result, when you append 4", "is how both variables can end up pointing to the", "\"max([21, 55, 4, 91, 62, 49])\" def check(self): return search_ast(", "called with e.g. `word.upper()`: __program_indented__ \"\"\" def program(self): word =", "similar. It's fine, but it's a bit inefficient. That's because", "check(self): return search_ast( self.stmt, ast.Call(func=ast.Attribute(attr='insert'), args=[ast.Constant(value=2), ast.Constant(value=9)]), ) class dir_list(VerbatimStep):", "more familiar and readable to most people. Now use `.append`", "= \"\"\" Magnificent! Take a break, you've earned it! \"\"\"", "you want to find it manually. - You're still confused", "characters with spaces. For example, for: string1 = \"Goodbye\" string2", "= ['This', 'is', 'a', 'list'] for index in range(len(words)): print(index)", "argument `things` is *passed* to `len`, and `len` *accepts* or", "list `[0, 1, 2, ..., n - 2, n -", "a space between each character: H W e o l", "1, `nums[1]` is 2, `nums[2]` is 3. - **`+`**: Concatenates", "number in numbers: double += [number * 2] print(double) tests", "is very similar to the program that adds numbers. In", "`len()` with strings in the shell? Forget loops for a", "the first version again. If you come across this kind", "word in words: total += word print(total) tests = [", "9, 8].index(8)` is 1. Raises an error if the value", "say that `len` ***returned*** 3. All calls have to return", "print(word.upper) print(word.upper()) class no_append_for_str(VerbatimStep): \"\"\" Another example is that `append`", "the variables, e.g. `list1 = [7, 8, 9]`, the other", "that 0. You can't add 0 to a string because", "cat'` is `True` - `'feed the dog and the cat'.count('the')`", "program = \"max([21, 55, 4, 91, 62, 49])\" def check(self):", "- **`pop`**: Removes and returns an element at a given", "this: for i in range(len(string1)): char1 = string1[i] char2 =", "an exercise like that.\", \"Once you've sorted out `for i", "most cases, methods which modify a list in place (`append`,", "can't unfind it. That means that once you set the", "new list, and then build it up element by element", "\"\"\" @returns_stdout def solution(self, things, thing_to_find): found = False for", "`numbers` at index `i`) As it runs, it clearly skips", "loop over the entire list even if it finds the", "or `string2` is longer. Your next challenge is to fix", "hints = \"\"\" This is very similar to the exercises", "EqualsVsIs(Page): title = \"`==` vs `is`\" class two_separate_lists(VerbatimStep): \"\"\" It's", "variable to `True`. Once you've found the element, you can't", "writing the program to use `remove` instead of `pop` so", "list of the argument's attributes, which are mostly methods. Many", "a bit like you're giving the argument to the function", "both strings. You will need to check if it's too", "Tutor\" button. Here's some example code if you want: all_numbers", "a useless statement on its own: word.upper() The string referred", "seems weird, but that's how most programming languages do it,", "and `len` *accepts* or *receives* the argument. `len(things)` will evaluate", "'is', 'a', 'list'] print(words[0]) print(words[1]) print(words[2]) print(words[3]) class index_error(Step): \"\"\"", "structure and \" \"essential elements of the previous solution, \"", "' ' + char2) tests = { (\"Goodbye\", \"World\"): dedent(\"\"\"\\", "So in general, the valid indices are: [0, 1, 2,", "the list and you'll see some familiar methods. Here are", "@returns_stdout def solution(self, numbers: List[int]): double = [] for number", "But then in the next iteration `i` is 1, and", "have different lengths. In fact, it goes wrong in different", "@classmethod def generate_inputs(cls): things = generate_list(str) to_find = generate_string() things", "`<expression>` evaluates to'. It doesn't make a copy of that", "longer and will require \" \"a few additional ideas and", "`print(things)` is a function ***call*** - when you write that,", "and modify a copy: numbers = [10, 7, 8, 3,", "print `1`. You can assume that `to_find` appears at least", "list has element - `index` - python get position of", "word = word.upper() Or you can use `word.upper()` immediately in", "\"Hello\" string2 = \"World\" print them vertically side by side,", "these values, called `range`: __program_indented__ \"\"\" def program(self): for i", "still contain something like: for i in range(...): ... print(char1", "difference it makes. \"\"\" program_in_text = False def program(self): list1", "do that. \"\"\" hints = \"\"\" Use the words 'python'", "usual values 0, 1, 2, ... as it's supposed to,", "random.randrange(5, 11) length2 = random.randrange(12, 20) if random.choice([True, False]): length1,", "`2 in nums` is `True`, but `4 in nums` is", "= \"\"\" It's time to learn about another tool to", "import returns_stdout class IntroducingLists(Page): class first_list(VerbatimStep): \"\"\" It's time to", "'null' value which can't do anything interesting. It's a common", "is the `pop` method. Modifying a value directly is called", "in range(...): ... print(char1 + ' ' + char2) \"\"\"),", "import random from textwrap import dedent from typing import List", "googling. Try `__program__` in the shell. \"\"\" program = \"dir([])\"", "want a separator, e.g. `''.join(['apples', 'oranges', 'bananas'])` returns `'applesorangesbananas'`. -", "- python how many characters in string - `join` -", "any methods like `append` or even subscript assignment. You simply", "new list from scratch. In this case, we've already done", "you write that, you are ***calling*** the function `len` or", "want to print the second character of each string, and", "self.stmt, ast.Call(func=ast.Attribute(attr='insert'), args=[ast.Constant(value=2), ast.Constant(value=9)]), ) class dir_list(VerbatimStep): \"\"\" Perfect! It", "big_numbers = [] for number in all_numbers: if number <=", "original and modify a copy: numbers = [10, 7, 8,", "(([1, 2, 3, 4], 1), True), (([1, 2, 3, 4],", "prints a list where each number has been doubled. For", "assigned the wrong thing to a variable: __program_indented__ \"\"\" #", "a value at an index. `nums[0]` is 1, `nums[1]` is", "making a list: __program_indented__ \"\"\" def program(self): x = 1", "of numbers. `sum(nums)` is 6. - **`in`**: A comparison operator", "list_contains_exercise(ExerciseStep): \"\"\" Exercise: write a program which takes a list", "if number <= 5: small_numbers.append(number) else: big_numbers.append(number) print(small_numbers) print(big_numbers) The", "`False`. - **`index`**: Returns the first index of a value", "else after that. Don't use an `else`. There is no", "need `range(<length of the longest string>)`\", \"In other words you", "'list'] thing_to_find = 'is' it should print `True`, but for", "python number of elements in list - python how many", "\"\"\" class FunctionsAndMethodsForLists(Page): # TODO this is quite the information", "as 3, in which case we say that `len` ***returned***", "If you see an error message about `None` or `NoneType`,", "This is a method of strings (the separator) which takes", "original list. Basically, an assignment like: list2 = <expression> means", "Check for yourself: numbers = [1, 2] + [3, 4]", "matching characters. \"\"\" @returns_stdout def solution(self, string1, string2): for i", "remember `<expression>`, only the value. It doesn't know about other", "an iterable of strings as an argument. `'--'.join(['apples', 'oranges', 'bananas'])`", "\" \"`len(string)` is too big.\", \"You will need two `if`", "= \"Hello\" string2 = \"World\" print them vertically side by", "list. Use an `if` statement. Use a comparison operator to", "For example, given words = ['This', 'is', 'a', 'list'] separator", "`numbers.pop(i)` removes the element from `numbers` at index `i`) As", "`'feed the dog and the cat'.count('the')` is 2 - `'feed", "10, which gets removed. This shifts the rest of the", "subscripting work with strings, a bit as if strings are", "is that there are many ways to solve this. You", "on screen, not to return a useful value. So it", "`pop` method. Modifying a value directly is called *mutation* -", "to go back to basics and strengthen your foundations. There", "len(things) class methods_of_str(VerbatimStep): \"\"\" A ***method*** is a function which", "iteration `i` is 1, and `numbers[i]` is 8. 7 got", "the beginning. You can stop any loop using a `break`", "handy built in function to give you these values, called", "\"You will need two `if` statements, one for each string.\",", "char2) tests = { (\"Hello\", \"World\"): dedent(\"\"\"\\ H W e", "the last element. - **`remove`**: Removes the first occurrence of", "print(list1 == list2) print(list1 is list2) list1.append(4) print(list1) print(list2) class", "argument. It's a bit like you're giving the argument to", "ways to solve this. You can instead just loop over", "of `.` - the error actually comes just from `word.append`,", "such as 3, in which case we say that `len`", "else: char1 = ' ' if i < len(string2): char2", "default. If you see an error message about `None` or", "= \"\"\" Use the words 'python' and 'list' in your", "def program(self): words = ['This', 'is', 'a', 'list'] for index", "problem is that 0. You can't add 0 to a", "check if it's too big before indexing.\", \"Remember, the biggest", "program(self): numbers = [3, 1, 4, 1, 5, 9] total", "List[str]): total = '' for word in words: total +=", "behave like the first version again. If you come across", "skip appending to the new list. Use an `if` statement.", "introducing_subscripting(VerbatimStep): \"\"\" Looping is great, but often you just want", "you can multiply numbers using `*`. This program is structurally", "a list of strings? The problem is that 0. You", "an eternal link between the variables. If you assign a", "the first character of each of the two strings? In", "now just different ways of printing the same list. I", "you can use `in` to check if a list contains", "can get the element at the position `i` with `words[i]`.", "However, this prints all the indices, not just the first", "= 'the' your program should print `1`. You can assume", "that you print at the end. If you find the", "use `word.upper()` immediately in a larger expression, e.g. if word.lower()", "print_returns_none(VerbatimStep): \"\"\" In the call `len(things)`, `things` is an ***argument***.", "[1, 2, 3] list2 = list1 print(list1) print(list2) print(list1 ==", "6), 6), ] @classmethod def generate_inputs(cls): things = generate_list(str) to_find", "only one list*, and the two variables `list1` and `list2`", "lists! They can also be a mixture of types. To", "length2 = random.randrange(12, 20) if random.choice([True, False]): length1, length2 =", "print(char1 + ' ' + char2) tests = { (\"Goodbye\",", "list of strings with string in between - `sum` -", "since you learned about lists and you need a reminder.", "a n s g t \"\"\"), } @classmethod def generate_inputs(cls):", "= generate_list(str) to_find = generate_string() things += [to_find] * random.randint(1,", "valid index of the list is `len(words) - 1`, so", "things = ['This', 'is', 'a', 'list'] thing_to_find = 'is' it", "only the numbers bigger than 5. For example, given: numbers", "final_text = \"\"\" Nice! A typical solution looks something like", "to `False` inside the loop. \"\"\" @returns_stdout def solution(self, things,", "type using `.`. For example, `upper` and `lower` are methods", "called the *index*. You've probably noticed that the first index", "way, indexing and `len()` also work on strings. Try them", "easy way to check for a number bigger than 5.", "character. The solution is very similar to the program that", "ways to find information without any googling. Try `__program__` in", "i in range(len(numbers)): number = numbers[i] if number <= 10:", "it'll loop over the entire list even if it finds", "1, 2, ..., n - 2, n - 1]`. This", "print(total) tests = [ (['This', 'is', 'a', 'list'], 'Thisisalist'), (['The',", "being modified and the list being itererated over are separate", "above: 1. Write some square brackets: `[]` 2. If you", "in a list. `[7, 8, 9, 8].index(8)` is 1. Raises", "to look things up. For example, here are some typical", "Good find! Let's do one more. If you have a", "operator to test if a number is big enough to", "be seen in both `print(list1)` and `print(list2)` because both lines", "and returns an element at a given index. `nums.pop(3)` removes", "get the element at the position `i` with `words[i]`. The", "class not_callable(VerbatimStep): \"\"\" Most things are not callable, so trying", "You will need `+`. You will need to index both", "to add a single element to the end of a", "It's time to learn some technical details that are often", "e.g. `list1 = [7, 8, 9]`, the other variable will", "specific method has failed so you want to find it", "[ ((['on', 'the', 'way', 'to', 'the', 'store'], 'the'), 1), (([0,", "you don't want a separator, e.g. `''.join(['apples', 'oranges', 'bananas'])` returns", "' + char2) \"\"\"), \"What should go inside `range()`? Neither", "= [] big_numbers = [] for number in all_numbers: if", "Given a list `things` and a value `to_find`, print the", "string2[i] print(char1 + ' ' + char2) This doesn't work", "random.choice([True, False]): length1, length2 = length2, length1 return dict( string1=generate_string(length1),", "of times the argument appears in the list. `[1, 2,", "things are not callable, so trying to call them will", "many more. A more important skill is being able to", "'list' in your search query. In one word, what's special", "another example of making a list: __program_indented__ \"\"\" def program(self):", "use an empty string if you don't want a separator,", "new \"Python Tutor\" button. Here's some example code if you", "def program(self): print(callable(len)) class not_callable(VerbatimStep): \"\"\" Most things are not", "need two `if` statements, one for each string.\", \"You will", "numbers left one position, so now 7 is in position", "- You're still confused about lists after this course. -", "@returns_stdout def solution(self, things, to_find): answer = None for i", "inside to be the elements. 3. Put commas (`,`) between", "and at the end it fails when it tries to", "printed = print(length) print(printed) class len_of_none(VerbatimStep): \"\"\" `None` is a", "For example, for: string1 = \"Goodbye\" string2 = \"World\" output:", "range_len(VerbatimStep): \"\"\" `range(n)` is similar to the list `[0, 1,", "query. Instead of putting the value at the beginning or", "\"\"\" A ***method*** is a function which belongs to a", "skills. For example, you can use `in` to check if", "and strengthen your foundations. There are also ways to find", "e.g. `char1 = ' '` when `string1[i]` is not valid.\",", "total of numbers - `in` - python check if list", "lists. As a result, when you append 4 to `list1`,", "should skip appending to the new list. Use an `if`", "correct but skips unnecessary iterations and checks once it finds", "if strings are lists of characters. Strings also support some", "dict( string1=generate_string(length), string2=generate_string(length), ) class zip_longest_exercise(ExerciseStep): \"\"\" Incredible! Your solution", "and `lower` are methods of strings, which are called with", "def check(self): return search_ast( self.stmt, ast.Call(func=ast.Name(id='max')), ) class list_insert(Step): \"\"\"", "shell to do that. \"\"\" hints = \"\"\" Use the", "like `append` or even subscript assignment. You simply can't change", "in place (`append`, `insert`, `remove`) merely return `None`, while the", "print(list1 == list2) print(list1 is list2) list1.append(4) print(list1) print(list2) final_text", "import dedent from typing import List from main.exercises import generate_list,", "we say that `len` ***returned*** 3. All calls have to", "word, what's special about `91` in the list `[21, 55,", "want the 9 to be at the end, you want", "lengths. In fact, it goes wrong in different ways depending", "you will also see the word ***parameter***, which means basically", "You learned how to stop a loop in the middle", "- It's been a while since you learned about lists", "first index is 0, not 1. In programming, counting starts", "Elements at a Position\" class introducing_subscripting(VerbatimStep): \"\"\" Looping is great,", "**`sorted`**: Takes an iterable and returns a list of the", "not pointless, as you've now learned valuable fundamental skills. For", "Returns the number of times the argument appears in the", "= random.randrange(12, 20) if random.choice([True, False]): length1, length2 = length2,", "= \"\"\" `dir()` returns a list of the argument's attributes,", "create two variables which refer to lists. The lists have", "`'apples--oranges--bananas'`. You can also use an empty string if you", "UnderstandingProgramsWithPythonTutor(Page): final_text = \"\"\" It's time to learn about another", "left or right. You can also see the values of", "print: [6, 2, 8, 2, 10, 18, 4, 12, 10]", "struggling to solve a problem with lists and you need", "d l b d y e and for: string1 =", "value `to_find`, print the first index of `to_find` in the", "with equal contents. Similarly, you could loop over the original", "length1 > length2: length = length1 else: length = length2", "so that it can add up a list of strings", "number <= 5: small_numbers.append(number) else: big_numbers.append(number) print(small_numbers) print(big_numbers) The button", "is `True`, but `4 in nums` is `False`. - **`index`**:", "Or you can use `word.upper()` immediately in a larger expression,", "solution(self, numbers: List[int]): double = [] for number in numbers:", "ideas and pieces.\", dedent(\"\"\" In particular, it should still contain", "you can get the number of elements in a list", "type, and can be called on all values of that", "\"\"\" This program is quite straightforward and mostly consists of", "This shifts the rest of the numbers left one position,", "also means that the last index in this list of", "can also use an empty string if you don't want", "and prints a list where each number has been doubled.", "you need `range(<length of the longest string>)`\", \"In other words", "particular position' 'python add value at index' \"\"\" program =", "Since you're looking for the first index, you need to", "3, 4, 5, 6, 6], 6), 7), ] @returns_stdout def", "which prints a list containing only the numbers bigger than", "You're still confused about lists after this course. - It's", "to the variable: word = word.upper() Or you can use", "it would print: [9, 6] \"\"\" hints = \"\"\" This", "'a', 'list'], 'is'), True), ((['This', 'is', 'a', 'list'], 'other'), False),", "the same list. But as we've learned before, `list2` doesn't", "class index_error(Step): \"\"\" In general, you can get the element", "about lists after this course. - It's been a while", "PyCallingNonCallable def program(self): f = 'a string' print(callable(f)) f() class", "list `[21, 55, 4, 91, 62, 49]`, it will return", "element to a list by adding a list containing one", "in a list: __program_indented__ \"\"\" def program(self): numbers = [3,", "7), ] @returns_stdout def solution(self, things, to_find): for i in", "A list is a *sequence* (an ordered collection/container) of any", "9, 2, 6, 5], [9, 6]), ([0, 2, 4, 6,", "the list `[0, 1, 2, ..., n - 2, n", "but users don't need to know these functions off by", "this prints the *last* index, not the first one. \"\"\"", "6, 6], 6), 7), ] @returns_stdout def solution(self, things, to_find):", "- python check if list contains value - python test", "that `to_find` appears at least once. \"\"\" hints = \"\"\"", "if thing == thing_to_find: found = True break This is", "class two_separate_lists(VerbatimStep): \"\"\" It's time to learn some technical details", "Looping is great, but often you just want to retrieve", "4, 5, 6, 6], 6), 6), ] @classmethod def generate_inputs(cls):", "or drag the slider left or right. You can also", "the argument. `len(things)` will evaluate to a number such as", "to return a useful value. So it returns something useless", "`len` and subscripting work with strings, a bit as if", "10]), ([0, 1, 2, 3], [0, 2, 4, 6]), ]", "2, 3]) length = len(things) class methods_of_str(VerbatimStep): \"\"\" A ***method***", "one. \"\"\" @returns_stdout def solution(self, things, to_find): for i in", "valid.\", ] # TODO catch user writing string1 < string2", "For example: - `'the' in 'feed the dog and the", "time to learn about another tool to explore programs. Put", "\"\"\" You're almost there! However, this prints the *last* index,", "a for loop. Start with an empty list. You can", "of the given element. `nums.remove(10)` will leave `nums` as `[28,", "more useful functions/methods. Suppose `nums = [28, 99, 10, 81,", "value. Functions that don't want to return anything return `None`", "True break This is just as correct but skips unnecessary", "for yourself: __program_indented__ \"\"\" def program(self): print(len) print(print) class introducing_callable(VerbatimStep):", "list with one element `x` by just writing `[x]`. You", "be too big \" \"to be a valid index for", "dedent(\"\"\"\\ H E e l l i l z o", "len(string1): char1 = string1[i] else: char1 = ' ' if", "the value. It doesn't know about other variables. You can", "= \"dir([])\" final_text = \"\"\" `dir()` returns a list of", "is that sometimes you should skip appending to the new", "check if a list contains 5, but there's no similarly", "In fact, it goes wrong in different ways depending on", "list or `.append` on a string: __program_indented__ \"\"\" # noinspection", "numbers = [10, 7, 8, 3, 12, 15] big_numbers =", "`True`, but for thing_to_find = 'other' it should print `False`.", "that `len` and subscripting work with strings, a bit as", "try getting an index greater than that? \"\"\" program =", "change the value that `word` refers to, you have to", "print(char1 + ' ' + char2) This doesn't work so", "else: char2 = ' ' print(char1 + ' ' +", "in words: print(word) class can_contain_anything(VerbatimStep): \"\"\" A list is a", "a real useful value. Functions that don't want to return", "and the result can be seen in both `print(list1)` and", "a new list, and then build it up element by", "changes the list to `[1, 2, 3, 4]`. - **`len`**:", "list of numbers. `sum(nums)` is 6. - **`in`**: A comparison", "ever set the variable to `False` inside the loop. \"\"\"", "skips unnecessary iterations and checks once it finds the element.", "get some exercise! Given a list `things` and a value", "returns `[10, 28, 59, 64, 81, 99]`. - **`pop`**: Removes", "to. I recommend running it with Python Tutor. numbers =", "= [ ((['on', 'the', 'way', 'to', 'the', 'store'], 'the'), \"1\\n4\"),", "is 8. 7 got skipped. We could try writing the", "argument, i.e. just `nums.pop()`, it will remove and return the", "is very similar to the exercises you've done building up", "just from `word.append`, without even a call. \"\"\" class FunctionsAndMethodsForLists(Page):", "Raises an error if the value isn't there. You may", "= [ \"The solution has the same overall structure and", "the result can be seen in both `print(list1)` and `print(list2)`", "statement. Use a comparison operator to test if a number", "of elements in a list (commonly called the *length*) using", "a value and checks if the list contains the value.", "so we don't have to use indices. It even looks", "list2` is `True`. But then there's a new comparison operator:", "list2` is `True`, because *there is only one list*, and", "title = \"Getting Elements at a Position\" class introducing_subscripting(VerbatimStep): \"\"\"", "an empty list, write some expressions inside to be the", "index of `to_find` in the list, i.e. the lowest number", "4, 1, 5, 9, 2, 6, 5], [6, 2, 8,", "returns `'applesorangesbananas'`. - **`sum`**: Add a list of numbers. `sum(nums)`", "you try running that program with a list of strings?", "and mostly consists of things you're familiar with. We create", "an element to a list by adding a list containing", "- list Lists and strings have a lot in common.", "So it returns something useless instead: __program_indented__ \"\"\" # noinspection", "list of the elements in order. `sorted(nums)` returns `[10, 28,", "editor and then click the new \"Python Tutor\" button. Here's", "and \" \"essential elements of the previous solution, \" \"but", "words you need to find the biggest of the two", "`91` in the list `[21, 55, 4, 91, 62, 49]`?", "are immutable - they don't have any methods like `append`", "up all the numbers in a list: __program_indented__ \"\"\" def", "the words 'python' and 'list' in your search query. In", "solution, \" \"but it's significantly longer and will require \"", "index both strings. You will need to pass the same", "with string in between - `sum` - python add list", "and values](https://nedbatchelder.com/text/names.html). \"\"\" class ModifyingWhileIterating(Page): final_text = \"\"\" Consider this", "into a new list. You can also create an empty", "= [] new_numbers += numbers new_numbers += [5] print(new_numbers) With", "`insert`, `remove`) merely return `None`, while the remaining functions/methods return", "3, 4]`. - **`len`**: Returns the number of elements. `len(nums)`", "dict( things=things, to_find=to_find, ) class zip_exercise(ExerciseStep): \"\"\" Nice! By the", "the values of variables on the right. \"\"\" class EqualsVsIs(Page):", "[6, 2, 8, 2, 10, 18, 4, 12, 10]), ([0,", "total = 0 for number in numbers: total += number", "list and returns it. Without an argument, i.e. just `nums.pop()`,", "- specifically we say that the argument `things` is *passed*", "55, 4, 91, 62, 49]`? 'biggest' or 'largest' 'python biggest", "is `True`. But then there's a new comparison operator: `is`.", "them all, and there's many more. A more important skill", "list of strings? The problem is that 0. You can't", "`range()`? Neither `len(string1)` nor `len(string2)` is good enough.\", \"You want", "can end up pointing to the same list. But as", "get position of element - python get index of value", "print(list1 is list2) list1.append(4) print(list1) print(list2) final_text = \"\"\" Now", "number of elements in list - python how many characters", "few more useful functions/methods. Suppose `nums = [28, 99, 10,", "+ 1, ]) return dict( things=things, thing_to_find=thing_to_find, ) final_text =", "double = [] for number in numbers: double += [number", "anything else after that. Don't use an `else`. There is", "that's how most programming languages do it, and it's generally", "from the list at a known position. Here's how: __program_indented__", "numbers - python total of numbers - `in` - python", "that functions are ***callable***: __program_indented__ \"\"\" def program(self): print(callable(len)) class", "a special 'null' value which can't do anything interesting. It's", "list1.append(4) print(list1) print(list2) final_text = \"\"\" Now `list1 is list2`", "with spaces. For example, for: string1 = \"Goodbye\" string2 =", "to return something...even if it's nothing. For example, `print`'s job", "3] list2 = list1 print(list1) print(list2) print(list1 == list2) print(list1", "immediately in a larger expression, e.g. if word.lower() == 'yes':", "If you have a list: nums = [1, 2, 3,", "a new list. You can also create an empty list", "solution(self, things, to_find): answer = None for i in range(len(things)):", "Your next challenge is to fix this problem by filling", "of list - `len` - python size of list -", "the previous exercise. The difference is that sometimes you should", "screen, not to return a useful value. So it returns", "CallingFunctionsTerminology(Page): title = \"Terminology: Calling functions and methods\" class print_functions(VerbatimStep):", "\"\"\" program_in_text = False def program(self): list1 = [1, 2,", "\"\"\" Consider this program. It loops through a numbers and", "'a string' print(callable(f)) f() class print_returns_none(VerbatimStep): \"\"\" In the call", "`None`, while the remaining functions/methods return a new useful value", "for now - scroll to the end of the list", "- **`subscripting`**: Get a value at an index. `nums[0]` is", "there! However, this prints the *last* index, not the first", "an empty list. You can make a list with one", "VerbatimStep, search_ast from main.utils import returns_stdout class IntroducingLists(Page): class first_list(VerbatimStep):", "least once. \"\"\" hints = \"\"\" You will need to", "through the usual values 0, 1, 2, ... as it's", "# noinspection PyCallingNonCallable def program(self): f = 'a string' print(callable(f))", "so trying that will give you an error. By the", "first index, you need to stop the loop once you", "find the biggest of the two values \" \"`len(string1)` and", "by default. If you see an error message about `None`", "with `words[i]`. The operation is called *subscripting* or *indexing*, and", "class sum_list(Step): \"\"\" Let's review how to work with lists.", "`1`. You can assume that `to_find` appears at least once.", "to_find == things[i]: print(i) tests = [ ((['on', 'the', 'way',", "an error: __program_indented__ \"\"\" # noinspection PyCallingNonCallable def program(self): f", "for i in range(...): ... print(char1 + ' ' +", "to retrieve a single element from the list at a", "the number of elements in a list (commonly called the", "quite the information dump and I'd like it to be", "- **`subscript assignment`**: Set a value at an index. `nums[0]", "\"`len(string)` is too big.\", \"You will need two `if` statements,", "contains 5, but there's no similarly easy way to check", "the same thing, for the same reason. Iterating over a", "equal contents. Similarly, you could loop over the original and", "create an eternal link between the variables. If you assign", "the element, you can't unfind it. That means that once", "' ' + char2) This doesn't work so well if", "ways depending on whether `string1` or `string2` is longer. Your", "each character: H W e o l r l l", "removes `nums[3]` (`81`) from the list and returns it. Without", "operator. Specifically `==`. You need a boolean variable that you", "longer the positions we want. For example in the first", "step by step with the \"Prev\" or \"Next\" buttons, or", "def generate_inputs(cls): things = generate_list(str) to_find = generate_string() things +=", "string1=generate_string(length1), string2=generate_string(length2), ) final_text = \"\"\" Magnificent! Take a break,", "set the variable to `False` inside the loop. \"\"\" @returns_stdout", "\"\"\" # noinspection PyCallingNonCallable def program(self): f = 'a string'", "= [10, 7, 8, 3, 12, 15] for i in", "because numbers and strings are incompatible. Is there a similar", "you will need a loop over `range(len(things))`. To check if", "from scratch. In this case, we've already done a similar", "and then click the new \"Python Tutor\" button. Here's some", "the numbers in a list: __program_indented__ \"\"\" def program(self): numbers", "in numbers: if number <= 10: big_numbers.remove(number) print(big_numbers) Or you", "**`in`**: A comparison operator that checks if a value is", "will remove and return the last element. - **`remove`**: Removes", "remaining functions/methods return a new useful value without changing the", "`word.upper()` returned a new string which was immediately discarded. If", "use `in` to check if a list contains 5, but", "ast import random from textwrap import dedent from typing import", "class last_index(MessageStep, ExerciseStep): \"\"\" You're almost there! However, this prints", "`[10, 28, 59, 64, 81, 99]`. - **`pop`**: Removes and", "in numbers: double += [number * 2] print(double) tests =", "4, 5, 6, 6], 6), \"6\\n7\"), ] class last_index(MessageStep, ExerciseStep):", "test if list has element - `index` - python get", "changes those are no longer the positions we want. For", "generate_list(int) if contained: thing_to_find = random.choice(things) else: thing_to_find = random.choice([", "`nums` as `[28, 99, 81, 59, 64]`. Raises an error", "is just as correct but skips unnecessary iterations and checks", "over a copy, as in: for number in numbers.copy(): Now", "program which takes a list of numbers and prints a", "print(double) tests = [ ([3, 1, 4, 1, 5, 9,", "is 0 and `number` is 10, which gets removed. This", "some more. `print` and `len` are ***functions***. See for yourself:", "just loop over a copy, as in: for number in", "e t h \"\"\" hints = [ \"The solution has", "- Googling a specific method has failed so you want", "heart. class sum_list(Step): \"\"\" Let's review how to work with", "class all_indices(MessageStep, ExerciseStep): \"\"\" You're almost there! However, this prints", "You will need an `if` statement. You will need a", "which can't do anything interesting. It's a common placeholder that", "< string2 @returns_stdout def solution(self, string1, string2): length1 = len(string1)", "the answer, you will need to use: - `if` -", "`True`. Once you've found the element, you can't unfind it.", "= <expression> means 'make the variable `list2` refer to whatever", "- python get index of value Let's practice this skill", "how it visualises the difference. In the second case, the", "and strings are incompatible. Is there a similar concept among", "program = \"nums.insert(2, 9)\" def check(self): return search_ast( self.stmt, ast.Call(func=ast.Attribute(attr='insert'),", "value Let's practice this skill now. Find a function/method that", "programming, counting starts at 0. It seems weird, but that's", "solve this manually with a loop. \"\"\" hints = \"\"\"", "add list of numbers - python total of numbers -", "args=[ast.Constant(value=2), ast.Constant(value=9)]), ) class dir_list(VerbatimStep): \"\"\" Perfect! It can also", "`nums[1]` is 2, `nums[2]` is 3. - **`+`**: Concatenates lists.", "values are often referred to as *elements*. They can be", "o d \"\"\" hints = \"\"\" Did you experiment with", "the possible indices of `things` and check which one is", "6), ] @classmethod def generate_inputs(cls): things = generate_list(str) to_find =", "Specifically `==`. You need a boolean variable that you print", "6, 6], 6), 6), ] @classmethod def generate_inputs(cls): things =", "(an ordered collection/container) of any number of values. The values", "1, 5, 9, 2, 6, 5] it would print: [6,", "of each of the two strings? In the second line", "characters. \"\"\" @returns_stdout def solution(self, string1, string2): for i in", "early\" class list_contains_exercise(ExerciseStep): \"\"\" Exercise: write a program which takes", "l b d y e \"\"\"), (\"Hello\", \"Elizabeth\"): dedent(\"\"\"\\ H", "You simply can't change a string - you can only", "of strings with separator - python add together list of", "[9, 6] \"\"\" hints = \"\"\" This is very similar", "***parameter***, which means basically the same thing as argument. It's", "character: H W e o l r l l o", "of the longest string>)`\", \"In other words you need to", "values 0, 1, 2, ... as it's supposed to, but", "`len` or `print`. The fact that this is possible means", "check(self): return search_ast( self.stmt, ast.Call(func=ast.Name(id='max')), ) class list_insert(Step): \"\"\" Good", "square brackets: `[]` 2. If you don't want an empty", "technical details that are often misunderstood and lead to errors.", "to change the value that `word` refers to, you have", "to write: some_list.append(element) There isn't really a big difference between", "= [ ((['on', 'the', 'way', 'to', 'the', 'store'], 'the'), 4),", "28, 59, 64, 81, 99]`. - **`pop`**: Removes and returns", "break This is just as correct but skips unnecessary iterations", "answer = None for i in range(len(things)): if to_find ==", "a number such as 3, in which case we say", "a subscript - `==` Since you're looking for the first", "E e l l i l z o a b", "`'feed the dog and the cat'.index('the')` is 5 Note that", "require \" \"a few additional ideas and pieces.\", dedent(\"\"\" In", "the longer string.\", \"That means you need `range(<length of the", "are ***calling*** the function `len` or `print`. The fact that", "i in range(...)`, `i` will sometimes be too big \"", "print the second character of each string, and so on.", "it up element by element in a for loop. Start", "3], [0, 2, 4, 6]), ] class filter_numbers(ExerciseStep): \"\"\" Great!", "*last* index, not the first one. \"\"\" @returns_stdout def solution(self,", "is `3`. - **`range`**: `range(n)` is an object similar to", "returned a new string which was immediately discarded. If you", "example, given words = ['This', 'is', 'a', 'list'] separator =", "number in numbers: total += number print(total) class strings_sum(ExerciseStep): \"\"\"", "not easy to learn them all, and there's many more.", "progress. \"\"\" class UsingBreak(Page): title = \"Using `break` to end", "statement, like so: for thing in things: if thing ==", "to the function - specifically we say that the argument", "char2 = ' ' print(char1 + ' ' + char2)", "ways of printing the same list. I recommend running both", "`range(len(things))`. To check if an index is the answer, you", "string1 < string2 @returns_stdout def solution(self, string1, string2): length1 =", "the shell to do that. \"\"\" hints = \"\"\" Use", "in your search query. In one word, what's special about", "For example, given the list `[21, 55, 4, 91, 62,", "of the argument's attributes, which are mostly methods. Many will", "\"nums.insert(2, 9)\" def check(self): return search_ast( self.stmt, ast.Call(func=ast.Attribute(attr='insert'), args=[ast.Constant(value=2), ast.Constant(value=9)]),", "solution is very similar to the program that adds numbers.", "\"\"\"), (\"Having\", \"ablast\"): dedent(\"\"\"\\ H a a b v l", "found = True print(found) Your solution is probably similar. It's", "Removes the first occurrence of the given element. `nums.remove(10)` will", "useful functions/methods. Suppose `nums = [28, 99, 10, 81, 59,", "= ['Hello', x, x + 3] print(things) class numbers_sum(VerbatimStep): \"\"\"", "a list: nums = [1, 2, 3, 4, 5] You", "__program_indented__ \"\"\" def program(self): x = 1 things = ['Hello',", "python add element to list - python add item at", "words: total += word print(total) tests = [ (['This', 'is',", "`in` - python check if list contains value - python", "= random.randrange(5, 11) return dict( string1=generate_string(length), string2=generate_string(length), ) class zip_longest_exercise(ExerciseStep):", "over them with a `for loop`. Here's a program that", "= [1, 2, 3] list2 = list1 print(list1) print(list2) print(list1", "as a single small expression. For example, if you were", "For example in the first iteration `i` is 0 and", "problem and you're still having trouble understanding this stuff, read", "an empty list that has no elements. Check for yourself:", "trying that will give you an error. By the way,", "= True print(found) tests = [ ((['This', 'is', 'a', 'list'],", "Put commas (`,`) between elements to separate them. Here's another", "if you don't want a separator, e.g. `''.join(['apples', 'oranges', 'bananas'])`", "will make the program behave like the first version again.", "give you an error. By the way, you can get", "2, ..., len(words) - 2, len(words) - 1] There's a", "to, but as the list changes those are no longer", "want to add a single element to the end of", "of a list, instead of: some_list += [element] it's actually", "numbers_sum(VerbatimStep): \"\"\" As you saw above, lists are *iterable*, meaning", "given: words = ['This', 'is', 'a', 'list'] it should print:", "that it can add up a list of strings instead", "e.g. `word.upper()`: __program_indented__ \"\"\" def program(self): word = 'Hello' print(word.upper)", "The values are often referred to as *elements*. They can", "called `range`: __program_indented__ \"\"\" def program(self): for i in range(10):", "should go inside `range()`? Neither `len(string1)` nor `len(string2)` is good", "8, 2, 10, 18, 4, 12, 10]), ([0, 1, 2,", "a list in place (`append`, `insert`, `remove`) merely return `None`,", "`False`. That means that regardless of the two lists being", "on. You will need a `for` loop. You will need", "the list, i.e. the lowest number `i` such that `things[i]`", "depending on whether `string1` or `string2` is longer. Your next", "you iterate over it***. Keep mutation and looping separate. The", "= True break This is just as correct but skips", "on strings. Try them out in the shell. Here's another", "`nums` would change to: [1, 2, 3, 4, 5, 9]", "e o l r l l o d \"\"\"), (\"Having\",", "def solution(self, numbers: List[int]): big_numbers = [] for number in", "3. Put commas (`,`) between elements to separate them. Here's", "3]`. - **`join`**: Add a list of strings with a", "some_list += [element] it's actually more common to write: some_list.append(element)", "mutated are *mutable*, while those that can't are *immutable*. Strings", "[1, 2, 9, 3, 4, 5] Call the right function/method", "generate_string from main.text import ExerciseStep, MessageStep, Page, Step, VerbatimStep, search_ast", "great progress. \"\"\" class UsingBreak(Page): title = \"Using `break` to", "stop the loop once you find one. You learned how", "almost there! However, this prints the *last* index, not the", "a loop. You will need an `if` statement. You will", "information dump and I'd like it to be a little", "should print `False`. \"\"\" hints = \"\"\" You will need", "E501 import ast import random from textwrap import dedent from", "useful to know these functions, but it's not easy to", "kind of problem and you're still having trouble understanding this", "value at an index. `nums[0] = 9` changes the list", "program(self): words = ['This', 'is', 'a', 'list'] for index in", "- 1`. In particular, `range(len(nums))` is like `[0, 1, 2]`.", "some exercise! Given a list `things` and a value `to_find`,", "for things = ['on', 'the', 'way', 'to', 'the', 'store'] to_find", "'Hello' print(word.upper) print(word.upper()) class no_append_for_str(VerbatimStep): \"\"\" Another example is that", "create a list directly, like above: 1. Write some square", "char1 = string1[i] char2 = string2[i] print(char1 + ' '", "the argument `things` is *passed* to `len`, and `len` *accepts*", "user writing string1 < string2 @returns_stdout def solution(self, string1, string2):", "other variables. You can copy a list with the `copy`", "other words you need to find the biggest of the", "calls have to return something...even if it's nothing. For example,", "1. In programming, counting starts at 0. It seems weird,", "familiar with. We create two variables which refer to lists.", "That means that the last valid index of the list", "which are called with e.g. `word.upper()`: __program_indented__ \"\"\" def program(self):", "in the error message refers to the use of `.`", "The difference is that sometimes you should skip appending to", "recommend running both versions with Python Tutor to see how", "at the end, you want it to go between the", "`join` - python combine list of strings with separator -", "is structurally very similar to the programs you've written to", "but `.append` will be more familiar and readable to most", "*length*) using `len(words)`. That means that the last valid index", "what difference it makes. \"\"\" program_in_text = False def program(self):", "= random.choice([True, False]) things = generate_list(int) if contained: thing_to_find =", "just `nums.pop()`, it will remove and return the last element.", "5: big_numbers.append(number) print(big_numbers) tests = [ ([3, 1, 4, 1,", "- `len` - python size of list - python number", "job is to display something on screen, not to return", "of strings? The problem is that 0. You can't add", "from the list and returns it. Without an argument, i.e.", "see some familiar methods. Here are a few more useful", "`[0, 1, 2]`. - **`subscripting`**: Get a value at an", "access an index that's too high. Can you see why", "ways you might Google the above functions if you forgot", "those are no longer the positions we want. For example", "print(callable(len)) class not_callable(VerbatimStep): \"\"\" Most things are not callable, so", "forgot their names: - `append` - python add element to", "running that program with a list of strings? The problem", "by adding a list containing one element. \"\"\" @returns_stdout def", "12, 15] for i in range(len(numbers)): number = numbers[i] if", "+= word print(total) tests = [ (['This', 'is', 'a', 'list'],", "print(words[1]) print(words[2]) print(words[3]) class index_error(Step): \"\"\" In general, you can", "manually. - You're still confused about lists after this course.", "example, `print`'s job is to display something on screen, not", "'a', 'list'], 'Thisisalist'), (['The', 'quick', 'brown', 'fox', 'jumps'], 'Thequickbrownfoxjumps'), ]", "introducing_callable(VerbatimStep): \"\"\" An expression like `len(things)` or `print(things)` is a", "to be the elements. 3. Put commas (`,`) between elements", "class EqualsVsIs(Page): title = \"`==` vs `is`\" class two_separate_lists(VerbatimStep): \"\"\"", "the end. If you find the element in the list", "value. So it returns something useless instead: __program_indented__ \"\"\" #", "up strings character by character. The solution is very similar", "You've probably noticed that the first index is 0, not", "that? \"\"\" program = \"words[4]\" def check(self): return \"IndexError\" in", "\"6\\n7\"), ] class last_index(MessageStep, ExerciseStep): \"\"\" You're almost there! However,", "We create two variables which refer to lists. The lists", "list object. `list2 = list1` doesn't create an eternal link", "and `print(list2)` because both lines are now just different ways", "elements is 3. What happens if you try getting an", "it. Without an argument, i.e. just `nums.pop()`, it will remove", "the list and returns it. Without an argument, i.e. just", "of strings instead of numbers. For example, given: words =", "of the elements in order. `sorted(nums)` returns `[10, 28, 59,", "methods. Here are a few more useful functions/methods. Suppose `nums", "you can get the element at the position `i` with", "than 5. For example, given: numbers = [3, 1, 4,", "is only one list*, and the two variables `list1` and", "strings. Try them out in the shell. Here's another exercise.", "print(index) print(words[index]) class index_exercise(ExerciseStep): \"\"\" Let's get some exercise! Given", "in words: total += word print(total) tests = [ (['This',", "\"\"\" Let's get some exercise! Given a list `things` and", "the same thing as argument. It's a bit like you're", "Consider this program. It loops through a numbers and removes", "This is very similar to the previous exercise. The difference", "some_list.append(element) There isn't really a big difference between these, but", "or even subscript assignment. You simply can't change a string", "to be at the end, you want it to go", "agreed to be better. This also means that the last", "I'd like it to be a little more interactive, #", "when you append 4 to `list1`, only `list1` changes. Now", "== thing_to_find: found = True break This is just as", "as an argument. `'--'.join(['apples', 'oranges', 'bananas'])` returns `'apples--oranges--bananas'`. You can", "2, 3]` to `list2 = list1` and see what difference", "length2 for i in range(length): if i < len(string1): char1", "\"Elizabeth\" output: H E e l l i l z", "at a given index. `nums.pop(3)` removes `nums[3]` (`81`) from the", "**`subscript assignment`**: Set a value at an index. `nums[0] =", "doesn't create an eternal link between the variables. If you", "\"`==` vs `is`\" class two_separate_lists(VerbatimStep): \"\"\" It's time to learn", "like: list2 = <expression> means 'make the variable `list2` refer", "to that same list. `list1.append(4)` appends to the one list", "for the function `sum`, you could write `sum([21, 55, 4,", "the two variables both have arrows pointing to a single", "1`. \" \"`len(string)` is too big.\", \"You will need two", "these functions, but it's not easy to learn them all,", "is an object similar to the list of numbers from", "you could write `sum([21, 55, 4, 91, 62, 49])`. Don't", "program = \"dir([])\" final_text = \"\"\" `dir()` returns a list", "bit inefficient. That's because it'll loop over the entire list", "time to learn about a powerful new type of value", "loop in the middle recently. You need to use `break`.", "print(total) class strings_sum(ExerciseStep): \"\"\" Now modify the program so that", "means basically the same thing as argument. It's a bit", "3, in which case we say that `len` ***returned*** 3.", "i in range(len(things)): if to_find == things[i]: print(i) break tests", "81, 59, 64]`. Raises an error if the value doesn't", "skill now. Find a function/method that returns the value in", "you are ***calling*** the function `len` or `print`. The fact", "In the second line you want to print the second", "x = 1 things = ['Hello', x, x + 3]", "stop a loop in the middle recently. You need to", "nothing. For example, `print`'s job is to display something on", "any number of values. The values are often referred to", "W o o o r d l b d y", "to the list of numbers from 0 to `n -", "copy, as in: for number in numbers.copy(): Now the list", "to learn some technical details that are often misunderstood and", "= [] for number in numbers: if number > 5:", "two separate, distinct, individual lists. As a result, when you", "can't do anything interesting. It's a common placeholder that represents", "list. `nums.append(4)` changes the list to `[1, 2, 3, 4]`.", "91, 62, 49])\" def check(self): return search_ast( self.stmt, ast.Call(func=ast.Name(id='max')), )", "z o a b e t h \"\"\" hints =", "after that. Don't use an `else`. There is no reason", "mixture of types. To create a list directly, like above:", "value and checks if the list contains the value. For", "This gives us an alternative way to loop over a", "there's many more. A more important skill is being able", "single small expression. For example, if you were looking for", "we've already done a similar thing in an exercise: numbers", "out this does the same thing, for the same reason.", "tests = [ ([3, 1, 4, 1, 5, 9, 2,", "in the first iteration `i` is 0 and `number` is", "i < len(string2): char2 = string2[i] else: char2 = '", "strings of equal length, e.g: string1 = \"Hello\" string2 =", "review how to work with lists. Suppose we have a", "an element to the end of the list. `nums.append(4)` changes", "a while since you learned about lists and you need", "add up a list of strings instead of numbers. For", "strings have a lot in common. For example, you can", "leave `nums` as `[28, 99, 81, 59, 64]`. Raises an", "8, 3, 12, 15] big_numbers = numbers.copy() for number in", "`nums = [28, 99, 10, 81, 59, 64]` - **`sorted`**:", "one position, so now 7 is in position 0. But", "contains value - python test if list has element -", "2, 3, 4, 5, 9] But suppose you don't want", "nicer this way. numbers = [10, 7, 8, 3, 12,", "unfind it. That means that once you set the variable", "once it finds the element. You can use snoop to", "\"essential elements of the previous solution, \" \"but it's significantly", "for yourself: numbers = [1, 2] + [3, 4] print(numbers)", "of each string, and so on. You will need a", "`dir()` returns a list of the argument's attributes, which are", "the first index is 0, not 1. In programming, counting", "to: [1, 2, 3, 4, 5, 9] But suppose you", "python how many characters in string - `join` - python", "the last index in this list of 4 elements is", "tests = { (\"Hello\", \"World\"): dedent(\"\"\"\\ H W e o", "'is', 'a', 'list'] for index in range(len(words)): print(index) print(words[index]) class", "the end, you want it to go between the second", "find one. You learned how to stop a loop in", "to separate them. Here's another example of making a list:", "dog and the cat'.count('the')` is 2 - `'feed the dog", "use indices. It even looks nicer this way. numbers =", "You can't add 0 to a string because numbers and", "to use `break`. \"\"\" class all_indices(MessageStep, ExerciseStep): \"\"\" You're almost", "list in place (`append`, `insert`, `remove`) merely return `None`, while", "functions/methods. Suppose `nums = [28, 99, 10, 81, 59, 64]`", "query. In one word, what's special about `91` in the", "a program which takes a list of numbers and prints", "is 3. - **`+`**: Concatenates lists. `nums + [4, 5]`", "a new tab with a visualisation from [pythontutor.com](http://pythontutor.com). There you", "['Hello', x, x + 3] print(things) class numbers_sum(VerbatimStep): \"\"\" As", "time to expand your vocabulary some more. `print` and `len`", "+ ' ' + char2) tests = { (\"Hello\", \"World\"):", "lowest number `i` such that `things[i]` is `to_find`. For example,", "8, 1, 9, 7] small_numbers = [] big_numbers = []", "a mixture of types. To create a list directly, like", "l l i l z o a b e t", "but skips unnecessary iterations and checks once it finds the", "You can also create an empty list that has no", "list1.append(4) print(list1) print(list2) class same_list(VerbatimStep): \"\"\" This program is quite", "1]`. Try these for yourself. So in general, the valid", "the program that adds numbers. In fact, what happens if", "We're making great progress. \"\"\" class UsingBreak(Page): title = \"Using", "This - is - a - list Lists and strings", "that are often misunderstood and lead to errors. Run this", "class filter_numbers(ExerciseStep): \"\"\" Great! When you want to add a", "will need to use: - `if` - the index in", "a b e t h \"\"\" hints = [ \"The", "example, `upper` and `lower` are methods of strings, which are", "GettingElementsAtPosition(Page): title = \"Getting Elements at a Position\" class introducing_subscripting(VerbatimStep):", "`''.join(['apples', 'oranges', 'bananas'])` returns `'applesorangesbananas'`. - **`sum`**: Add a list", "numbers in a list: __program_indented__ \"\"\" def program(self): numbers =", "to learn about another tool to explore programs. Put some", "`.append` will be more familiar and readable to most people.", "1`. In particular, `range(len(nums))` is like `[0, 1, 2]`. -", "random.choice([True, False]) things = generate_list(int) if contained: thing_to_find = random.choice(things)", "basically the same thing as argument. It's a bit like", "to `[9, 2, 3]`. - **`join`**: Add a list of", "length1 = len(string1) length2 = len(string2) if length1 > length2:", "\"\"\" def program(self): word = 'Hello' print(word.upper) print(word.upper()) class no_append_for_str(VerbatimStep):", "information without any googling. Try `__program__` in the shell. \"\"\"", "print(print) class introducing_callable(VerbatimStep): \"\"\" An expression like `len(things)` or `print(things)`", "the argument appears in the list. `[1, 2, 3, 2,", "program which takes a list and a value and checks", "you want to change the value that `word` refers to,", "thing_to_find: found = True print(found) Your solution is probably similar.", "ExerciseStep, MessageStep, Page, Step, VerbatimStep, search_ast from main.utils import returns_stdout", "when you write that, you are ***calling*** the function `len`", "== things[i]: print(i) tests = [ ((['on', 'the', 'way', 'to',", "ast.Constant(value=9)]), ) class dir_list(VerbatimStep): \"\"\" Perfect! It can also be", "dict( string1=generate_string(length1), string2=generate_string(length2), ) final_text = \"\"\" Magnificent! Take a", "of the new methods we've learned, not just for characters", "thing_to_find = 'other' it should print `False`. \"\"\" hints =", "5: small_numbers.append(number) else: big_numbers.append(number) print(small_numbers) print(big_numbers) The button will open", "is `False`. - **`index`**: Returns the first index of a", "strings are incompatible. Is there a similar concept among strings", "what's special about `91` in the list `[21, 55, 4,", "will give you an error. By the way, you can", "loop over a copy, as in: for number in numbers.copy():", "same list. I recommend running both versions with Python Tutor", "using a `break` statement, like so: for thing in things:", "in string - `join` - python combine list of strings", "l z o a b e t h \"\"\"), }", "def program(self): word = 'Hello' print(word.upper) print(word.upper()) class no_append_for_str(VerbatimStep): \"\"\"", "= \"max([21, 55, 4, 91, 62, 49])\" def check(self): return", "modified, instead `word.upper()` returned a new string which was immediately", "is 10, which gets removed. This shifts the rest of", "additional ideas and pieces.\", dedent(\"\"\" In particular, it should still", "length1, length2 = length2, length1 return dict( string1=generate_string(length1), string2=generate_string(length2), )", "'the', 'store'] to_find = 'the' your program should print `1`.", "are separate objects, even if they start out with equal", "if to_find == things[i]: answer = i print(answer) tests =", "people. Now use `.append` to write a program which prints", "loop over `range(len(things))`. To check if an index is the", "want it to go between the second and third elements:", "a result, when you append 4 to `list1`, only `list1`", "you set the variable to `True`, it should never be", "\"\"\" An expression like `len(things)` or `print(things)` is a function", "In the second case, the two variables both have arrows", "range(10): print(i) class range_len(VerbatimStep): \"\"\" `range(n)` is similar to the", "lack of a real useful value. Functions that don't want", "next challenge is to fix this problem by filling in", "never be set to anything else after that. Don't use", "are: [0, 1, 2, ..., len(words) - 2, len(words) -", "from your exercises. I assure you that those exercises were", "that adds up all the numbers in a list: __program_indented__", "[ ((['on', 'the', 'way', 'to', 'the', 'store'], 'the'), 4), (([0,", "at the end it fails when it tries to access", "in: for number in numbers.copy(): Now the list being modified", "both variables can end up pointing to the same list.", "Here's another exercise. Given two strings of equal length, e.g:", "(['This', 'is', 'a', 'list'], 'Thisisalist'), (['The', 'quick', 'brown', 'fox', 'jumps'],", "you just want to retrieve a single element from the", "nums` is `False`. - **`index`**: Returns the first index of", "91, 62, 49]`, it will return `91`. You should write", "'is'), True), ((['This', 'is', 'a', 'list'], 'other'), False), (([1, 2,", "..., len(words) - 2, len(words) - 1] There's a handy", "numbers: if number > 5: big_numbers.append(number) print(big_numbers) tests = [", "the positions we want. For example in the first iteration", "are not callable, so trying to call them will give", "you experiment with indexing and `len()` with strings in the", "You could write `nums.append(9)` and `nums` would change to: [1,", "give you an error: __program_indented__ \"\"\" # noinspection PyCallingNonCallable def", "5].count(2)` is 3. You've already seen that `len` and subscripting", "is probably similar. It's fine, but it's a bit inefficient.", "`.append` on a string: __program_indented__ \"\"\" # noinspection PyUnresolvedReferences def", "no longer the positions we want. For example in the", "- `'the' in 'feed the dog and the cat'` is", "for index in range(len(words)): print(index) print(words[index]) class index_exercise(ExerciseStep): \"\"\" Let's", "learned before, `list2` doesn't remember `<expression>`, only the value. It", "different ways depending on whether `string1` or `string2` is longer.", "0. You can't add 0 to a string because numbers", "is *passed* to `len`, and `len` *accepts* or *receives* the", "value without changing the original argument. The only exception is", "class first_list(VerbatimStep): \"\"\" It's time to learn about a powerful", "\"\"\" hints = \"\"\" You will need a loop. You", "b v l i a n s g t \"\"\"),", "False]): length1, length2 = length2, length1 return dict( string1=generate_string(length1), string2=generate_string(length2),", "not to return a useful value. So it returns something", "the end of the list. `nums.append(4)` changes the list to", "in the list you should set that variable to `True`.", "`words[i]`. The operation is called *subscripting* or *indexing*, and the", "# TODO this is quite the information dump and I'd", "We could try writing the program to use `remove` instead", "you come across this kind of problem and you're still", "this: found = False for thing in things: if thing", "dict( things=things, thing_to_find=thing_to_find, ) final_text = \"\"\" Nice! A typical", "to solve a problem with lists and you need to", "random.randint(1, 3) random.shuffle(things) return dict( things=things, to_find=to_find, ) class zip_exercise(ExerciseStep):", "91, 62, 49]`? 'biggest' or 'largest' 'python biggest value in", "you want: all_numbers = [2, 4, 8, 1, 9, 7]", "print(big_numbers) Or you could build up a new list from", "only create new strings and use those instead. That means", "`[9, 2, 3]`. - **`join`**: Add a list of strings", "call them will give you an error: __program_indented__ \"\"\" #", "10: big_numbers.remove(number) print(big_numbers) Or you could build up a new", "to `list1`, only `list1` changes. Now change `list2 = [1,", "the first occurrence of the given element. `nums.remove(10)` will leave", "to the use of `.` - the error actually comes", "whatever `<expression>` evaluates to'. It doesn't make a copy of", "`3`. - **`range`**: `range(n)` is an object similar to the", "versions with Python Tutor to see how it visualises the", "= random.randrange(5, 11) length2 = random.randrange(12, 20) if random.choice([True, False]):", "elements of the previous solution, \" \"but it's significantly longer", "to do that. \"\"\" hints = \"\"\" Use the words", "second line you want to print the second character of", "if a list contains 5, but there's no similarly easy", "consists of things you're familiar with. We create two variables", "indexing and `len()` also work on strings. Try them out", "misunderstood and lead to errors. Run this program: __program_indented__ \"\"\"", "means 'make the variable `list2` refer to whatever `<expression>` evaluates", "FunctionsAndMethodsForLists(Page): # TODO this is quite the information dump and", "+= [number * 2] print(double) tests = [ ([3, 1,", "Many will start with `__` which you can ignore for", "set the variable to `True`, it should never be set", "brackets: `[]` 2. If you don't want an empty list,", "the hood. The lesson here is to ***never modify something", "of the two values \" \"`len(string1)` and `len(string2)`. You've already", "well if the strings have different lengths. In fact, it", "the ones smaller than 10. Or at least, it tries", "list1 = [1, 2, 3] list2 = [1, 2, 3]", "= \"\"\" Consider this program. It loops through a numbers", "expression like `len(things)` or `print(things)` is a function ***call*** -", "Most things are not callable, so trying to call them", "= len(things) printed = print(length) print(printed) class len_of_none(VerbatimStep): \"\"\" `None`", "- python combine list of strings with separator - python", "prints all the indices, not just the first one. \"\"\"", "it should print: Thisisalist \"\"\" hints = \"\"\" This is", "lists. Here's an example: __program_indented__ \"\"\" def program(self): words =", "valuable fundamental skills. For example, you can use `in` to", "have a list `nums = [1, 2, 3]`. You can", "5], [6, 2, 8, 2, 10, 18, 4, 12, 10]),", "Add a list of numbers. `sum(nums)` is 6. - **`in`**:", "= ['on', 'the', 'way', 'to', 'the', 'store'] to_find = 'the'", "for the same reason. Iterating over a list still goes", "retrieve a single element from the list at a known", "list of numbers and prints a list where each number", "things[i]: print(i) break tests = [ ((['on', 'the', 'way', 'to',", "4, 91, 62, 49])\" def check(self): return search_ast( self.stmt, ast.Call(func=ast.Name(id='max')),", "\"\"\" hints = [ \"The solution has the same overall", "that. \"\"\" hints = \"\"\" Use the words 'python' and", "that sometimes you should skip appending to the new list.", "in all_numbers: if number <= 5: small_numbers.append(number) else: big_numbers.append(number) print(small_numbers)", "this does the same thing, for the same reason. Iterating", "Try these for yourself. So in general, the valid indices", "`if` statements, one for each string.\", \"You will need to", "set to anything else after that. Don't use an `else`.", "5, 6, 6], 6), \"6\\n7\"), ] class last_index(MessageStep, ExerciseStep): \"\"\"", "You will need indexing (subscripting). You will need `range`. You", "need indexing (subscripting). You will need `range`. You will need", "\"\"\" class CallingFunctionsTerminology(Page): title = \"Terminology: Calling functions and methods\"", "function ***call*** - when you write that, you are ***calling***", "fact, what happens if you try running that program with", "`i` is 1, and `numbers[i]` is 8. 7 got skipped.", "the cat'.index('the')` is 5 Note that in most cases, methods", "to anything else after that. Don't use an `else`. There", "`==`. You need a boolean variable that you print at", "= [7, 8, 9]`, the other variable will be unaffected", "`list2 = list1` doesn't create an eternal link between the", "operator that checks if a value is in a list.", "same reason. Iterating over a list still goes through the", "If you find the element in the list you should", "means that regardless of the two lists being equal, they", "[pythontutor.com](http://pythontutor.com). There you can navigate through the program step by", "in numbers: if number > 5: big_numbers.append(number) print(big_numbers) tests =", "thing_to_find = random.choice(things) else: thing_to_find = random.choice([ min(things) - 1,", "(subscripting). You will need `range`. You will need `len`. You", "snoop to see the difference. \"\"\" class GettingElementsAtPosition(Page): title =", "and subscripting work with strings, a bit as if strings", "navigate through the program step by step with the \"Prev\"", "to set e.g. `char1 = ' '` when `string1[i]` is", "start out with equal contents. Similarly, you could loop over", "look at all possible indices, you will need a loop", "will be more familiar and readable to most people. Now", "{ (\"Goodbye\", \"World\"): dedent(\"\"\"\\ G W o o o r", "- `==` Since you're looking for the first index, you", "l z o a b e t h \"\"\" hints", "you want to print the second character of each string,", "\"\"\" Did you experiment with indexing and `len()` with strings", "need to go back to basics and strengthen your foundations.", "5, 9, 2, 6, 5] it would print: [9, 6]", "python test if list has element - `index` - python", "The button will open a new tab with a visualisation", "l i l z o a b e t h", "You can make a list with one element `x` by", "Here's some example code if you want: all_numbers = [2,", "This also means that the last index in this list", "there's a new comparison operator: `is`. Here `list1 is list2`", "t \"\"\"), } @classmethod def generate_inputs(cls): length = random.randrange(5, 11)", "= \"\"\" Nice! A typical solution looks something like this:", "4, 5, 6, 6], 6), 7), ] @returns_stdout def solution(self,", "of numbers - `in` - python check if list contains", "Python Tutor. numbers = [10, 7, 8, 3, 12, 15]", "character. Make a new list, and then build it up", "it with Python Tutor. numbers = [10, 7, 8, 3,", "thing == thing_to_find: found = True print(found) tests = [", "should print `True`, but for thing_to_find = 'other' it should", "of numbers. For example, given: words = ['This', 'is', 'a',", "NOQA E501 import ast import random from textwrap import dedent", "the second line you want to print the second character", "are still two separate, distinct, individual lists. As a result,", "the variable `list2` refer to whatever `<expression>` evaluates to'. It", "tests = [ ((['on', 'the', 'way', 'to', 'the', 'store'], 'the'),", "want to return anything return `None` by default. If you", "often misunderstood and lead to errors. Run this program: __program_indented__", "l r l l o d \"\"\"), (\"Having\", \"ablast\"): dedent(\"\"\"\\", "all the indices, not just the first one. \"\"\" @returns_stdout", "the list to `[9, 2, 3]`. - **`join`**: Add a", "@returns_stdout def solution(self, things, to_find): for i in range(len(things)): if", "modify something while you iterate over it***. Keep mutation and", "to *either* of the variables, e.g. `list1 = [7, 8,", "`to_find`. For example, for things = ['on', 'the', 'way', 'to',", "59, 64]`. Raises an error if the value doesn't exist.", "it returns something useless instead: __program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment", "'the', 'store'], 'the'), \"1\\n4\"), (([0, 1, 2, 3, 4, 5,", "to write a program which prints a list containing only", "you need to find the biggest of the two values", "That means that regardless of the two lists being equal,", "the biggest of the two values \" \"`len(string1)` and `len(string2)`.", "out `for i in range(...)`, `i` will sometimes be too", "doesn't work so well if the strings have different lengths.", "to assign a new value to the variable: word =", "True), (([1, 2, 3, 4], 0), False), ] @classmethod def", "\"What should go inside `range()`? Neither `len(string1)` nor `len(string2)` is", "\"\"\" As you saw above, lists are *iterable*, meaning you", "element. `nums.remove(10)` will leave `nums` as `[28, 99, 81, 59,", "on the right. \"\"\" class EqualsVsIs(Page): title = \"`==` vs", "to be a little more interactive, # but users don't", "index. `nums[0] = 9` changes the list to `[9, 2,", "to `list2 = list1` and see what difference it makes.", "you're looking for the first index, you need to stop", "there. You may recognise some of these from your exercises.", "1] There's a handy built in function to give you", "G W o o o r d l b d", "methods_of_str(VerbatimStep): \"\"\" A ***method*** is a function which belongs to", "Find a function/method that returns the value in a list", "familiar and readable to most people. Now use `.append` to", "list of numbers from 0 to `n - 1`. In", "'way', 'to', 'the', 'store'], 'the'), 1), (([0, 1, 2, 3,", "list and a value and checks if the list contains", "fix this problem by filling in 'missing' characters with spaces.", "= \"Elizabeth\" output: H E e l l i l", "How would you print just the first line, which has", "- when you write that, you are ***calling*** the function", "most programming languages do it, and it's generally agreed to", "empty list that has no elements. Check for yourself: numbers", "checks if a value is in a list. `2 in", "This program is quite straightforward and mostly consists of things", "very similar to the program that adds numbers. In fact,", "((['This', 'is', 'a', 'list'], 'is'), True), ((['This', 'is', 'a', 'list'],", "with e.g. `word.upper()`: __program_indented__ \"\"\" def program(self): word = 'Hello'", "word = 'Hello' print(word.upper) print(word.upper()) class no_append_for_str(VerbatimStep): \"\"\" Another example", "in the shell. \"\"\" program = \"dir([])\" final_text = \"\"\"", "string1 = \"Goodbye\" string2 = \"World\" output: G W o", "Let's do one more. If you have a list: nums", "see the word ***parameter***, which means basically the same thing", "not callable, so trying to call them will give you", "__program_indented__ \"\"\" def program(self): word = 'Hello' print(word.upper) print(word.upper()) class", "\"\"\" def program(self): print(callable(len)) class not_callable(VerbatimStep): \"\"\" Most things are", "familiar methods. Here are a few more useful functions/methods. Suppose", "something like this: found = False for thing in things:", "difference between these, but `.append` will be more familiar and", "string2): for i in range(len(string1)): char1 = string1[i] char2 =", "to build up strings character by character. Make a new", "= '' for word in words: total += word print(total)", "a big difference between these, but `.append` will be more", "Calling functions and methods\" class print_functions(VerbatimStep): \"\"\" It's time to", "a list `things` and a value `to_find`, print the first", "buttons, or drag the slider left or right. You can", "output: G W o o o r d l b", "more important skill is being able to look things up.", "with a loop. \"\"\" hints = \"\"\" Use the words", "in range(length): if i < len(string1): char1 = string1[i] else:", "Another example is that `append` is a method of lists.", "an index. `nums[0] = 9` changes the list to `[9,", "= length2, length1 return dict( string1=generate_string(length1), string2=generate_string(length2), ) final_text =", "print(i) break tests = [ ((['on', 'the', 'way', 'to', 'the',", "If you don't want an empty list, write some expressions", "methods of strings, which are called with e.g. `word.upper()`: __program_indented__", "numbers.pop(i) print(numbers) (remember that `numbers.pop(i)` removes the element from `numbers`", "same thing, for the same reason. Iterating over a list", "*between* each word. For example, given words = ['This', 'is',", "also see the values of variables on the right. \"\"\"", "looking for the function `sum`, you could write `sum([21, 55,", "'store'], 'the'), 4), (([0, 1, 2, 3, 4, 5, 6,", "the element at the position `i` with `words[i]`. The operation", "\"\"\"), \"What should go inside `range()`? Neither `len(string1)` nor `len(string2)`", "= random.choice(things) else: thing_to_find = random.choice([ min(things) - 1, max(things)", "difference. In the second case, the two variables both have", "happens? The index variable `i` runs through the usual values", "`None` by default. If you see an error message about", "2, ... as it's supposed to, but as the list", "64, 81, 99]`. - **`pop`**: Removes and returns an element", "you need to stop the loop once you find one.", "both versions with Python Tutor to see how it visualises", "string1=generate_string(length), string2=generate_string(length), ) class zip_longest_exercise(ExerciseStep): \"\"\" Incredible! Your solution probably", "method of strings (the separator) which takes an iterable of", "cat'.count('the')` is 2 - `'feed the dog and the cat'.index('the')`", "program(self): for i in range(10): print(i) class range_len(VerbatimStep): \"\"\" `range(n)`", "list of strings instead of numbers. For example, given: words", "that checks if a value is in a list. `2", "empty string if you don't want a separator, e.g. `''.join(['apples',", "it will remove and return the last element. - **`remove`**:", "assignment like: list2 = <expression> means 'make the variable `list2`", "contains the value. For example, given: things = ['This', 'is',", "a method of lists. But you can't use `.upper` on", "any loop using a `break` statement, like so: for thing", "being able to look things up. For example, here are", "also see the word ***parameter***, which means basically the same", "of element - python get index of value Let's practice", "H E e l l i l z o a", "between. This is a method of strings (the separator) which", "position, so now 7 is in position 0. But then", "1, 2, 3, 4, 5, 6, 6], 6), 6), ]", "shell? Forget loops for a moment. How would you print", "of variables on the right. \"\"\" class EqualsVsIs(Page): title =", "`len(string1) - 1`. \" \"`len(string)` is too big.\", \"You will", "# noinspection PyNoneFunctionAssignment def program(self): things = [1, 2, 3]", "list is a *sequence* (an ordered collection/container) of any number", "tries to. I recommend running it with Python Tutor. numbers", "appends to the one list and the result can be", "are ***callable***: __program_indented__ \"\"\" def program(self): print(callable(len)) class not_callable(VerbatimStep): \"\"\"", "no elements. Check for yourself: numbers = [1, 2] +", "`in` to check if a list contains 5, but there's", "should still contain something like: for i in range(...): ...", "can also see the values of variables on the right.", "`True`, because *there is only one list*, and the two", "returns a list of the elements in order. `sorted(nums)` returns", "... as it's supposed to, but as the list changes", "which modify a list in place (`append`, `insert`, `remove`) merely", "- a - list Lists and strings have a lot", "By the way, indexing and `len()` also work on strings.", "were looking for the function `sum`, you could write `sum([21,", "7, 2, 5].count(2)` is 3. You've already seen that `len`", "so on. You will need a `for` loop. You will", "1, ]) return dict( things=things, thing_to_find=thing_to_find, ) final_text = \"\"\"", "an empty string if you don't want a separator, e.g.", "by character. The solution is very similar to the program", "`list2` refer to whatever `<expression>` evaluates to'. It doesn't make", "'list'] for index in range(len(words)): print(index) print(words[index]) class index_exercise(ExerciseStep): \"\"\"", "value at the beginning or end, we want to put", "add a single element to the end of a list,", "print(list1) print(list2) class same_list(VerbatimStep): \"\"\" This program is quite straightforward", "that this is possible means that functions are ***callable***: __program_indented__", "of `pop` so we don't have to use indices. It", "they don't have any methods like `append` or even subscript", "`==` Since you're looking for the first index, you need", "'store'], 'the'), 1), (([0, 1, 2, 3, 4, 5, 6,", "to see how it visualises the difference. In the second", "be useful to Google things like \"python list tutorial\", e.g.", "= \"\"\" Remember that you can multiply numbers using `*`.", "([3, 1, 4, 1, 5, 9, 2, 6, 5], [9,", "the dog and the cat'` is `True` - `'feed the", "return something...even if it's nothing. For example, `print`'s job is", "\"\"\" `dir()` returns a list of the argument's attributes, which", "which takes a list of numbers and prints a list", "thing == thing_to_find: found = True break This is just", "first one. \"\"\" @returns_stdout def solution(self, things, to_find): for i", "to find the biggest of the two values \" \"`len(string1)`", "h \"\"\" hints = [ \"The solution has the same", "the element. You can use snoop to see the difference.", "if word.lower() == 'yes': \"\"\" class UnderstandingProgramsWithPythonTutor(Page): final_text = \"\"\"", "order. `sorted(nums)` returns `[10, 28, 59, 64, 81, 99]`. -", "`list1 is list2` is `True`, because *there is only one", "] class double_numbers(ExerciseStep): \"\"\" Optional bonus challenge: extend the program", "81, 99]`. - **`pop`**: Removes and returns an element at", "instead of `pop` so we don't have to use indices.", "to `[1, 2, 3, 4]`. - **`len`**: Returns the number", "They can also be a mixture of types. To create", "to the exercises you've done building up strings character by", "bonus challenge: extend the program to insert a separator string", "just the first one. \"\"\" @returns_stdout def solution(self, things, to_find):", "Now change `list2 = [1, 2, 3]` to `list2 =", "reason. Iterating over a list still goes through the indices", "= ['This', 'is', 'a', 'list'] print(words[0]) print(words[1]) print(words[2]) print(words[3]) class", "the shell. \"\"\" program = \"dir([])\" final_text = \"\"\" `dir()`", "True print(found) Your solution is probably similar. It's fine, but", "means you assigned the wrong thing to a variable: __program_indented__", "is called the *index*. You've probably noticed that the first", "= [1, 2, 3] print(list1) print(list2) print(list1 == list2) print(list1", "like this: found = False for thing in things: if", "It's time to learn about another tool to explore programs.", "evaluates to'. It doesn't make a copy of that value,", "62, 49])\" def check(self): return search_ast( self.stmt, ast.Call(func=ast.Name(id='max')), ) class", "too high. Can you see why this happens? The index", "skips even looking at 7 or 3 and doesn't remove", "def program(self): list1 = [1, 2, 3] list2 = [1,", "Sometimes you will also see the word ***parameter***, which means", "<expression> means 'make the variable `list2` refer to whatever `<expression>`", "10, 18, 4, 12, 10] \"\"\" hints = \"\"\" Remember", "In general, you can get the element at the position", "the value at the beginning or end, we want to", "how to stop a loop in the middle recently. You", "r d l b d y e \"\"\"), (\"Hello\", \"Elizabeth\"):", "element - `index` - python get position of element -", "dedent(\"\"\"\\ H W e o l r l l o", "combine list of strings with separator - python add together", "so you want to find it manually. - You're still", "(\"Hello\", \"Elizabeth\"): dedent(\"\"\"\\ H E e l l i l", "`[1, 2, 3, 2, 7, 2, 5].count(2)` is 3. You've", "'list'] for word in words: print(word) class can_contain_anything(VerbatimStep): \"\"\" A", "is to display something on screen, not to return a", "need to find the biggest of the two values \"", "an argument, i.e. just `nums.pop()`, it will remove and return", "are often referred to as *elements*. They can be anything:", "`4 in nums` is `False`. - **`index`**: Returns the first", "Google things like \"python list tutorial\", e.g. if: - Googling", "instead of numbers. For example, given: words = ['This', 'is',", "`nums.append(9)` and `nums` would change to: [1, 2, 3, 4,", "= [1, 2, 3, 4, 5] You could write `nums.append(9)`", "lists. But you can't use `.upper` on a list or", "will return `91`. You should write the answer in the", "words = ['This', 'is', 'a', 'list'] it should print: Thisisalist", "can navigate through the program step by step with the", "list of 4 elements is 3. What happens if you", "= \"\"\" You will need to look at all the", "range(length): if i < len(string1): char1 = string1[i] else: char1", "between the variables. If you assign a new value to", "if you were looking for the function `sum`, you could", "display something on screen, not to return a useful value.", "written to build up strings character by character. Make a", "`things` is an ***argument***. Sometimes you will also see the", "Your solution probably looks something like this: for i in", "is `True` - `'feed the dog and the cat'.count('the')` is", "challenge is to fix this problem by filling in 'missing'", "general, you can get the element at the position `i`", "want. For example in the first iteration `i` is 0", "11) return dict( string1=generate_string(length), string2=generate_string(length), ) class zip_longest_exercise(ExerciseStep): \"\"\" Incredible!", "the second and third elements: [1, 2, 9, 3, 4,", "a copy, as in: for number in numbers.copy(): Now the", "big_numbers = numbers.copy() for number in numbers: if number <=", "set e.g. `char1 = ' '` when `string1[i]` is not", "@returns_stdout def solution(self, words: List[str]): total = '' for word", "2, 4, 6, 8, 10], [6, 8, 10]), ] final_text", "`i` is 0 and `number` is 10, which gets removed.", "possible means that functions are ***callable***: __program_indented__ \"\"\" def program(self):", "[1, 2, 3, 4, 5, 9] But suppose you don't", "`words[len(words) - 1]`. Try these for yourself. So in general,", "numbers, strings, booleans, even lists! They can also be a", "them together into a new list. You can also create", "- `sum` - python add list of numbers - python", "filling in 'missing' characters with spaces. For example, for: string1", "the list `[21, 55, 4, 91, 62, 49]`? 'biggest' or", "value in a list. `[7, 8, 9, 8].index(8)` is 1.", "a separator, e.g. `''.join(['apples', 'oranges', 'bananas'])` returns `'applesorangesbananas'`. - **`sum`**:", "3] list2 = [1, 2, 3] print(list1) print(list2) print(list1 ==", "= len(things) class methods_of_str(VerbatimStep): \"\"\" A ***method*** is a function", "returns something useless instead: __program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment def", "your exercises. I assure you that those exercises were not", "thing in an exercise: numbers = [10, 7, 8, 3,", "good enough.\", \"You want a loop iteration for every character", "an element at a given index. `nums.pop(3)` removes `nums[3]` (`81`)", "2, 3, 4, 5]`. Here's some new things. Try them", "final_text = \"\"\" `dir()` returns a list of the argument's", "python total of numbers - `in` - python check if", "insert a separator string *between* each word. For example, given", "functions/methods return a new useful value without changing the original", "be a little more interactive, # but users don't need", "\"\"\" class UnderstandingProgramsWithPythonTutor(Page): final_text = \"\"\" It's time to learn", "`word.upper()` immediately in a larger expression, e.g. if word.lower() ==", "strings are lists of characters. Strings also support some of", "have to return something...even if it's nothing. For example, `print`'s", "'jumps'], 'Thequickbrownfoxjumps'), ] class double_numbers(ExerciseStep): \"\"\" Optional bonus challenge: extend", "Now `list1 is list2` is `True`, because *there is only", "subscript - `==` Since you're looking for the first index,", "You will need a loop. You will need an `if`", "called on all values of that type using `.`. For", "which takes a list and a value and checks if", "between each character: H W e o l r l", "too big.\", \"You will need two `if` statements, one for", "`len` ***returned*** 3. All calls have to return something...even if", "at an index. `nums[0]` is 1, `nums[1]` is 2, `nums[2]`", "4, 5]`. Here's some new things. Try them out in", "= 'is' it should print `True`, but for thing_to_find =", "are *mutable*, while those that can't are *immutable*. Strings are", "variables which refer to lists. The lists have the same", "next iteration `i` is 1, and `numbers[i]` is 8. 7", "like: for i in range(...): ... print(char1 + ' '", "7 or 3 and doesn't remove them, and at the", "of 4 elements is 3. What happens if you try", "an argument. `'--'.join(['apples', 'oranges', 'bananas'])` returns `'apples--oranges--bananas'`. You can also", "shell. \"\"\" program = \"dir([])\" final_text = \"\"\" `dir()` returns", "removes the element from `numbers` at index `i`) As it", "Step, VerbatimStep, search_ast from main.utils import returns_stdout class IntroducingLists(Page): class", "to a list by adding a list containing one element.", "= 'Hello' word.append('!') final_text = \"\"\" The word 'attribute' in", "between elements to separate them. Here's another example of making", "for i in range(len(string1)): char1 = string1[i] char2 = string2[i]", "n - 1]`. This gives us an alternative way to", "['This', 'is', 'a', 'list'] print(words[0]) print(words[1]) print(words[2]) print(words[3]) class index_error(Step):", "that `word` refers to, you have to assign a new", "range(len(things)): if to_find == things[i]: print(i) tests = [ ((['on',", "loop over the original and modify a copy: numbers =", "final_text = \"\"\" Fantastic! We're making great progress. \"\"\" class", "[3, 4] print(numbers) new_numbers = [] new_numbers += numbers new_numbers", "get the number of elements in a list (commonly called", "class print_returns_none(VerbatimStep): \"\"\" In the call `len(things)`, `things` is an", "is the answer, you will need to use: - `if`", "you've sorted out `for i in range(...)`, `i` will sometimes", "another tool to explore programs. Put some code in the", "Is there a similar concept among strings to 0? A", "from typing import List from main.exercises import generate_list, generate_string from", "if it finds the element at the beginning. You can", "7 is in position 0. But then in the next", "big_numbers.remove(number) print(big_numbers) Or you could build up a new list", "\"That means you need `range(<length of the longest string>)`\", \"In", "'make the variable `list2` refer to whatever `<expression>` evaluates to'.", "so trying to call them will give you an error:", "of any number of values. The values are often referred", "could write `nums.append(9)` and `nums` would change to: [1, 2,", "of the numbers left one position, so now 7 is", "at least, it tries to. I recommend running it with", "class dir_list(VerbatimStep): \"\"\" Perfect! It can also be useful to", "- python total of numbers - `in` - python check", "making great progress. \"\"\" class UsingBreak(Page): title = \"Using `break`", "pointless, as you've now learned valuable fundamental skills. For example,", "at end of list - `len` - python size of", "- **`remove`**: Removes the first occurrence of the given element.", "list from scratch. In this case, we've already done a", "= len(string1) length2 = len(string2) if length1 > length2: length", "list containing only the numbers bigger than 5. For example,", "- python number of elements in list - python how", "i.e. just `nums.pop()`, it will remove and return the last", "way to loop over a list: __program_indented__ \"\"\" def program(self):", "will need `len`. You will need `+`. You will need", "list: __program_indented__ \"\"\" def program(self): x = 1 things =", "You can add an element to a list by adding", "= [10, 7, 8, 3, 12, 15] big_numbers = numbers.copy()", "__program_indented__ \"\"\" def program(self): words = ['This', 'is', 'a', 'list']", "contained = random.choice([True, False]) things = generate_list(int) if contained: thing_to_find", "so now 7 is in position 0. But then in", "`.`. For example, `upper` and `lower` are methods of strings,", "iteration for every character in the longer string.\", \"That means", "zip_exercise(ExerciseStep): \"\"\" Nice! By the way, indexing and `len()` also", "them with a `for loop`. Here's a program that adds", "- the index in a subscript - `==` Since you're", "To create a list directly, like above: 1. Write some", "which belongs to a type, and can be called on", "`NoneType`, it often means you assigned the wrong thing to", "and lead to errors. Run this program: __program_indented__ \"\"\" def", "between these, but `.append` will be more familiar and readable", "You will need to index both strings. You will need", "exercises were not pointless, as you've now learned valuable fundamental", "programs you've written to build up strings character by character.", "\"\"\" class UsingBreak(Page): title = \"Using `break` to end a", "f() class print_returns_none(VerbatimStep): \"\"\" In the call `len(things)`, `things` is", "element. \"\"\" @returns_stdout def solution(self, numbers: List[int]): double = []", "other value. For example, given the list `[21, 55, 4,", "**`+`**: Concatenates lists. `nums + [4, 5]` is `[1, 2,", "99]`. - **`pop`**: Removes and returns an element at a", "programming languages do it, and it's generally agreed to be", "is list2) list1.append(4) print(list1) print(list2) final_text = \"\"\" Now `list1", "button will open a new tab with a visualisation from", "function `sum`, you could write `sum([21, 55, 4, 91, 62,", "6), 7), ] @returns_stdout def solution(self, things, to_find): for i", "in the shell. Here's another exercise. Given two strings of", "enforce not using += @returns_stdout def solution(self, numbers: List[int]): big_numbers", "of that value, which is how both variables can end", "\"\"\" def program(self): x = 1 things = ['Hello', x,", "new things. Try them out in the shell. - **`subscript", "so: for thing in things: if thing == thing_to_find: found", "but often you just want to retrieve a single element", "3] print(things) class numbers_sum(VerbatimStep): \"\"\" As you saw above, lists", "solution(self, things, to_find): for i in range(len(things)): if to_find ==", "example, for: string1 = \"Goodbye\" string2 = \"World\" output: G", "the original argument. The only exception is the `pop` method.", "\"\"\" Fantastic! We're making great progress. \"\"\" class UsingBreak(Page): title", "`len(string1)` nor `len(string2)` is good enough.\", \"You want a loop", "`to_find`, print the first index of `to_find` in the list,", "] class last_index(MessageStep, ExerciseStep): \"\"\" You're almost there! However, this", "go between the second and third elements: [1, 2, 9,", "types. To create a list directly, like above: 1. Write", "`print(list2)` because both lines are now just different ways of", "to check if a list contains 5, but there's no", "@returns_stdout def solution(self, string1, string2): length1 = len(string1) length2 =", "able to look things up. For example, here are some", "List[int]): big_numbers = [] for number in numbers: if number", "`things` is *passed* to `len`, and `len` *accepts* or *receives*", "second and third elements: [1, 2, 9, 3, 4, 5]", "languages do it, and it's generally agreed to be better.", "which takes an iterable of strings as an argument. `'--'.join(['apples',", "as it's supposed to, but as the list changes those", "You're almost there! However, this prints the *last* index, not", "this manually with a loop. \"\"\" hints = \"\"\" Use", "PyUnresolvedReferences def program(self): word = 'Hello' word.append('!') final_text = \"\"\"", "error message refers to the use of `.` - the", "difference is that sometimes you should skip appending to the", "= length1 else: length = length2 for i in range(length):", "list2 = list1 print(list1) print(list2) print(list1 == list2) print(list1 is", "[element] it's actually more common to write: some_list.append(element) There isn't", "if they start out with equal contents. Similarly, you could", "their names: - `append` - python add element to list", "class range_len(VerbatimStep): \"\"\" `range(n)` is similar to the list `[0,", "`print`'s job is to display something on screen, not to", "the next iteration `i` is 1, and `numbers[i]` is 8.", "reason to ever set the variable to `False` inside the", "you forgot their names: - `append` - python add element", "ModifyingWhileIterating(Page): final_text = \"\"\" Consider this program. It loops through", "example is that `append` is a method of lists. But", "program that adds up all the numbers in a list:", "them, and at the end it fails when it tries", "2]`. - **`subscripting`**: Get a value at an index. `nums[0]`", "write a program which takes a list of numbers and", "how many characters in string - `join` - python combine", "of the two lists being equal, they are still two", "number in numbers: if number > 5: big_numbers.append(number) print(big_numbers) tests", "list: __program_indented__ \"\"\" def program(self): numbers = [3, 1, 4,", "`range(<length of the longest string>)`\", \"In other words you need", "W e o l r l l o d \"\"\"", "list2` is `False`. That means that regardless of the two", "the last valid index of the list is `len(words) -", "is being able to look things up. For example, here", "say that the argument `things` is *passed* to `len`, and", "(remember that `numbers.pop(i)` removes the element from `numbers` at index", "program to use `remove` instead of `pop` so we don't", "Takes an iterable and returns a list of the elements", "`for loop`. Here's a program that adds up all the", "loop once you find one. You learned how to stop", "can be called on all values of that type using", "those that can't are *immutable*. Strings are immutable - they", "the \"Prev\" or \"Next\" buttons, or drag the slider left", "a Position\" class introducing_subscripting(VerbatimStep): \"\"\" Looping is great, but often", "Or at least, it tries to. I recommend running it", "it turns out this does the same thing, for the", "example in the first iteration `i` is 0 and `number`", "a list where each number has been doubled. For example,", "'the' your program should print `1`. You can assume that", "0 to a string because numbers and strings are incompatible.", "could loop over the original and modify a copy: numbers", "False), ] @classmethod def generate_inputs(cls): contained = random.choice([True, False]) things", "Equivalent to `nums.pop(nums.index(10))`. - **`count`**: Returns the number of times", "index in a subscript - `==` Since you're looking for", "the list being modified and the list being itererated over", "supposed to, but as the list changes those are no", "similar to the exercises you've done building up strings character", "or 3 and doesn't remove them, and at the end", "t h \"\"\"), } @classmethod def generate_inputs(cls): length1 = random.randrange(5,", "\"python list tutorial\", e.g. if: - Googling a specific method", "a function ***call*** - when you write that, you are", "= [ (['This', 'is', 'a', 'list'], 'Thisisalist'), (['The', 'quick', 'brown',", "\"\"\"), } @classmethod def generate_inputs(cls): length1 = random.randrange(5, 11) length2", "discarded. If you want to change the value that `word`", "stuff, read the essay [Facts and myths about Python names", "the right function/method in the shell to do that. \"\"\"", "adding a list containing one element. \"\"\" @returns_stdout def solution(self,", "the value. For example, given: things = ['This', 'is', 'a',", "need a boolean variable that you print at the end.", "will need `+`. You will need to index both strings.", "n s g t \"\"\"), } @classmethod def generate_inputs(cls): length", "= \"Terminology: Calling functions and methods\" class print_functions(VerbatimStep): \"\"\" It's", "then build it up element by element in a for", "Now modify the program so that it can add up", "2, ..., n - 2, n - 1]`. This gives", "an error message about `None` or `NoneType`, it often means", "@classmethod def generate_inputs(cls): length1 = random.randrange(5, 11) length2 = random.randrange(12,", "in which case we say that `len` ***returned*** 3. All", "is `len(words) - 1`, so the last element is `words[len(words)", "big difference between these, but `.append` will be more familiar", "**`append`**: Add an element to the end of the list.", "exercise! Given a list `things` and a value `to_find`, print", "4], 1), True), (([1, 2, 3, 4], 0), False), ]", "list (commonly called the *length*) using `len(words)`. That means that", "Don't use an `else`. There is no reason to ever", "is `False`. That means that regardless of the two lists", "= [28, 99, 10, 81, 59, 64]` - **`sorted`**: Takes", "`.append` to write a program which prints a list containing", "get index of value Let's practice this skill now. Find", "on its own: word.upper() The string referred to by `word`", "last_index(MessageStep, ExerciseStep): \"\"\" You're almost there! However, this prints the", "news is that there are many ways to solve this.", "just for characters but for any substring. For example: -", "MessageStep, Page, Step, VerbatimStep, search_ast from main.utils import returns_stdout class", "in most cases, methods which modify a list in place", "program so that it can add up a list of", "one element `x` by just writing `[x]`. You can add", "result can be seen in both `print(list1)` and `print(list2)` because", "up. For example, here are some typical ways you might", "to the one list and the result can be seen", "thing_to_find): found = False for thing in things: if thing", "the wrong thing to a variable: __program_indented__ \"\"\" # noinspection", "doesn't know about other variables. You can copy a list", "**`sum`**: Add a list of numbers. `sum(nums)` is 6. -", "you can ignore for now - scroll to the end", "total += number print(total) class strings_sum(ExerciseStep): \"\"\" Now modify the", "list2 = [1, 2, 3] print(list1) print(list2) print(list1 == list2)", "main.exercises import generate_list, generate_string from main.text import ExerciseStep, MessageStep, Page,", "a larger expression, e.g. if word.lower() == 'yes': \"\"\" class", "= ['This', 'is', 'a', 'list'] for word in words: print(word)", "8, 10]), ] final_text = \"\"\" Fantastic! We're making great", "+ 3] print(things) class numbers_sum(VerbatimStep): \"\"\" As you saw above,", "exercise. The difference is that sometimes you should skip appending", "try writing the program to use `remove` instead of `pop`", "tests = [ ((['This', 'is', 'a', 'list'], 'is'), True), ((['This',", "don't exist, so trying that will give you an error.", "the other variable will be unaffected and will still point", "put it ____________? 'in the middle' or 'at an index'", "it's significantly longer and will require \" \"a few additional", "You can use snoop to see the difference. \"\"\" class", "`break` to end a loop early\" class list_contains_exercise(ExerciseStep): \"\"\" Exercise:", "refer to lists. The lists have the same elements, so", "all the numbers in a list: __program_indented__ \"\"\" def program(self):", "= \"\"\" This is very similar to the exercises you've", "= [] for number in numbers: double += [number *", "of that type using `.`. For example, `upper` and `lower`", "= print([1, 2, 3]) length = len(things) class methods_of_str(VerbatimStep): \"\"\"", "string1, string2): for i in range(len(string1)): char1 = string1[i] char2", "3] print(list1) print(list2) print(list1 == list2) print(list1 is list2) list1.append(4)", "doesn't remember `<expression>`, only the value. It doesn't know about", "and third elements: [1, 2, 9, 3, 4, 5] Call", "each number has been doubled. For example, given: numbers =", "common. For example, you can add two lists to combine", "Let's get some exercise! Given a list `things` and a", "a list with the `copy` method: list2 = list1.copy() This", "learned how to stop a loop in the middle recently.", "can add up a list of strings instead of numbers.", "`91`. You should write the answer in the shell as", "= \"Hello\" string2 = \"Elizabeth\" output: H E e l", "in between. This is a method of strings (the separator)", "is quite the information dump and I'd like it to", "and the cat'.index('the')` is 5 Note that in most cases,", "a list with one element `x` by just writing `[x]`.", "is 1, `nums[1]` is 2, `nums[2]` is 3. - **`+`**:", "real useful value. Functions that don't want to return anything", "A more important skill is being able to look things", "\"\"\" # TODO enforce not using += @returns_stdout def solution(self,", "import ast import random from textwrap import dedent from typing", "previous exercise. The difference is that sometimes you should skip", "an iterable and returns a list of the elements in", "the same index to both strings each time to retrieve", "list and the result can be seen in both `print(list1)`", "probably noticed that the first index is 0, not 1.", "to print the second character of each string, and so", "to pass the same index to both strings each time", "beyond don't exist, so trying that will give you an", "' ' if i < len(string2): char2 = string2[i] else:", "contain something like: for i in range(...): ... print(char1 +", "print(list1 is list2) list1.append(4) print(list1) print(list2) class same_list(VerbatimStep): \"\"\" This", "def solution(self, string1, string2): for i in range(len(string1)): char1 =", "want to put it ____________? 'in the middle' or 'at", "has the same overall structure and \" \"essential elements of", "appending to the new list. Use an `if` statement. Use", "3, 4, 5]`. Here's some new things. Try them out", "of the list is `len(words) - 1`, so the last", "= list1 print(list1) print(list2) print(list1 == list2) print(list1 is list2)", "x, x + 3] print(things) class numbers_sum(VerbatimStep): \"\"\" As you", "to check for a number bigger than 5. It's useful", "this program: __program_indented__ \"\"\" def program(self): list1 = [1, 2,", "a new value to *either* of the variables, e.g. `list1", "something on screen, not to return a useful value. So", "\"Getting Elements at a Position\" class introducing_subscripting(VerbatimStep): \"\"\" Looping is", "scratch. In this case, we've already done a similar thing", "- **`sum`**: Add a list of numbers. `sum(nums)` is 6.", "with `__` which you can ignore for now - scroll", "Thisisalist \"\"\" hints = \"\"\" This is very similar to", "single element to the end of a list, instead of:", "__program_indented__ \"\"\" def program(self): numbers = [3, 1, 4, 1,", "we say that the argument `things` is *passed* to `len`,", "similar to the previous exercise. The difference is that sometimes", "too big \" \"to be a valid index for both", "variables. You can copy a list with the `copy` method:", "\"\"\" Exercise: write a program which takes a list and", "5, 6, 6], 6), 7), ] @returns_stdout def solution(self, things,", "argument. The only exception is the `pop` method. Modifying a", "the usual values 0, 1, 2, ... as it's supposed", "better. This also means that the last index in this", "6]), ] class filter_numbers(ExerciseStep): \"\"\" Great! When you want to", "and readable to most people. Now use `.append` to write", "typing import List from main.exercises import generate_list, generate_string from main.text", "would you print just the first line, which has the", "single list object. `list2 = list1` doesn't create an eternal", "a b e t h \"\"\"), } @classmethod def generate_inputs(cls):", "build up a new list from scratch. In this case,", "the one list and the result can be seen in", "don't want a separator, e.g. `''.join(['apples', 'oranges', 'bananas'])` returns `'applesorangesbananas'`.", "with one element `x` by just writing `[x]`. You can", "do anything interesting. It's a common placeholder that represents the", "index in range(len(words)): print(index) print(words[index]) class index_exercise(ExerciseStep): \"\"\" Let's get", "takes a list of numbers and prints a list where", "= [ ((['on', 'the', 'way', 'to', 'the', 'store'], 'the'), 1),", "`to_find` appears at least once. \"\"\" hints = \"\"\" You", "a particular position' 'python add value at index' \"\"\" program", "range(len(numbers)): number = numbers[i] if number <= 10: numbers.pop(i) print(numbers)", "list `[21, 55, 4, 91, 62, 49]`? 'biggest' or 'largest'", "0 for number in numbers: total += number print(total) class", "is - a - list Lists and strings have a", "can't add 0 to a string because numbers and strings", "print(i) class range_len(VerbatimStep): \"\"\" `range(n)` is similar to the list", "Nice! By the way, indexing and `len()` also work on", "a list of the elements in order. `sorted(nums)` returns `[10,", "thing_to_find = 'is' it should print `True`, but for thing_to_find", "i l z o a b e t h \"\"\"", "`len(things)`, `things` is an ***argument***. Sometimes you will also see", "and `numbers[i]` is 8. 7 got skipped. We could try", "[10, 7, 8, 3, 12, 15] for i in range(len(numbers)):", "(commonly called the *length*) using `len(words)`. That means that the", "thing_to_find = random.choice([ min(things) - 1, max(things) + 1, ])", "modify a copy: numbers = [10, 7, 8, 3, 12,", "a new comparison operator: `is`. Here `list1 is list2` is", "It's time to expand your vocabulary some more. `print` and", "in function to give you these values, called `range`: __program_indented__", "first line, which has the first character of each of", "Your solution is probably similar. It's fine, but it's a", "= string1[i] else: char1 = ' ' if i <", "This will make the program behave like the first version", "`nums.pop(3)` removes `nums[3]` (`81`) from the list and returns it.", "some expressions inside to be the elements. 3. Put commas", "s g t \"\"\"), } @classmethod def generate_inputs(cls): length =", "print(new_numbers) With that knowledge, write a program which takes a", "to give you these values, called `range`: __program_indented__ \"\"\" def", "as if strings are lists of characters. Strings also support", "strings (the separator) which takes an iterable of strings as", "item at end of list - `len` - python size", "like the first version again. If you come across this", "you could build up a new list from scratch. In", "`list1 = [7, 8, 9]`, the other variable will be", "you could loop over the original and modify a copy:", "have arrows pointing to a single list object. `list2 =", "once you find one. You learned how to stop a", "index. `nums.pop(3)` removes `nums[3]` (`81`) from the list and returns", "in numbers: if number <= 10: numbers.remove(number) print(numbers) But it", "numbers: List[int]): big_numbers = [] for number in numbers: if", "- 1`, so the last element is `words[len(words) - 1]`.", "characters. Strings also support some of the new methods we've", "to use `remove` instead of `pop` so we don't have", "is a special 'null' value which can't do anything interesting.", "you're giving the argument to the function - specifically we", "Tutor to see how it visualises the difference. In the", "with a `for loop`. Here's a program that adds up", "list to `[9, 2, 3]`. - **`join`**: Add a list", "retrieve matching characters. \"\"\" @returns_stdout def solution(self, string1, string2): for", "users don't need to know these functions off by heart.", "the `pop` method. Modifying a value directly is called *mutation*", "index that's too high. Can you see why this happens?", "variable `list2` refer to whatever `<expression>` evaluates to'. It doesn't", "In the call `len(things)`, `things` is an ***argument***. Sometimes you", "of numbers and prints a list where each number has", "= [10, 7, 8, 3, 12, 15] for number in", "to put it ____________? 'in the middle' or 'at an", "double += [number * 2] print(double) tests = [ ([3,", "one. You learned how to stop a loop in the", "for number in numbers: double += [number * 2] print(double)", "\"\"\" It's time to learn about a powerful new type", "\" \"`len(string1)` and `len(string2)`. You've already done an exercise like", "also ways to find information without any googling. Try `__program__`", "to know these functions, but it's not easy to learn", "containing only the numbers bigger than 5. For example, given:", "= i print(answer) tests = [ ((['on', 'the', 'way', 'to',", "e.g. if word.lower() == 'yes': \"\"\" class UnderstandingProgramsWithPythonTutor(Page): final_text =", "'the', 'way', 'to', 'the', 'store'], 'the'), \"1\\n4\"), (([0, 1, 2,", "`True`. But then there's a new comparison operator: `is`. Here", "try running that program with a list of strings? The", "new string which was immediately discarded. If you want to", "index_exercise(ExerciseStep): \"\"\" Let's get some exercise! Given a list `things`", "be better. This also means that the last index in", "1), True), (([1, 2, 3, 4], 0), False), ] @classmethod", "in the list. `[1, 2, 3, 2, 7, 2, 5].count(2)`", "to learn them all, and there's many more. A more", "`things` and a value `to_find`, print the first index of", "some new things. Try them out in the shell. -", "link between the variables. If you assign a new value", "lists. Suppose we have a list `nums = [1, 2,", "1, 5, 9, 2, 6, 5], [6, 2, 8, 2,", "@returns_stdout def solution(self, things, thing_to_find): found = False for thing", "seen that `len` and subscripting work with strings, a bit", "i in range(len(things)): if to_find == things[i]: answer = i", "one list*, and the two variables `list1` and `list2` both", "4, 1, 5, 9] total = 0 for number in", "class introducing_subscripting(VerbatimStep): \"\"\" Looping is great, but often you just", "it to be a little more interactive, # but users", "is list2) list1.append(4) print(list1) print(list2) class same_list(VerbatimStep): \"\"\" This program", "List from main.exercises import generate_list, generate_string from main.text import ExerciseStep,", "y e and for: string1 = \"Hello\" string2 = \"Elizabeth\"", "3]) length = len(things) class methods_of_str(VerbatimStep): \"\"\" A ***method*** is", "probably similar. It's fine, but it's a bit inefficient. That's", "`sorted(nums)` returns `[10, 28, 59, 64, 81, 99]`. - **`pop`**:", "some of the new methods we've learned, not just for", "4, 1, 5, 9, 2, 6, 5] it would print:", "we have a list `nums = [1, 2, 3]`. You", "example, for things = ['on', 'the', 'way', 'to', 'the', 'store']", "the list changes those are no longer the positions we", "lot in common. For example, you can add two lists", "'list'] it should print: Thisisalist \"\"\" hints = \"\"\" This", "in common. For example, you can add two lists to", "= [1, 2] + [3, 4] print(numbers) new_numbers = []", "`list1 is list2` is `False`. That means that regardless of", "to, you have to assign a new value to the", "in a subscript - `==` Since you're looking for the", "we want to put it ____________? 'in the middle' or", "value that `word` refers to, you have to assign a", "we want. For example in the first iteration `i` is", "if you forgot their names: - `append` - python add", "\"Goodbye\" string2 = \"World\" output: G W o o o", "for number in numbers: if number <= 10: numbers.remove(number) print(numbers)", "is that `append` is a method of lists. But you", "- `index` - python get position of element - python", "often you just want to retrieve a single element from", "things, to_find): answer = None for i in range(len(things)): if", "exercise like that.\", \"Once you've sorted out `for i in", "TODO enforce not using += @returns_stdout def solution(self, numbers: List[int]):", "= \"\"\" You will need a loop. You will need", "] # TODO catch user writing string1 < string2 @returns_stdout", "a problem with lists and you need to go back", "number = numbers[i] if number <= 10: numbers.pop(i) print(numbers) (remember", "a copy: numbers = [10, 7, 8, 3, 12, 15]", "in things: if thing == thing_to_find: found = True break", "similar to the list of numbers from 0 to `n", "find! Let's do one more. If you have a list:", "in list' \"\"\" program = \"max([21, 55, 4, 91, 62,", "5] Call the right function/method in the shell to do", "a list directly, like above: 1. Write some square brackets:", "`print` and `len` are ***functions***. See for yourself: __program_indented__ \"\"\"", "elements in list - python how many characters in string", "number in all_numbers: if number <= 5: small_numbers.append(number) else: big_numbers.append(number)", "it manually. - You're still confused about lists after this", "`word.append`, without even a call. \"\"\" class FunctionsAndMethodsForLists(Page): # TODO", "just different ways of printing the same list. I recommend", "to retrieve matching characters. \"\"\" @returns_stdout def solution(self, string1, string2):", "placeholder that represents the lack of a real useful value.", "isn't modified, instead `word.upper()` returned a new string which was", "len(string2): char2 = string2[i] else: char2 = ' ' print(char1", "generate_list(str) to_find = generate_string() things += [to_find] * random.randint(1, 3)", "important skill is being able to look things up. For", "if the value doesn't exist. Equivalent to `nums.pop(nums.index(10))`. - **`count`**:", "in different ways depending on whether `string1` or `string2` is", "want a loop iteration for every character in the longer", "different ways of printing the same list. I recommend running", "of things you're familiar with. We create two variables which", "a variable: __program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment,PyUnusedLocal,PyTypeChecker def program(self): things", "a visualisation from [pythontutor.com](http://pythontutor.com). There you can navigate through the", "10: numbers.remove(number) print(numbers) But it turns out this does the", "list - python add item at end of list -", "which you can ignore for now - scroll to the", "learn about a powerful new type of value called lists.", "above, lists are *iterable*, meaning you can iterate over them", "were not pointless, as you've now learned valuable fundamental skills.", "or *indexing*, and the position is called the *index*. You've", "case, we've already done a similar thing in an exercise:", "multiply numbers using `*`. This program is structurally very similar", "which can be mutated are *mutable*, while those that can't", "the numbers left one position, so now 7 is in", "the last element is `words[len(words) - 1]`. Try these for", "class list_insert(Step): \"\"\" Good find! Let's do one more. If", "the index in a subscript - `==` Since you're looking", "by `word` isn't modified, instead `word.upper()` returned a new string", "If you want to change the value that `word` refers", "[] new_numbers += numbers new_numbers += [5] print(new_numbers) With that", "them vertically side by side, with a space between each", "loop. \"\"\" hints = \"\"\" Use the words 'python' and", "False]) things = generate_list(int) if contained: thing_to_find = random.choice(things) else:", "in range(len(things)): if to_find == things[i]: print(i) tests = [", "example, given: things = ['This', 'is', 'a', 'list'] thing_to_find =", "program behave like the first version again. If you come", "Perfect! It can also be useful to Google things like", "big.\", \"You will need two `if` statements, one for each", "e t h \"\"\"), } @classmethod def generate_inputs(cls): length1 =", "\"\"\" Nice! By the way, indexing and `len()` also work", "the argument's attributes, which are mostly methods. Many will start", "at index `i`) As it runs, it clearly skips even", "index of the list is `len(words) - 1`, so the", "== list2) print(list1 is list2) list1.append(4) print(list1) print(list2) final_text =", "to the new list. Use an `if` statement. Use a", "10]), ] final_text = \"\"\" Fantastic! We're making great progress.", "find information without any googling. Try `__program__` in the shell.", "experiment with indexing and `len()` with strings in the shell?", "both strings. You will need to pass the same index", "string2=generate_string(length), ) class zip_longest_exercise(ExerciseStep): \"\"\" Incredible! Your solution probably looks", "if the strings have different lengths. In fact, it goes", "is `True`, because *there is only one list*, and the", "`sum` - python add list of numbers - python total", "5] it would print: [9, 6] \"\"\" hints = \"\"\"", "things up. For example, here are some typical ways you", "strings? The problem is that 0. You can't add 0", "your program should print `1`. You can assume that `to_find`", "TODO this is quite the information dump and I'd like", "if: - Googling a specific method has failed so you", "`break` statement, like so: for thing in things: if thing", "at the beginning. You can stop any loop using a", "indices are: [0, 1, 2, ..., len(words) - 2, len(words)", "to index both strings. You will need to pass the", "\"\"\" program = \"nums.insert(2, 9)\" def check(self): return search_ast( self.stmt,", "\"a few additional ideas and pieces.\", dedent(\"\"\" In particular, it", "write a program which prints a list containing only the", "list - `len` - python size of list - python", "pieces.\", dedent(\"\"\" In particular, it should still contain something like:", "can copy a list with the `copy` method: list2 =", "indices under the hood. The lesson here is to ***never", "value called lists. Here's an example: __program_indented__ \"\"\" def program(self):", "exception is the `pop` method. Modifying a value directly is", "Here's another example of making a list: __program_indented__ \"\"\" def", "the word ***parameter***, which means basically the same thing as", "instead. That means that this is a useless statement on", "recognise some of these from your exercises. I assure you", "2, 3]`. You can use: - **`append`**: Add an element", "will be unaffected and will still point to the original", "len(words) - 1] There's a handy built in function to", "return dict( string1=generate_string(length), string2=generate_string(length), ) class zip_longest_exercise(ExerciseStep): \"\"\" Incredible! Your", "among strings to 0? A blank initial value? \"\"\" @returns_stdout", "that once you set the variable to `True`, it should", "4, 5] You could write `nums.append(9)` and `nums` would change", "refer to whatever `<expression>` evaluates to'. It doesn't make a", "use of `.` - the error actually comes just from", "= random.choice([ min(things) - 1, max(things) + 1, ]) return", "list: nums = [1, 2, 3, 4, 5] You could", "comparison operator to test if a number is big enough", "nums = [1, 2, 3, 4, 5] You could write", "is 3. What happens if you try getting an index", "place (`append`, `insert`, `remove`) merely return `None`, while the remaining", "myths about Python names and values](https://nedbatchelder.com/text/names.html). \"\"\" class ModifyingWhileIterating(Page): final_text", "of equal length, e.g: string1 = \"Hello\" string2 = \"World\"", "it's actually more common to write: some_list.append(element) There isn't really", "you print just the first line, which has the first", "an `if` statement. You will need a comparison operator. Specifically", "element at the beginning. You can stop any loop using", "the loop once you find one. You learned how to", "`range(n)` is similar to the list `[0, 1, 2, ...,", "need `range`. You will need `len`. You will need `+`.", "e.g. `''.join(['apples', 'oranges', 'bananas'])` returns `'applesorangesbananas'`. - **`sum`**: Add a", "visualisation from [pythontutor.com](http://pythontutor.com). There you can navigate through the program", "a single element from the list at a known position.", "element by element in a for loop. Start with an", "statement. You will need a comparison operator. Specifically `==`. You", "without any googling. Try `__program__` in the shell. \"\"\" program", "quite straightforward and mostly consists of things you're familiar with.", "doesn't make a copy of that value, which is how", "trouble understanding this stuff, read the essay [Facts and myths", "search_ast( self.stmt, ast.Call(func=ast.Attribute(attr='insert'), args=[ast.Constant(value=2), ast.Constant(value=9)]), ) class dir_list(VerbatimStep): \"\"\" Perfect!", "Exercise: write a program which takes a list and a", "def program(self): f = 'a string' print(callable(f)) f() class print_returns_none(VerbatimStep):", "and will still point to the original list. Basically, an", "[] for number in numbers: if number > 10: big_numbers.append(number)", "class introducing_len_and_range(VerbatimStep): \"\"\" There you go. `words[4]` and beyond don't", "+ [4, 5]` is `[1, 2, 3, 4, 5]`. Here's", "is in position 0. But then in the next iteration", "\" \"essential elements of the previous solution, \" \"but it's", "o d \"\"\"), (\"Having\", \"ablast\"): dedent(\"\"\"\\ H a a b", "something like this: for i in range(len(string1)): char1 = string1[i]", "very similar to the previous exercise. The difference is that", "@classmethod def generate_inputs(cls): length = random.randrange(5, 11) return dict( string1=generate_string(length),", "only the value. It doesn't know about other variables. You", "def program(self): list1 = [1, 2, 3] list2 = list1", "returns a list of the argument's attributes, which are mostly", "or `NoneType`, it often means you assigned the wrong thing", "final_text = \"\"\" Magnificent! Take a break, you've earned it!", "come across this kind of problem and you're still having", "2, 5].count(2)` is 3. You've already seen that `len` and", "list1.copy() This will make the program behave like the first", "for i in range(len(things)): if to_find == things[i]: print(i) tests", "spaces. For example, for: string1 = \"Goodbye\" string2 = \"World\"", "longest string>)`\", \"In other words you need to find the", "`'the' in 'feed the dog and the cat'` is `True`", "then in the next iteration `i` is 1, and `numbers[i]`", "'` when `string1[i]` is not valid.\", ] # TODO catch", "49]`? 'biggest' or 'largest' 'python biggest value in list' \"\"\"", "4), (([0, 1, 2, 3, 4, 5, 6, 6], 6),", "equal: `list1 == list2` is `True`. But then there's a", "useless instead: __program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment def program(self): things", "Now the list being modified and the list being itererated", "print them vertically side by side, with a space between", "of a real useful value. Functions that don't want to", "of lists. But you can't use `.upper` on a list", "word. For example, given words = ['This', 'is', 'a', 'list']", "= \"Getting Elements at a Position\" class introducing_subscripting(VerbatimStep): \"\"\" Looping", "essay [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html). \"\"\"", "characters in string - `join` - python combine list of", "assign a new value to *either* of the variables, e.g.", "2, 3, 2, 7, 2, 5].count(2)` is 3. You've already", "got skipped. We could try writing the program to use", "in a larger expression, e.g. if word.lower() == 'yes': \"\"\"", "separate them. Here's another example of making a list: __program_indented__", "True print(found) tests = [ ((['This', 'is', 'a', 'list'], 'is'),", "longer. Your next challenge is to fix this problem by", "char2) \"\"\"), \"What should go inside `range()`? Neither `len(string1)` nor", "a string because numbers and strings are incompatible. Is there", "has no elements. Check for yourself: numbers = [1, 2]", "- 1] There's a handy built in function to give", "a program which takes a list and a value and", "list. `list1.append(4)` appends to the one list and the result", "make a copy of that value, which is how both", "\"The solution has the same overall structure and \" \"essential", "variable will be unaffected and will still point to the", "len(things) printed = print(length) print(printed) class len_of_none(VerbatimStep): \"\"\" `None` is", "objects, even if they start out with equal contents. Similarly,", "big_numbers = [] for number in numbers: if number >", "a value in a list. `[7, 8, 9, 8].index(8)` is", "to add. \"\"\" # TODO enforce not using += @returns_stdout", "the slider left or right. You can also see the", "print(length) print(printed) class len_of_none(VerbatimStep): \"\"\" `None` is a special 'null'", "over are separate objects, even if they start out with", "*immutable*. Strings are immutable - they don't have any methods", "1, max(things) + 1, ]) return dict( things=things, thing_to_find=thing_to_find, )", "([0, 2, 4, 6, 8, 10], [6, 8, 10]), ]", "it tries to. I recommend running it with Python Tutor.", "3. - **`+`**: Concatenates lists. `nums + [4, 5]` is", "\"\"\" It's time to learn some technical details that are", "By the way, you can get the number of elements", "the list you should set that variable to `True`. Once", "like \"python list tutorial\", e.g. if: - Googling a specific", "List[int]): double = [] for number in numbers: double +=", "`range(n)` is an object similar to the list of numbers", "things you're familiar with. We create two variables which refer", "[to_find] * random.randint(1, 3) random.shuffle(things) return dict( things=things, to_find=to_find, )", "in a for loop. Start with an empty list. You", "the strings have different lengths. In fact, it goes wrong", "indexing and `len()` with strings in the shell? Forget loops", "done building up strings character by character. The solution is", "8, 3, 12, 15] for number in numbers: if number", "need an `if` statement. You will need a comparison operator.", "can use snoop to see the difference. \"\"\" class GettingElementsAtPosition(Page):", "example, if you were looking for the function `sum`, you", "side by side, with a space between each character: H", "times the argument appears in the list. `[1, 2, 3,", "solution probably looks something like this: for i in range(len(string1)):", "even subscript assignment. You simply can't change a string -", "range(len(string1)): char1 = string1[i] char2 = string2[i] print(char1 + '", "1), (([0, 1, 2, 3, 4, 5, 6, 6], 6),", "element at a given index. `nums.pop(3)` removes `nums[3]` (`81`) from", "still having trouble understanding this stuff, read the essay [Facts", "use: - `if` - the index in a subscript -", "and `number` is 10, which gets removed. This shifts the", "a string: __program_indented__ \"\"\" # noinspection PyUnresolvedReferences def program(self): word", "two `if` statements, one for each string.\", \"You will need", "a separator string *between* each word. For example, given words", "@classmethod def generate_inputs(cls): contained = random.choice([True, False]) things = generate_list(int)", "thing to a variable: __program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment,PyUnusedLocal,PyTypeChecker def", "don't want an empty list, write some expressions inside to", "'a', 'list'] separator = ' - ' it would output:", "\"\"\"), } @classmethod def generate_inputs(cls): length = random.randrange(5, 11) return", "- **`append`**: Add an element to the end of the", "Optional bonus challenge: extend the program to insert a separator", "own: word.upper() The string referred to by `word` isn't modified,", "is called *mutation* - types of values which can be", "sometimes be too big \" \"to be a valid index", "will need a loop over `range(len(things))`. To check if an", "2, 3] list2 = list1 print(list1) print(list2) print(list1 == list2)", "that `len` ***returned*** 3. All calls have to return something...even", "= [1, 2, 3] length = len(things) printed = print(length)", "99, 10, 81, 59, 64]` - **`sorted`**: Takes an iterable", "a single element to the end of a list, instead", "[] big_numbers = [] for number in all_numbers: if number", "them. Here's another example of making a list: __program_indented__ \"\"\"", "' it would output: This - is - a -", "and so on. You will need a `for` loop. You", "*receives* the argument. `len(things)` will evaluate to a number such", "an error if the value doesn't exist. Equivalent to `nums.pop(nums.index(10))`.", "hood. The lesson here is to ***never modify something while", "is too big.\", \"You will need two `if` statements, one", "eternal link between the variables. If you assign a new", "numbers: List[int]): double = [] for number in numbers: double", "above functions if you forgot their names: - `append` -", "string.\", \"That means you need `range(<length of the longest string>)`\",", "character of each string, and so on. You will need", "still two separate, distinct, individual lists. As a result, when", "The operation is called *subscripting* or *indexing*, and the position", "`<expression>`, only the value. It doesn't know about other variables.", "for `string1` is `len(string1) - 1`. \" \"`len(string)` is too", "which gets removed. This shifts the rest of the numbers", "b e t h \"\"\"), } @classmethod def generate_inputs(cls): length1", "to find it manually. - You're still confused about lists", "9]`, the other variable will be unaffected and will still", "they are equal: `list1 == list2` is `True`. But then", "looks something like this: found = False for thing in", "value. For example, given the list `[21, 55, 4, 91,", "Instead of putting the value at the beginning or end,", "your foundations. There are also ways to find information without", "you've found the element, you can't unfind it. That means", "at all possible indices, you will need a loop over", "running it with Python Tutor. numbers = [10, 7, 8,", "'oranges', 'bananas'])` returns `'applesorangesbananas'`. - **`sum`**: Add a list of", "\"\"\" def program(self): numbers = [3, 1, 4, 1, 5,", "a a b v l i a n s g", "will need to look at all the possible indices of", "finds the element at the beginning. You can stop any", "\" \"a few additional ideas and pieces.\", dedent(\"\"\" In particular,", "\"You will need to set e.g. `char1 = ' '`", "\"\"\" @returns_stdout def solution(self, string1, string2): for i in range(len(string1)):", "'a', 'list'], 'other'), False), (([1, 2, 3, 4], 1), True),", "`nums.pop(nums.index(10))`. - **`count`**: Returns the number of times the argument", "loop using a `break` statement, like so: for thing in", "through a numbers and removes the ones smaller than 10.", "to `nums.pop(nums.index(10))`. - **`count`**: Returns the number of times the", "`nums[2]` is 3. - **`+`**: Concatenates lists. `nums + [4,", "is the answer. To look at all possible indices, you", "from main.text import ExerciseStep, MessageStep, Page, Step, VerbatimStep, search_ast from", "'Thequickbrownfoxjumps'), ] class double_numbers(ExerciseStep): \"\"\" Optional bonus challenge: extend the", "*accepts* or *receives* the argument. `len(things)` will evaluate to a", "= [1, 2, 3]` to `list2 = list1` and see", "list where each number has been doubled. For example, given:", "a number is big enough to add. \"\"\" # TODO", "you print at the end. If you find the element", "\"\"\" Use the words 'python' and 'list' in your search", "that program with a list of strings? The problem is", "hints = \"\"\" You will need to look at all", "to be better. This also means that the last index", "l r l l o d \"\"\" hints = \"\"\"", "the shell. - **`subscript assignment`**: Set a value at an", "\"\"\" hints = \"\"\" Remember that you can multiply numbers", "list. But as we've learned before, `list2` doesn't remember `<expression>`,", "generate_inputs(cls): things = generate_list(str) to_find = generate_string() things += [to_find]", "and I'd like it to be a little more interactive,", "def generate_inputs(cls): length1 = random.randrange(5, 11) length2 = random.randrange(12, 20)", "length2: length = length1 else: length = length2 for i", "to the end of the list. `nums.append(4)` changes the list", "list at a known position. Here's how: __program_indented__ \"\"\" def", "bigger than 5. For example, given: numbers = [3, 1,", "To look at all possible indices, you will need a", "8, 3, 12, 15] for i in range(len(numbers)): number =", "Let's review how to work with lists. Suppose we have", "It doesn't know about other variables. You can copy a", "return a useful value. So it returns something useless instead:", "'the'), 4), (([0, 1, 2, 3, 4, 5, 6, 6],", "It seems weird, but that's how most programming languages do", "a common placeholder that represents the lack of a real", "\"\"\" def program(self): list1 = [1, 2, 3] list2 =", "5, 9] But suppose you don't want the 9 to", "this skill now. Find a function/method that returns the value", "why this happens? The index variable `i` runs through the", "things += [to_find] * random.randint(1, 3) random.shuffle(things) return dict( things=things,", "- 1]`. Try these for yourself. So in general, the", "word in words: print(word) class can_contain_anything(VerbatimStep): \"\"\" A list is", "9] But suppose you don't want the 9 to be", "if it's nothing. For example, `print`'s job is to display", "\"World\" print them vertically side by side, with a space", "print([1, 2, 3]) length = len(things) class methods_of_str(VerbatimStep): \"\"\" A", "\"\"\" This is very similar to the exercises you've done", "Nice! A typical solution looks something like this: found =", "collection/container) of any number of values. The values are often", "to the original list. Basically, an assignment like: list2 =", "but `4 in nums` is `False`. - **`index`**: Returns the", "end up pointing to the same list. But as we've", "add 0 to a string because numbers and strings are", "in a list (commonly called the *length*) using `len(words)`. That", "case we say that `len` ***returned*** 3. All calls have", "a loop. \"\"\" hints = \"\"\" Use the words 'python'", "is not valid.\", ] # TODO catch user writing string1", "number `i` such that `things[i]` is `to_find`. For example, for", "assume that `to_find` appears at least once. \"\"\" hints =", "of list - python number of elements in list -", "tab with a visualisation from [pythontutor.com](http://pythontutor.com). There you can navigate", "and see what difference it makes. \"\"\" program_in_text = False", "list, i.e. the lowest number `i` such that `things[i]` is", "similar thing in an exercise: numbers = [10, 7, 8,", "really a big difference between these, but `.append` will be", "lists have the same elements, so they are equal: `list1", "are many ways to solve this. You can instead just", "a comparison operator to test if a number is big", "to solve this. You can instead just loop over a", "are mostly methods. Many will start with `__` which you", "if to_find == things[i]: print(i) break tests = [ ((['on',", "print(len) print(print) class introducing_callable(VerbatimStep): \"\"\" An expression like `len(things)` or", "will need a `for` loop. You will need indexing (subscripting).", "number has been doubled. For example, given: numbers = [3,", "'store'] to_find = 'the' your program should print `1`. You", "title = \"Terminology: Calling functions and methods\" class print_functions(VerbatimStep): \"\"\"", "f = 'a string' print(callable(f)) f() class print_returns_none(VerbatimStep): \"\"\" In", "index' \"\"\" program = \"nums.insert(2, 9)\" def check(self): return search_ast(", "IntroducingLists(Page): class first_list(VerbatimStep): \"\"\" It's time to learn about a", "exercises. I assure you that those exercises were not pointless,", "with an empty list. You can make a list with", "and 'list' in your search query. In one word, what's", "also support some of the new methods we've learned, not", "the list contains the value. For example, given: things =", "anything return `None` by default. If you see an error", "valid index for `string1` is `len(string1) - 1`. \" \"`len(string)`", "and myths about Python names and values](https://nedbatchelder.com/text/names.html). \"\"\" class ModifyingWhileIterating(Page):", "or end, we want to put it ____________? 'in the", "print: [9, 6] \"\"\" hints = \"\"\" This is very", "copy of that value, which is how both variables can", "to display something on screen, not to return a useful", "list. `[1, 2, 3, 2, 7, 2, 5].count(2)` is 3.", "read the essay [Facts and myths about Python names and", "is in a list. `2 in nums` is `True`, but", "way. numbers = [10, 7, 8, 3, 12, 15] for", "still goes through the indices under the hood. The lesson", "as we've learned before, `list2` doesn't remember `<expression>`, only the", "big before indexing.\", \"Remember, the biggest valid index for `string1`", "in range(len(words)): print(index) print(words[index]) class index_exercise(ExerciseStep): \"\"\" Let's get some", "list - python number of elements in list - python", "up strings character by character. Make a new list, and", "that type using `.`. For example, `upper` and `lower` are", "def program(self): words = ['This', 'is', 'a', 'list'] print(words[0]) print(words[1])", "in the longer string.\", \"That means you need `range(<length of", "value. It doesn't know about other variables. You can copy", "adds up all the numbers in a list: __program_indented__ \"\"\"", "an error. By the way, you can get the number", "[ \"The solution has the same overall structure and \"", "first_list(VerbatimStep): \"\"\" It's time to learn about a powerful new", "i in range(length): if i < len(string1): char1 = string1[i]", "the list of numbers from 0 to `n - 1`.", "`word` refers to, you have to assign a new value", "Use a comparison operator to test if a number is", "'brown', 'fox', 'jumps'], 'Thequickbrownfoxjumps'), ] class double_numbers(ExerciseStep): \"\"\" Optional bonus", "hints = \"\"\" Use the words 'python' and 'list' in", "end of the list and you'll see some familiar methods.", "*elements*. They can be anything: numbers, strings, booleans, even lists!", "is 6. - **`in`**: A comparison operator that checks if", "Google the above functions if you forgot their names: -", "of strings as an argument. `'--'.join(['apples', 'oranges', 'bananas'])` returns `'apples--oranges--bananas'`.", "list which is bigger than any other value. For example,", "thing in things: if thing == thing_to_find: found = True", "= ' ' print(char1 + ' ' + char2) tests", "\"\"\" In general, you can get the element at the", "returns `'apples--oranges--bananas'`. You can also use an empty string if", "will need `range`. You will need `len`. You will need", "an index. `nums[0]` is 1, `nums[1]` is 2, `nums[2]` is", "have to use indices. It even looks nicer this way.", "1`, so the last element is `words[len(words) - 1]`. Try", "string2 = \"Elizabeth\" output: H E e l l i", "need to use: - `if` - the index in a", "***never modify something while you iterate over it***. Keep mutation", "an index' or 'at a particular position' 'python add value", "empty list. You can make a list with one element", "print(list2) class same_list(VerbatimStep): \"\"\" This program is quite straightforward and", "will evaluate to a number such as 3, in which", "print_functions(VerbatimStep): \"\"\" It's time to expand your vocabulary some more.", "'feed the dog and the cat'` is `True` - `'feed", "i print(answer) tests = [ ((['on', 'the', 'way', 'to', 'the',", "+ ' ' + char2) \"\"\"), \"What should go inside", "larger expression, e.g. if word.lower() == 'yes': \"\"\" class UnderstandingProgramsWithPythonTutor(Page):", "Neither `len(string1)` nor `len(string2)` is good enough.\", \"You want a", "in nums` is `False`. - **`index`**: Returns the first index", "<= 5: small_numbers.append(number) else: big_numbers.append(number) print(small_numbers) print(big_numbers) The button will", "manually with a loop. \"\"\" hints = \"\"\" Use the", "looping separate. The good news is that there are many", "you learned about lists and you need a reminder. -", "zip_longest_exercise(ExerciseStep): \"\"\" Incredible! Your solution probably looks something like this:", "**`remove`**: Removes the first occurrence of the given element. `nums.remove(10)`", "should write the answer in the shell as a single", "= string2[i] else: char2 = ' ' print(char1 + '", "you go. `words[4]` and beyond don't exist, so trying that", "noinspection PyCallingNonCallable def program(self): f = 'a string' print(callable(f)) f()", "two strings? In the second line you want to print", "class introducing_callable(VerbatimStep): \"\"\" An expression like `len(things)` or `print(things)` is", "`else`. There is no reason to ever set the variable", "python size of list - python number of elements in", "\"\"\" @returns_stdout def solution(self, numbers: List[int]): double = [] for", "55, 4, 91, 62, 49])`. Don't solve this manually with", "\"\"\" class EqualsVsIs(Page): title = \"`==` vs `is`\" class two_separate_lists(VerbatimStep):", "of printing the same list. I recommend running both versions", "numbers using `*`. This program is structurally very similar to", "- **`range`**: `range(n)` is an object similar to the list", "' ' print(char1 + ' ' + char2) tests =", "\"\"\" def program(self): words = ['This', 'is', 'a', 'list'] for", "a *sequence* (an ordered collection/container) of any number of values.", "= True print(found) Your solution is probably similar. It's fine,", "solution has the same overall structure and \" \"essential elements", "2, 6, 5], [9, 6]), ([0, 2, 4, 6, 8,", "I recommend running it with Python Tutor. numbers = [10,", "list. `2 in nums` is `True`, but `4 in nums`", "list contains 5, but there's no similarly easy way to", "or right. You can also see the values of variables", "Add a list of strings with a separator in between.", "like that.\", \"Once you've sorted out `for i in range(...)`,", "isn't really a big difference between these, but `.append` will", "middle recently. You need to use `break`. \"\"\" class all_indices(MessageStep,", "all possible indices, you will need a loop over `range(len(things))`.", "strings and use those instead. That means that this is", "and a value `to_find`, print the first index of `to_find`", "9` changes the list to `[9, 2, 3]`. - **`join`**:", "two variables both have arrows pointing to a single list", "def program(self): print(len) print(print) class introducing_callable(VerbatimStep): \"\"\" An expression like", "the list at a known position. Here's how: __program_indented__ \"\"\"", "it runs, it clearly skips even looking at 7 or", "is `words[len(words) - 1]`. Try these for yourself. So in", "prints the *last* index, not the first one. \"\"\" @returns_stdout", "that can't are *immutable*. Strings are immutable - they don't", "\"\"\" This is very similar to the previous exercise. The", "separator) which takes an iterable of strings as an argument.", "4, 1, 5, 9, 2, 6, 5], [9, 6]), ([0,", "ExerciseStep): \"\"\" You're almost there! However, this prints all the", "5, 9, 2, 6, 5], [6, 2, 8, 2, 10,", "variables `list1` and `list2` both refer to that same list.", "it should still contain something like: for i in range(...):", "you an error. By the way, you can get the", "- 2, n - 1]`. This gives us an alternative", "the rest of the numbers left one position, so now", "an index that's too high. Can you see why this", "+= [element] it's actually more common to write: some_list.append(element) There", "and `len()` also work on strings. Try them out in", "use those instead. That means that this is a useless", "in between - `sum` - python add list of numbers", "\"Python Tutor\" button. Here's some example code if you want:", "For example, given: words = ['This', 'is', 'a', 'list'] it", "often means you assigned the wrong thing to a variable:", "textwrap import dedent from typing import List from main.exercises import", "like it to be a little more interactive, # but", "clearly skips even looking at 7 or 3 and doesn't", "of `things` and check which one is the answer. To", "be the elements. 3. Put commas (`,`) between elements to", "string which was immediately discarded. If you want to change", "list_insert(Step): \"\"\" Good find! Let's do one more. If you", "class same_list(VerbatimStep): \"\"\" This program is quite straightforward and mostly", "'bananas'])` returns `'apples--oranges--bananas'`. You can also use an empty string", "two variables which refer to lists. The lists have the", "3, 4, 5] Call the right function/method in the shell", "of the two strings? In the second line you want", "} @classmethod def generate_inputs(cls): length1 = random.randrange(5, 11) length2 =", "a copy of that value, which is how both variables", "to combine them together into a new list. You can", "words = ['This', 'is', 'a', 'list'] separator = ' -", "loop. You will need indexing (subscripting). You will need `range`.", "returns an element at a given index. `nums.pop(3)` removes `nums[3]`", "two lists being equal, they are still two separate, distinct,", ") class list_insert(Step): \"\"\" Good find! Let's do one more.", "you find one. You learned how to stop a loop", "\"\"\" Magnificent! Take a break, you've earned it! \"\"\" class", "= [3, 1, 4, 1, 5, 9] total = 0", "because it'll loop over the entire list even if it", "`i`) As it runs, it clearly skips even looking at", "You're almost there! However, this prints all the indices, not", "Write some square brackets: `[]` 2. If you don't want", "- `in` - python check if list contains value -", "writing `[x]`. You can add an element to a list", "can't use `.upper` on a list or `.append` on a", "Strings are immutable - they don't have any methods like", "[] for number in all_numbers: if number <= 5: small_numbers.append(number)", "elements. 3. Put commas (`,`) between elements to separate them.", "given words = ['This', 'is', 'a', 'list'] separator = '", "a reminder. - You're struggling to solve a problem with", "double_numbers(ExerciseStep): \"\"\" Optional bonus challenge: extend the program to insert", "char2 = string2[i] print(char1 + ' ' + char2) This", "# flake8: NOQA E501 import ast import random from textwrap", "a list (commonly called the *length*) using `len(words)`. That means", "print(callable(f)) f() class print_returns_none(VerbatimStep): \"\"\" In the call `len(things)`, `things`", "9] total = 0 for number in numbers: total +=", "but it's a bit inefficient. That's because it'll loop over", "the second character of each string, and so on. You", "`[0, 1, 2, ..., n - 2, n - 1]`.", "length = len(things) class methods_of_str(VerbatimStep): \"\"\" A ***method*** is a", "4 to `list1`, only `list1` changes. Now change `list2 =", "the cat'` is `True` - `'feed the dog and the", "some typical ways you might Google the above functions if", "element is `words[len(words) - 1]`. Try these for yourself. So", "You can use: - **`append`**: Add an element to the", "list2) print(list1 is list2) list1.append(4) print(list1) print(list2) class same_list(VerbatimStep): \"\"\"", "`range`: __program_indented__ \"\"\" def program(self): for i in range(10): print(i)", "like `[0, 1, 2]`. - **`subscripting`**: Get a value at", "title = \"Using `break` to end a loop early\" class", "how most programming languages do it, and it's generally agreed", "2, 3]`. - **`join`**: Add a list of strings with", "same elements, so they are equal: `list1 == list2` is", "91, 62, 49])`. Don't solve this manually with a loop.", "programs. Put some code in the editor and then click", "search_ast( self.stmt, ast.Call(func=ast.Name(id='max')), ) class list_insert(Step): \"\"\" Good find! Let's", "a boolean variable that you print at the end. If", "print(list1) print(list2) print(list1 == list2) print(list1 is list2) list1.append(4) print(list1)", "@returns_stdout def solution(self, string1, string2): for i in range(len(string1)): char1", "and then build it up element by element in a", "a given index. `nums.pop(3)` removes `nums[3]` (`81`) from the list", "lists. The lists have the same elements, so they are", "add. \"\"\" # TODO enforce not using += @returns_stdout def", "to 0? A blank initial value? \"\"\" @returns_stdout def solution(self,", "on a list or `.append` on a string: __program_indented__ \"\"\"", "= \"\"\" This is very similar to the previous exercise.", "while those that can't are *immutable*. Strings are immutable -", "python add item at end of list - `len` -", "You've already seen that `len` and subscripting work with strings,", "of the list and you'll see some familiar methods. Here", "Here's how: __program_indented__ \"\"\" def program(self): words = ['This', 'is',", "an object similar to the list of numbers from 0", "all the possible indices of `things` and check which one", "tool to explore programs. Put some code in the editor", "`[1, 2, 3, 4]`. - **`len`**: Returns the number of", "1, 2]`. - **`subscripting`**: Get a value at an index.", "a little more interactive, # but users don't need to", "- **`index`**: Returns the first index of a value in", "An expression like `len(things)` or `print(things)` is a function ***call***", "Returns the number of elements. `len(nums)` is `3`. - **`range`**:", "end it fails when it tries to access an index", "You will need to check if it's too big before", "go inside `range()`? Neither `len(string1)` nor `len(string2)` is good enough.\",", "'a', 'list'] thing_to_find = 'is' it should print `True`, but", "is very similar to the previous exercise. The difference is", "is `[1, 2, 3, 4, 5]`. Here's some new things.", "an exercise: numbers = [10, 7, 8, 3, 12, 15]", "which means basically the same thing as argument. It's a", "that represents the lack of a real useful value. Functions", "Don't solve this manually with a loop. \"\"\" hints =", "i a n s g t \"\"\"), } @classmethod def", "= ' - ' it would output: This - is", "`len(string2)` is good enough.\", \"You want a loop iteration for", "'a', 'list'] print(words[0]) print(words[1]) print(words[2]) print(words[3]) class index_error(Step): \"\"\" In", "a specific method has failed so you want to find", "ast.Call(func=ast.Name(id='max')), ) class list_insert(Step): \"\"\" Good find! Let's do one", "1, 2, 3], [0, 2, 4, 6]), ] class filter_numbers(ExerciseStep):", "i in range(...): ... print(char1 + ' ' + char2)", "UsingBreak(Page): title = \"Using `break` to end a loop early\"", "`word` isn't modified, instead `word.upper()` returned a new string which", "that this is a useless statement on its own: word.upper()", "class ModifyingWhileIterating(Page): final_text = \"\"\" Consider this program. It loops", "for loop. Start with an empty list. You can make", ") class zip_exercise(ExerciseStep): \"\"\" Nice! By the way, indexing and", "['This', 'is', 'a', 'list'] for word in words: print(word) class", "biggest value in list' \"\"\" program = \"max([21, 55, 4,", "solution(self, numbers: List[int]): big_numbers = [] for number in numbers:", "index for `string1` is `len(string1) - 1`. \" \"`len(string)` is", "of a value in a list. `[7, 8, 9, 8].index(8)`", "'Thisisalist'), (['The', 'quick', 'brown', 'fox', 'jumps'], 'Thequickbrownfoxjumps'), ] class double_numbers(ExerciseStep):", "bit like you're giving the argument to the function -", "that the argument `things` is *passed* to `len`, and `len`", "changes. Now change `list2 = [1, 2, 3]` to `list2", "\"\"\" It's time to learn about another tool to explore", "It's a common placeholder that represents the lack of a", "It's been a while since you learned about lists and", "ExerciseStep): \"\"\" You're almost there! However, this prints the *last*", "['on', 'the', 'way', 'to', 'the', 'store'] to_find = 'the' your", "Add an element to the end of the list. `nums.append(4)`", "position of element - python get index of value Let's", "shell. Here's another exercise. Given two strings of equal length,", "numbers: if number <= 10: numbers.remove(number) print(numbers) But it turns", "__program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment,PyUnusedLocal,PyTypeChecker def program(self): things = print([1,", "position. Here's how: __program_indented__ \"\"\" def program(self): words = ['This',", "\"dir([])\" final_text = \"\"\" `dir()` returns a list of the", "***returned*** 3. All calls have to return something...even if it's", "It can also be useful to Google things like \"python", "This is very similar to the exercises you've done building", "in order. `sorted(nums)` returns `[10, 28, 59, 64, 81, 99]`.", "in range(len(things)): if to_find == things[i]: print(i) break tests =", "return search_ast( self.stmt, ast.Call(func=ast.Attribute(attr='insert'), args=[ast.Constant(value=2), ast.Constant(value=9)]), ) class dir_list(VerbatimStep): \"\"\"", "4, 6]), ] class filter_numbers(ExerciseStep): \"\"\" Great! When you want", "a b v l i a n s g t", "this is quite the information dump and I'd like it", "if number <= 10: numbers.pop(i) print(numbers) (remember that `numbers.pop(i)` removes", "know about other variables. You can copy a list with", "- python add item at end of list - `len`", "words 'python' and 'list' in your search query. In one", "number > 5: big_numbers.append(number) print(big_numbers) tests = [ ([3, 1,", "same thing as argument. It's a bit like you're giving", "new comparison operator: `is`. Here `list1 is list2` is `False`.", "common to write: some_list.append(element) There isn't really a big difference", "from textwrap import dedent from typing import List from main.exercises", "using `.`. For example, `upper` and `lower` are methods of", "positions we want. For example in the first iteration `i`", "or `print`. The fact that this is possible means that", "`string1[i]` is not valid.\", ] # TODO catch user writing", "`len(words) - 1`, so the last element is `words[len(words) -", "values, called `range`: __program_indented__ \"\"\" def program(self): for i in", "the two lists being equal, they are still two separate,", "program(self): x = 1 things = ['Hello', x, x +", "set that variable to `True`. Once you've found the element,", "off by heart. class sum_list(Step): \"\"\" Let's review how to", "the way, indexing and `len()` also work on strings. Try", "is called *subscripting* or *indexing*, and the position is called", "iterable of strings as an argument. `'--'.join(['apples', 'oranges', 'bananas'])` returns", "a list which is bigger than any other value. For", "Start with an empty list. You can make a list", "typical solution looks something like this: found = False for", "9, 2, 6, 5] it would print: [6, 2, 8,", "0, not 1. In programming, counting starts at 0. It", "1, 4, 1, 5, 9, 2, 6, 5], [9, 6]),", "the list `[21, 55, 4, 91, 62, 49]`, it will", "do one more. If you have a list: nums =", "example of making a list: __program_indented__ \"\"\" def program(self): x", "biggest valid index for `string1` is `len(string1) - 1`. \"", "iteration `i` is 0 and `number` is 10, which gets", "good news is that there are many ways to solve", "answer. To look at all possible indices, you will need", "it fails when it tries to access an index that's", "for number in numbers: if number > 5: big_numbers.append(number) print(big_numbers)", "example code if you want: all_numbers = [2, 4, 8,", "`range`. You will need `len`. You will need `+`. You", "to loop over a list: __program_indented__ \"\"\" def program(self): words", "saw above, lists are *iterable*, meaning you can iterate over", "6. - **`in`**: A comparison operator that checks if a", "many ways to solve this. You can instead just loop", "could write `sum([21, 55, 4, 91, 62, 49])`. Don't solve", "***call*** - when you write that, you are ***calling*** the", "the value that `word` refers to, you have to assign", "like you're giving the argument to the function - specifically", "and checks if the list contains the value. For example,", "i.e. the lowest number `i` such that `things[i]` is `to_find`.", "elements. Check for yourself: numbers = [1, 2] + [3,", "5 Note that in most cases, methods which modify a", "`[7, 8, 9, 8].index(8)` is 1. Raises an error if", "means that the last index in this list of 4", "**`join`**: Add a list of strings with a separator in", "loops through a numbers and removes the ones smaller than", "list. `[7, 8, 9, 8].index(8)` is 1. Raises an error", "still point to the original list. Basically, an assignment like:", "62, 49]`, it will return `91`. You should write the", "\"World\"): dedent(\"\"\"\\ H W e o l r l l", "type of value called lists. Here's an example: __program_indented__ \"\"\"", "a function/method that returns the value in a list which", "list being modified and the list being itererated over are", "* 2] print(double) tests = [ ([3, 1, 4, 1,", "returns the value in a list which is bigger than", "easy to learn them all, and there's many more. A", "both `print(list1)` and `print(list2)` because both lines are now just", "\"In other words you need to find the biggest of", "__program_indented__ \"\"\" def program(self): print(callable(len)) class not_callable(VerbatimStep): \"\"\" Most things", "enough.\", \"You want a loop iteration for every character in", "yourself: numbers = [1, 2] + [3, 4] print(numbers) new_numbers", "change to: [1, 2, 3, 4, 5, 9] But suppose", "an assignment like: list2 = <expression> means 'make the variable", "example: - `'the' in 'feed the dog and the cat'`", "assure you that those exercises were not pointless, as you've", "the end it fails when it tries to access an", "individual lists. As a result, when you append 4 to", "<= 10: big_numbers.remove(number) print(big_numbers) Or you could build up a", "= 1 things = ['Hello', x, x + 3] print(things)", "because both lines are now just different ways of printing", "mutation and looping separate. The good news is that there", "mostly consists of things you're familiar with. We create two", "yourself: __program_indented__ \"\"\" def program(self): print(len) print(print) class introducing_callable(VerbatimStep): \"\"\"", "in range(...)`, `i` will sometimes be too big \" \"to", "\"\"\" def program(self): for i in range(10): print(i) class range_len(VerbatimStep):", "6, 5] it would print: [6, 2, 8, 2, 10,", "pointing to the same list. But as we've learned before,", "[10, 7, 8, 3, 12, 15] for number in numbers:", "find the element in the list you should set that", "z o a b e t h \"\"\"), } @classmethod", "means that this is a useless statement on its own:", "o l r l l o d \"\"\" hints =", "does the same thing, for the same reason. Iterating over", "7] small_numbers = [] big_numbers = [] for number in", "1. Write some square brackets: `[]` 2. If you don't", "__program_indented__ \"\"\" def program(self): for i in range(10): print(i) class", "generate_inputs(cls): contained = random.choice([True, False]) things = generate_list(int) if contained:", "prints a list containing only the numbers bigger than 5.", "print(answer) tests = [ ((['on', 'the', 'way', 'to', 'the', 'store'],", "step with the \"Prev\" or \"Next\" buttons, or drag the", "You will need a comparison operator. Specifically `==`. You need", "[1, 2, 3] length = len(things) printed = print(length) print(printed)", "{ (\"Hello\", \"World\"): dedent(\"\"\"\\ H W e o l r", "index of value Let's practice this skill now. Find a", "ones smaller than 10. Or at least, it tries to.", "method of lists. But you can't use `.upper` on a", "even looking at 7 or 3 and doesn't remove them,", "It doesn't make a copy of that value, which is", "# noinspection PyNoneFunctionAssignment,PyUnusedLocal,PyTypeChecker def program(self): things = print([1, 2, 3])", "it***. Keep mutation and looping separate. The good news is", "lines are now just different ways of printing the same", "special about `91` in the list `[21, 55, 4, 91,", "solution(self, string1, string2): length1 = len(string1) length2 = len(string2) if", "*passed* to `len`, and `len` *accepts* or *receives* the argument.", "the list. `nums.append(4)` changes the list to `[1, 2, 3,", "d \"\"\"), (\"Having\", \"ablast\"): dedent(\"\"\"\\ H a a b v", "= 'a string' print(callable(f)) f() class print_returns_none(VerbatimStep): \"\"\" In the", "you're familiar with. We create two variables which refer to", "to work with lists. Suppose we have a list `nums", "with a visualisation from [pythontutor.com](http://pythontutor.com). There you can navigate through", "a string - you can only create new strings and", "are lists of characters. Strings also support some of the", "big \" \"to be a valid index for both strings.", "the value isn't there. You may recognise some of these", "print(char1 + ' ' + char2) tests = { (\"Hello\",", "index variable `i` runs through the usual values 0, 1,", "the numbers bigger than 5. For example, given: numbers =", "5. For example, given: numbers = [3, 1, 4, 1,", "to expand your vocabulary some more. `print` and `len` are", "\"\"\" In the call `len(things)`, `things` is an ***argument***. Sometimes", "it should never be set to anything else after that.", "add element to list - python add item at end", "every character in the longer string.\", \"That means you need", "should print `1`. You can assume that `to_find` appears at", "random.choice(things) else: thing_to_find = random.choice([ min(things) - 1, max(things) +", "10], [6, 8, 10]), ] final_text = \"\"\" Fantastic! We're", "a few more useful functions/methods. Suppose `nums = [28, 99,", "can iterate over them with a `for loop`. Here's a", "earned it! \"\"\" class CallingFunctionsTerminology(Page): title = \"Terminology: Calling functions", "\"\"\" Looping is great, but often you just want to", "done an exercise like that.\", \"Once you've sorted out `for", "strings. You will need to pass the same index to", "its own: word.upper() The string referred to by `word` isn't", "Now use `.append` to write a program which prints a", "which are mostly methods. Many will start with `__` which", "'is' it should print `True`, but for thing_to_find = 'other'", "been a while since you learned about lists and you", "end, we want to put it ____________? 'in the middle'", "final_text = \"\"\" It's time to learn about another tool", "This doesn't work so well if the strings have different", "\"\"\" def program(self): print(len) print(print) class introducing_callable(VerbatimStep): \"\"\" An expression", "`if` statement. You will need a comparison operator. Specifically `==`.", "those instead. That means that this is a useless statement", "or \"Next\" buttons, or drag the slider left or right.", "Googling a specific method has failed so you want to", "the biggest valid index for `string1` is `len(string1) - 1`.", "look at all the possible indices of `things` and check", "it finds the element. You can use snoop to see", "that, you are ***calling*** the function `len` or `print`. The", "line, which has the first character of each of the", "of strings with string in between - `sum` - python", "found = False for thing in things: if thing ==", "of strings, which are called with e.g. `word.upper()`: __program_indented__ \"\"\"", "copy a list with the `copy` method: list2 = list1.copy()", "print(big_numbers) tests = [ ([3, 1, 4, 1, 5, 9,", "some code in the editor and then click the new", "empty list, write some expressions inside to be the elements.", "strings_sum(ExerciseStep): \"\"\" Now modify the program so that it can", "Or you could build up a new list from scratch.", "- the error actually comes just from `word.append`, without even", "+= numbers new_numbers += [5] print(new_numbers) With that knowledge, write", "Without an argument, i.e. just `nums.pop()`, it will remove and", "5. It's useful to know these functions, but it's not", "the value in a list which is bigger than any", "if thing == thing_to_find: found = True print(found) tests =", "'python add value at index' \"\"\" program = \"nums.insert(2, 9)\"", "class numbers_sum(VerbatimStep): \"\"\" As you saw above, lists are *iterable*,", "same index to both strings each time to retrieve matching", "instead `word.upper()` returned a new string which was immediately discarded.", "= [2, 4, 8, 1, 9, 7] small_numbers = []", "In particular, it should still contain something like: for i", "random.randrange(12, 20) if random.choice([True, False]): length1, length2 = length2, length1", "= ' '` when `string1[i]` is not valid.\", ] #", "elements, so they are equal: `list1 == list2` is `True`.", "useful to Google things like \"python list tutorial\", e.g. if:", "end a loop early\" class list_contains_exercise(ExerciseStep): \"\"\" Exercise: write a", "vs `is`\" class two_separate_lists(VerbatimStep): \"\"\" It's time to learn some", "= 9` changes the list to `[9, 2, 3]`. -", "new value to *either* of the variables, e.g. `list1 =", "of these from your exercises. I assure you that those", "add item at end of list - `len` - python", "a function which belongs to a type, and can be", "one list and the result can be seen in both", "little more interactive, # but users don't need to know", "loop. Start with an empty list. You can make a", "to go between the second and third elements: [1, 2,", "(`,`) between elements to separate them. Here's another example of", "for word in words: total += word print(total) tests =", "6, 5] it would print: [9, 6] \"\"\" hints =", "PyNoneFunctionAssignment,PyUnusedLocal,PyTypeChecker def program(self): things = print([1, 2, 3]) length =", "length = random.randrange(5, 11) return dict( string1=generate_string(length), string2=generate_string(length), ) class", "python combine list of strings with separator - python add", "values \" \"`len(string1)` and `len(string2)`. You've already done an exercise", "program. It loops through a numbers and removes the ones", "`i` such that `things[i]` is `to_find`. For example, for things", "together list of strings with string in between - `sum`", "would output: This - is - a - list Lists", "it's a bit inefficient. That's because it'll loop over the", "things: if thing == thing_to_find: found = True print(found) Your", "'a', 'list'] for index in range(len(words)): print(index) print(words[index]) class index_exercise(ExerciseStep):", "when `string1[i]` is not valid.\", ] # TODO catch user", "it makes. \"\"\" program_in_text = False def program(self): list1 =", "[10, 7, 8, 3, 12, 15] big_numbers = [] for", "a list of numbers. `sum(nums)` is 6. - **`in`**: A", "`print(list1)` and `print(list2)` because both lines are now just different", "\"but it's significantly longer and will require \" \"a few", "(\"Goodbye\", \"World\"): dedent(\"\"\"\\ G W o o o r d", "as *elements*. They can be anything: numbers, strings, booleans, even", "the programs you've written to build up strings character by", "things = generate_list(str) to_find = generate_string() things += [to_find] *", "are methods of strings, which are called with e.g. `word.upper()`:", "belongs to a type, and can be called on all", "greater than that? \"\"\" program = \"words[4]\" def check(self): return", "`[21, 55, 4, 91, 62, 49]`? 'biggest' or 'largest' 'python", "the same overall structure and \" \"essential elements of the", "char2) This doesn't work so well if the strings have", "big_numbers.append(number) print(small_numbers) print(big_numbers) The button will open a new tab", "Try them out in the shell. Here's another exercise. Given", "`things[i]` is `to_find`. For example, for things = ['on', 'the',", "4, 5] Call the right function/method in the shell to", "4], 0), False), ] @classmethod def generate_inputs(cls): contained = random.choice([True,", "not using += @returns_stdout def solution(self, numbers: List[int]): big_numbers =", "\"Remember, the biggest valid index for `string1` is `len(string1) -", "self.result class introducing_len_and_range(VerbatimStep): \"\"\" There you go. `words[4]` and beyond", "things = ['Hello', x, x + 3] print(things) class numbers_sum(VerbatimStep):", "= { (\"Hello\", \"World\"): dedent(\"\"\"\\ H W e o l", "to look at all the possible indices of `things` and", "value which can't do anything interesting. It's a common placeholder", "now - scroll to the end of the list and", "common placeholder that represents the lack of a real useful", "len(string2) if length1 > length2: length = length1 else: length", "([3, 1, 4, 1, 5, 9, 2, 6, 5], [6,", "You can instead just loop over a copy, as in:", "on whether `string1` or `string2` is longer. Your next challenge", "You need to use `break`. \"\"\" class all_indices(MessageStep, ExerciseStep): \"\"\"", "can be mutated are *mutable*, while those that can't are", "4, 12, 10]), ([0, 1, 2, 3], [0, 2, 4,", "was immediately discarded. If you want to change the value", "\"\"\"), (\"Hello\", \"Elizabeth\"): dedent(\"\"\"\\ H E e l l i", "2, 4, 6]), ] class filter_numbers(ExerciseStep): \"\"\" Great! When you", "value. For example, given: things = ['This', 'is', 'a', 'list']", "in the shell? Forget loops for a moment. How would", "char2) tests = { (\"Goodbye\", \"World\"): dedent(\"\"\"\\ G W o", "not_callable(VerbatimStep): \"\"\" Most things are not callable, so trying to", "the list being itererated over are separate objects, even if", "need to index both strings. You will need to pass", "a method of strings (the separator) which takes an iterable", "= False def program(self): list1 = [1, 2, 3] list2", "for i in range(len(things)): if to_find == things[i]: answer =", "not valid.\", ] # TODO catch user writing string1 <", "be unaffected and will still point to the original list.", "But as we've learned before, `list2` doesn't remember `<expression>`, only", "a program that adds up all the numbers in a", "practice this skill now. Find a function/method that returns the", "print(word) class can_contain_anything(VerbatimStep): \"\"\" A list is a *sequence* (an", "by step with the \"Prev\" or \"Next\" buttons, or drag", "the lowest number `i` such that `things[i]` is `to_find`. For", "is `len(string1) - 1`. \" \"`len(string)` is too big.\", \"You", "or 'at a particular position' 'python add value at index'", "Try `__program__` in the shell. \"\"\" program = \"dir([])\" final_text", "\"\"\" @returns_stdout def solution(self, things, to_find): answer = None for", "add two lists to combine them together into a new", "inside `range()`? Neither `len(string1)` nor `len(string2)` is good enough.\", \"You", "that will give you an error. By the way, you", "it would output: This - is - a - list", "index is 0, not 1. In programming, counting starts at", "`string1` or `string2` is longer. Your next challenge is to", "is similar to the list `[0, 1, 2, ..., n", "indices, you will need a loop over `range(len(things))`. To check", "at the end. If you find the element in the", "['This', 'is', 'a', 'list'] for index in range(len(words)): print(index) print(words[index])", "\"ablast\"): dedent(\"\"\"\\ H a a b v l i a", "to insert a separator string *between* each word. For example,", "here are some typical ways you might Google the above", "initial value? \"\"\" @returns_stdout def solution(self, words: List[str]): total =", "to_find = generate_string() things += [to_find] * random.randint(1, 3) random.shuffle(things)", "length1 return dict( string1=generate_string(length1), string2=generate_string(length2), ) final_text = \"\"\" Magnificent!", "print(list1) print(list2) final_text = \"\"\" Now `list1 is list2` is", "You're struggling to solve a problem with lists and you", "starts at 0. It seems weird, but that's how most", "while since you learned about lists and you need a", "the entire list even if it finds the element at", "your search query. In one word, what's special about `91`", "with Python Tutor. numbers = [10, 7, 8, 3, 12,", "be mutated are *mutable*, while those that can't are *immutable*.", "- python add list of numbers - python total of", "`len(words)`. That means that the last valid index of the", "variables on the right. \"\"\" class EqualsVsIs(Page): title = \"`==`", "remove them, and at the end it fails when it", "confused about lists after this course. - It's been a", "this is a useless statement on its own: word.upper() The", "= \"Using `break` to end a loop early\" class list_contains_exercise(ExerciseStep):", "`string2` is longer. Your next challenge is to fix this", "the two strings? In the second line you want to", "15] for i in range(len(numbers)): number = numbers[i] if number", "the exercises you've done building up strings character by character.", "a list: __program_indented__ \"\"\" def program(self): numbers = [3, 1,", "But suppose you don't want the 9 to be at", "3, 12, 15] big_numbers = [] for number in numbers:", "a list `nums = [1, 2, 3]`. You can use:", "= [] for number in all_numbers: if number <= 5:", "print(words[index]) class index_exercise(ExerciseStep): \"\"\" Let's get some exercise! Given a", "elements. `len(nums)` is `3`. - **`range`**: `range(n)` is an object", "way, you can get the number of elements in a", "3. What happens if you try getting an index greater", "comparison operator that checks if a value is in a", "value, which is how both variables can end up pointing", "numbers.remove(number) print(numbers) But it turns out this does the same", "booleans, even lists! They can also be a mixture of", "Raises an error if the value doesn't exist. Equivalent to", "that's too high. Can you see why this happens? The", "or 'largest' 'python biggest value in list' \"\"\" program =", "size of list - python number of elements in list", "will open a new tab with a visualisation from [pythontutor.com](http://pythontutor.com).", "- 1, max(things) + 1, ]) return dict( things=things, thing_to_find=thing_to_find,", "list contains value - python test if list has element", "string2=generate_string(length2), ) final_text = \"\"\" Magnificent! Take a break, you've", "significantly longer and will require \" \"a few additional ideas", "number in numbers: if number <= 10: numbers.remove(number) print(numbers) But", "this case, we've already done a similar thing in an", "that `things[i]` is `to_find`. For example, for things = ['on',", "a list. `2 in nums` is `True`, but `4 in", "\"World\"): dedent(\"\"\"\\ G W o o o r d l", "For example, given: numbers = [3, 1, 4, 1, 5,", "is bigger than any other value. For example, given the", "5, but there's no similarly easy way to check for", "to the programs you've written to build up strings character", "now 7 is in position 0. But then in the", "the end of the list and you'll see some familiar", "dir_list(VerbatimStep): \"\"\" Perfect! It can also be useful to Google", "introducing_len_and_range(VerbatimStep): \"\"\" There you go. `words[4]` and beyond don't exist,", "more interactive, # but users don't need to know these", "which refer to lists. The lists have the same elements,", "looks nicer this way. numbers = [10, 7, 8, 3,", "12, 10]), ([0, 1, 2, 3], [0, 2, 4, 6]),", "title = \"`==` vs `is`\" class two_separate_lists(VerbatimStep): \"\"\" It's time", "3, 4], 1), True), (([1, 2, 3, 4], 0), False),", "that value, which is how both variables can end up", "each of the two strings? In the second line you", "you don't want the 9 to be at the end,", "learned, not just for characters but for any substring. For", "it. That means that once you set the variable to", "length1 = random.randrange(5, 11) length2 = random.randrange(12, 20) if random.choice([True,", "use: - **`append`**: Add an element to the end of", "\"You want a loop iteration for every character in the", "dedent from typing import List from main.exercises import generate_list, generate_string", "is possible means that functions are ***callable***: __program_indented__ \"\"\" def", "in nums` is `True`, but `4 in nums` is `False`.", "a list: __program_indented__ \"\"\" def program(self): words = ['This', 'is',", "over it***. Keep mutation and looping separate. The good news", "words = ['This', 'is', 'a', 'list'] print(words[0]) print(words[1]) print(words[2]) print(words[3])", "at index' \"\"\" program = \"nums.insert(2, 9)\" def check(self): return", "def solution(self, numbers: List[int]): double = [] for number in", "element `x` by just writing `[x]`. You can add an", "will leave `nums` as `[28, 99, 81, 59, 64]`. Raises", "unaffected and will still point to the original list. Basically,", "and return the last element. - **`remove`**: Removes the first", "doesn't remove them, and at the end it fails when", "to basics and strengthen your foundations. There are also ways", "For example, you can use `in` to check if a", "is a *sequence* (an ordered collection/container) of any number of", "* random.randint(1, 3) random.shuffle(things) return dict( things=things, to_find=to_find, ) class", "more common to write: some_list.append(element) There isn't really a big", "checks if the list contains the value. For example, given:", "10, 18, 4, 12, 10]), ([0, 1, 2, 3], [0,", "to_find == things[i]: answer = i print(answer) tests = [", "and check which one is the answer. To look at", "bigger than 5. It's useful to know these functions, but", "things. Try them out in the shell. - **`subscript assignment`**:", "class zip_longest_exercise(ExerciseStep): \"\"\" Incredible! Your solution probably looks something like", "Python names and values](https://nedbatchelder.com/text/names.html). \"\"\" class ModifyingWhileIterating(Page): final_text = \"\"\"", "recommend running it with Python Tutor. numbers = [10, 7,", "to a type, and can be called on all values", "> 5: big_numbers.append(number) print(big_numbers) tests = [ ([3, 1, 4,", "tries to access an index that's too high. Can you", "in the shell as a single small expression. For example,", "object similar to the list of numbers from 0 to", "'way', 'to', 'the', 'store'], 'the'), 4), (([0, 1, 2, 3,", "3, 12, 15] for number in numbers: if number <=", "callable, so trying to call them will give you an", "9, 2, 6, 5], [6, 2, 8, 2, 10, 18,", "it goes wrong in different ways depending on whether `string1`", "iterate over it***. Keep mutation and looping separate. The good", "index' or 'at a particular position' 'python add value at", "example: __program_indented__ \"\"\" def program(self): words = ['This', 'is', 'a',", "useful value without changing the original argument. The only exception", "the right. \"\"\" class EqualsVsIs(Page): title = \"`==` vs `is`\"", "[1, 2] + [3, 4] print(numbers) new_numbers = [] new_numbers", "function - specifically we say that the argument `things` is", "need a comparison operator. Specifically `==`. You need a boolean", "general, the valid indices are: [0, 1, 2, ..., len(words)", "`things` and check which one is the answer. To look", "over the original and modify a copy: numbers = [10,", "9 to be at the end, you want it to", "for i in range(len(numbers)): number = numbers[i] if number <=", "don't have any methods like `append` or even subscript assignment.", "The string referred to by `word` isn't modified, instead `word.upper()`", "'the', 'way', 'to', 'the', 'store'], 'the'), 4), (([0, 1, 2,", "dedent(\"\"\"\\ G W o o o r d l b", "separator, e.g. `''.join(['apples', 'oranges', 'bananas'])` returns `'applesorangesbananas'`. - **`sum`**: Add", "`nums[0]` is 1, `nums[1]` is 2, `nums[2]` is 3. -", "the original list. Basically, an assignment like: list2 = <expression>", "something while you iterate over it***. Keep mutation and looping", "3, 4, 5, 9] But suppose you don't want the", "+ char2) tests = { (\"Hello\", \"World\"): dedent(\"\"\"\\ H W", "strings have different lengths. In fact, it goes wrong in", "it visualises the difference. In the second case, the two", "numbers. In fact, what happens if you try running that", "You may recognise some of these from your exercises. I", "'at a particular position' 'python add value at index' \"\"\"", "the function `sum`, you could write `sum([21, 55, 4, 91,", "But you can't use `.upper` on a list or `.append`", "`break`. \"\"\" class all_indices(MessageStep, ExerciseStep): \"\"\" You're almost there! However,", "that don't want to return anything return `None` by default.", "'is', 'a', 'list'], 'Thisisalist'), (['The', 'quick', 'brown', 'fox', 'jumps'], 'Thequickbrownfoxjumps'),", "`len`, and `len` *accepts* or *receives* the argument. `len(things)` will", "but it's not easy to learn them all, and there's", "out in the shell. Here's another exercise. Given two strings", "those exercises were not pointless, as you've now learned valuable", "list being itererated over are separate objects, even if they", "about Python names and values](https://nedbatchelder.com/text/names.html). \"\"\" class ModifyingWhileIterating(Page): final_text =", "will need indexing (subscripting). You will need `range`. You will", "using `*`. This program is structurally very similar to the", "`'applesorangesbananas'`. - **`sum`**: Add a list of numbers. `sum(nums)` is", "((['on', 'the', 'way', 'to', 'the', 'store'], 'the'), 4), (([0, 1,", "x + 3] print(things) class numbers_sum(VerbatimStep): \"\"\" As you saw", "writing string1 < string2 @returns_stdout def solution(self, string1, string2): length1", "But then there's a new comparison operator: `is`. Here `list1", "numbers: if number <= 10: big_numbers.remove(number) print(big_numbers) Or you could", "can assume that `to_find` appears at least once. \"\"\" hints", "class can_contain_anything(VerbatimStep): \"\"\" A list is a *sequence* (an ordered", "False), (([1, 2, 3, 4], 1), True), (([1, 2, 3,", "right function/method in the shell to do that. \"\"\" hints", "is longer. Your next challenge is to fix this problem", "need a loop. You will need an `if` statement. You", "getting an index greater than that? \"\"\" program = \"words[4]\"", "the difference. In the second case, the two variables both", "values](https://nedbatchelder.com/text/names.html). \"\"\" class ModifyingWhileIterating(Page): final_text = \"\"\" Consider this program.", "7, 8, 3, 12, 15] big_numbers = [] for number", "\"\"\" hints = \"\"\" This is very similar to the", "of putting the value at the beginning or end, we", "it's generally agreed to be better. This also means that", "characters but for any substring. For example: - `'the' in", "example, you can use `in` to check if a list", "if the list contains the value. For example, given: things", "what happens if you try running that program with a", "list: __program_indented__ \"\"\" def program(self): words = ['This', 'is', 'a',", "To check if an index is the answer, you will", "program(self): list1 = [1, 2, 3] list2 = list1 print(list1)", "Take a break, you've earned it! \"\"\" class CallingFunctionsTerminology(Page): title", "len(words) - 2, len(words) - 1] There's a handy built", "`None` is a special 'null' value which can't do anything", "are now just different ways of printing the same list.", "know these functions off by heart. class sum_list(Step): \"\"\" Let's", "already done an exercise like that.\", \"Once you've sorted out", "b d y e \"\"\"), (\"Hello\", \"Elizabeth\"): dedent(\"\"\"\\ H E", "loop over a list: __program_indented__ \"\"\" def program(self): words =", "class CallingFunctionsTerminology(Page): title = \"Terminology: Calling functions and methods\" class", "also be useful to Google things like \"python list tutorial\",", "the valid indices are: [0, 1, 2, ..., len(words) -", "+ ' ' + char2) This doesn't work so well", ") class zip_longest_exercise(ExerciseStep): \"\"\" Incredible! Your solution probably looks something", "program that adds numbers. In fact, what happens if you", "49])\" def check(self): return search_ast( self.stmt, ast.Call(func=ast.Name(id='max')), ) class list_insert(Step):", "and the list being itererated over are separate objects, even", "`len()` also work on strings. Try them out in the", "work on strings. Try them out in the shell. Here's", "cases, methods which modify a list in place (`append`, `insert`,", "loop early\" class list_contains_exercise(ExerciseStep): \"\"\" Exercise: write a program which", "12, 15] big_numbers = [] for number in numbers: if", "tests = [ (['This', 'is', 'a', 'list'], 'Thisisalist'), (['The', 'quick',", "through the program step by step with the \"Prev\" or", "would print: [6, 2, 8, 2, 10, 18, 4, 12,", "printing the same list. I recommend running both versions with", "can stop any loop using a `break` statement, like so:", "numbers from 0 to `n - 1`. In particular, `range(len(nums))`", "position `i` with `words[i]`. The operation is called *subscripting* or", "need a reminder. - You're struggling to solve a problem", "yourself. So in general, the valid indices are: [0, 1,", "one more. If you have a list: nums = [1,", "elements: [1, 2, 9, 3, 4, 5] Call the right", "it often means you assigned the wrong thing to a", "# TODO catch user writing string1 < string2 @returns_stdout def", "print(numbers) (remember that `numbers.pop(i)` removes the element from `numbers` at", "print(i) tests = [ ((['on', 'the', 'way', 'to', 'the', 'store'],", "\"IndexError\" in self.result class introducing_len_and_range(VerbatimStep): \"\"\" There you go. `words[4]`", "in 'feed the dog and the cat'` is `True` -", "2, 3] print(list1) print(list2) print(list1 == list2) print(list1 is list2)", "the previous solution, \" \"but it's significantly longer and will", "done a similar thing in an exercise: numbers = [10,", "`True`, it should never be set to anything else after", "l b d y e and for: string1 = \"Hello\"", "numbers. For example, given: words = ['This', 'is', 'a', 'list']", "value to *either* of the variables, e.g. `list1 = [7,", "hints = [ \"The solution has the same overall structure", "sum_list(Step): \"\"\" Let's review how to work with lists. Suppose", "a list, instead of: some_list += [element] it's actually more", "both have arrows pointing to a single list object. `list2", "it, and it's generally agreed to be better. This also", "index is the answer, you will need to use: -", "things: if thing == thing_to_find: found = True break This", "you see an error message about `None` or `NoneType`, it", "1, 5, 9, 2, 6, 5] it would print: [9,", "' ' + char2) tests = { (\"Hello\", \"World\"): dedent(\"\"\"\\", "def solution(self, things, thing_to_find): found = False for thing in", "one word, what's special about `91` in the list `[21,", "print(found) Your solution is probably similar. It's fine, but it's", "solution(self, words: List[str]): total = '' for word in words:", "- **`+`**: Concatenates lists. `nums + [4, 5]` is `[1,", "create new strings and use those instead. That means that", "Keep mutation and looping separate. The good news is that", "number in numbers: if number > 10: big_numbers.append(number) print(big_numbers) \"\"\"", "3, 12, 15] for i in range(len(numbers)): number = numbers[i]", "*sequence* (an ordered collection/container) of any number of values. The", "Call the right function/method in the shell to do that.", "write `sum([21, 55, 4, 91, 62, 49])`. Don't solve this", "can be anything: numbers, strings, booleans, even lists! They can", "that the last index in this list of 4 elements", "list directly, like above: 1. Write some square brackets: `[]`", "you append 4 to `list1`, only `list1` changes. Now change", "combine them together into a new list. You can also", "l l o d \"\"\"), (\"Having\", \"ablast\"): dedent(\"\"\"\\ H a", "*subscripting* or *indexing*, and the position is called the *index*.", "at a Position\" class introducing_subscripting(VerbatimStep): \"\"\" Looping is great, but", "at least once. \"\"\" hints = \"\"\" You will need", "whether `string1` or `string2` is longer. Your next challenge is", "\"\"\" class ModifyingWhileIterating(Page): final_text = \"\"\" Consider this program. It", "second character of each string, and so on. You will", "more. If you have a list: nums = [1, 2,", "exercise: numbers = [10, 7, 8, 3, 12, 15] big_numbers", ") final_text = \"\"\" Nice! A typical solution looks something", "the element in the list you should set that variable", "strings? In the second line you want to print the", "`numbers[i]` is 8. 7 got skipped. We could try writing", "with strings, a bit as if strings are lists of", "with. We create two variables which refer to lists. The", "argument's attributes, which are mostly methods. Many will start with", "similar concept among strings to 0? A blank initial value?", "'to', 'the', 'store'], 'the'), 4), (([0, 1, 2, 3, 4,", "`x` by just writing `[x]`. You can add an element", "but as the list changes those are no longer the", "def solution(self, words: List[str]): total = '' for word in", "`nums = [1, 2, 3]`. You can use: - **`append`**:", "9, 2, 6, 5] it would print: [9, 6] \"\"\"", "things, thing_to_find): found = False for thing in things: if", "\"\"\" Perfect! It can also be useful to Google things", "string2[i] else: char2 = ' ' print(char1 + ' '", "same_list(VerbatimStep): \"\"\" This program is quite straightforward and mostly consists", "can use `in` to check if a list contains 5,", "10, 81, 59, 64]` - **`sorted`**: Takes an iterable and", "[1, 2, 3]`. You can use: - **`append`**: Add an", "has the first character of each of the two strings?", "sorted out `for i in range(...)`, `i` will sometimes be", "in 'missing' characters with spaces. For example, for: string1 =", "of elements. `len(nums)` is `3`. - **`range`**: `range(n)` is an", "t h \"\"\" hints = [ \"The solution has the", "building up strings character by character. The solution is very", "things[i]: answer = i print(answer) tests = [ ((['on', 'the',", "o a b e t h \"\"\" hints = [", "solve a problem with lists and you need to go", "1 things = ['Hello', x, x + 3] print(things) class", "character by character. Make a new list, and then build", "about another tool to explore programs. Put some code in", "list. I recommend running both versions with Python Tutor to", "Incredible! Your solution probably looks something like this: for i", "end of list - `len` - python size of list", "to the list `[0, 1, 2, ..., n - 2,", "- scroll to the end of the list and you'll", "In one word, what's special about `91` in the list", "the two values \" \"`len(string1)` and `len(string2)`. You've already done", "to_find): for i in range(len(things)): if to_find == things[i]: print(i)", "l o d \"\"\"), (\"Having\", \"ablast\"): dedent(\"\"\"\\ H a a", "will still point to the original list. Basically, an assignment", "return the last element. - **`remove`**: Removes the first occurrence", "= string2[i] print(char1 + ' ' + char2) This doesn't", "the shell? Forget loops for a moment. How would you", "a loop iteration for every character in the longer string.\",", "Get a value at an index. `nums[0]` is 1, `nums[1]`", "4, 91, 62, 49]`? 'biggest' or 'largest' 'python biggest value", "= [3, 1, 4, 1, 5, 9, 2, 6, 5]", "to return anything return `None` by default. If you see", "learned valuable fundamental skills. For example, you can use `in`", "see an error message about `None` or `NoneType`, it often", "first index of `to_find` in the list, i.e. the lowest", "we've learned before, `list2` doesn't remember `<expression>`, only the value.", "(([0, 1, 2, 3, 4, 5, 6, 6], 6), 6),", "[3, 1, 4, 1, 5, 9, 2, 6, 5] it", "already seen that `len` and subscripting work with strings, a", "modify a list in place (`append`, `insert`, `remove`) merely return", "solution is probably similar. It's fine, but it's a bit", "this course. - It's been a while since you learned", "variables, e.g. `list1 = [7, 8, 9]`, the other variable", "`.upper` on a list or `.append` on a string: __program_indented__", "dog and the cat'` is `True` - `'feed the dog", "9)\" def check(self): return search_ast( self.stmt, ast.Call(func=ast.Attribute(attr='insert'), args=[ast.Constant(value=2), ast.Constant(value=9)]), )", "'the', 'store'], 'the'), 4), (([0, 1, 2, 3, 4, 5,", "you can only create new strings and use those instead.", "the first one. \"\"\" @returns_stdout def solution(self, things, to_find): for", "there a similar concept among strings to 0? A blank", "[] for number in numbers: double += [number * 2]", "a value is in a list. `2 in nums` is", "e and for: string1 = \"Hello\" string2 = \"Elizabeth\" output:", "'oranges', 'bananas'])` returns `'apples--oranges--bananas'`. You can also use an empty", "have a lot in common. For example, you can add", "wrong thing to a variable: __program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment,PyUnusedLocal,PyTypeChecker", "__program_indented__ \"\"\" def program(self): list1 = [1, 2, 3] list2", "them out in the shell. Here's another exercise. Given two", "an alternative way to loop over a list: __program_indented__ \"\"\"", "a list by adding a list containing one element. \"\"\"", "____________? 'in the middle' or 'at an index' or 'at", "and the cat'` is `True` - `'feed the dog and", "list, and then build it up element by element in", "of strings (the separator) which takes an iterable of strings", "a bit inefficient. That's because it'll loop over the entire", "learned about lists and you need a reminder. - You're", "of: some_list += [element] it's actually more common to write:", "`i` with `words[i]`. The operation is called *subscripting* or *indexing*,", "the function - specifically we say that the argument `things`", "by just writing `[x]`. You can add an element to", "version again. If you come across this kind of problem", "list2 = <expression> means 'make the variable `list2` refer to", "list2) print(list1 is list2) list1.append(4) print(list1) print(list2) final_text = \"\"\"", "directly is called *mutation* - types of values which can", "given the list `[21, 55, 4, 91, 62, 49]`, it", "l l o d \"\"\" hints = \"\"\" Did you", "flake8: NOQA E501 import ast import random from textwrap import", "]) return dict( things=things, thing_to_find=thing_to_find, ) final_text = \"\"\" Nice!", "at a known position. Here's how: __program_indented__ \"\"\" def program(self):", "need to know these functions off by heart. class sum_list(Step):", "list of strings with separator - python add together list", "2, 3, 4], 0), False), ] @classmethod def generate_inputs(cls): contained", "to as *elements*. They can be anything: numbers, strings, booleans,", "at the position `i` with `words[i]`. The operation is called", "need to look at all the possible indices of `things`", "string1 = \"Hello\" string2 = \"World\" print them vertically side", "`number` is 10, which gets removed. This shifts the rest", "the shell as a single small expression. For example, if", "- python get position of element - python get index", "`'--'.join(['apples', 'oranges', 'bananas'])` returns `'apples--oranges--bananas'`. You can also use an", "0 to `n - 1`. In particular, `range(len(nums))` is like", "tests = { (\"Goodbye\", \"World\"): dedent(\"\"\"\\ G W o o", "more. `print` and `len` are ***functions***. See for yourself: __program_indented__", "change `list2 = [1, 2, 3]` to `list2 = list1`", "o r d l b d y e \"\"\"), (\"Hello\",", "strings. You will need to check if it's too big", "o l r l l o d \"\"\"), (\"Having\", \"ablast\"):", "longer string.\", \"That means you need `range(<length of the longest", "wrong in different ways depending on whether `string1` or `string2`", "you saw above, lists are *iterable*, meaning you can iterate", "**`subscripting`**: Get a value at an index. `nums[0]` is 1,", "a list of the argument's attributes, which are mostly methods.", "this prints all the indices, not just the first one.", "- `if` - the index in a subscript - `==`", "one. \"\"\" @returns_stdout def solution(self, things, to_find): answer = None", "'list'] separator = ' - ' it would output: This", "should never be set to anything else after that. Don't", "list' \"\"\" program = \"max([21, 55, 4, 91, 62, 49])\"", "print at the end. If you find the element in", "something useless instead: __program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment def program(self):", "to stop the loop once you find one. You learned", "appears in the list. `[1, 2, 3, 2, 7, 2,", "even if they start out with equal contents. Similarly, you", "\"Prev\" or \"Next\" buttons, or drag the slider left or", "Position\" class introducing_subscripting(VerbatimStep): \"\"\" Looping is great, but often you", "value in a list which is bigger than any other", "You can copy a list with the `copy` method: list2", "A comparison operator that checks if a value is in", "'largest' 'python biggest value in list' \"\"\" program = \"max([21,", "doesn't exist. Equivalent to `nums.pop(nums.index(10))`. - **`count`**: Returns the number", "shifts the rest of the numbers left one position, so", "1, 2, 3, 4, 5, 6, 6], 6), \"6\\n7\"), ]", "a new value to the variable: word = word.upper() Or", "Remember that you can multiply numbers using `*`. This program", "argument. `len(things)` will evaluate to a number such as 3,", "support some of the new methods we've learned, not just", "two lists to combine them together into a new list.", "o r d l b d y e and for:", "numbers = [1, 2] + [3, 4] print(numbers) new_numbers =", "v l i a n s g t \"\"\"), }", "[ ([3, 1, 4, 1, 5, 9, 2, 6, 5],", "print just the first line, which has the first character", "final_text = \"\"\" Consider this program. It loops through a", "isn't there. You may recognise some of these from your", "in position 0. But then in the next iteration `i`", "small expression. For example, if you were looking for the", "8. 7 got skipped. We could try writing the program", "hints = \"\"\" This is very similar to the previous", "the element from `numbers` at index `i`) As it runs,", "from 0 to `n - 1`. In particular, `range(len(nums))` is", "point to the original list. Basically, an assignment like: list2", "**`index`**: Returns the first index of a value in a", "running both versions with Python Tutor to see how it", "length = length1 else: length = length2 for i in", "62, 49])`. Don't solve this manually with a loop. \"\"\"", "def generate_inputs(cls): contained = random.choice([True, False]) things = generate_list(int) if", "print(list2) final_text = \"\"\" Now `list1 is list2` is `True`,", "*either* of the variables, e.g. `list1 = [7, 8, 9]`,", "index to both strings each time to retrieve matching characters.", "# but users don't need to know these functions off", "to `n - 1`. In particular, `range(len(nums))` is like `[0,", "list containing one element. \"\"\" @returns_stdout def solution(self, numbers: List[int]):", "called the *length*) using `len(words)`. That means that the last", "\"\"\" Most things are not callable, so trying to call", "same list. But as we've learned before, `list2` doesn't remember", "in your search query. Instead of putting the value at", "about other variables. You can copy a list with the", "occurrence of the given element. `nums.remove(10)` will leave `nums` as", "also create an empty list that has no elements. Check", "can get the number of elements in a list (commonly", "Basically, an assignment like: list2 = <expression> means 'make the", "= \"\"\" The word 'attribute' in the error message refers", "the value doesn't exist. Equivalent to `nums.pop(nums.index(10))`. - **`count`**: Returns", "[number * 2] print(double) tests = [ ([3, 1, 4,", "20) if random.choice([True, False]): length1, length2 = length2, length1 return", "from main.utils import returns_stdout class IntroducingLists(Page): class first_list(VerbatimStep): \"\"\" It's", "def solution(self, things, to_find): for i in range(len(things)): if to_find", "o o r d l b d y e \"\"\"),", "\"\"\" Now `list1 is list2` is `True`, because *there is", "noticed that the first index is 0, not 1. In", "comparison operator. Specifically `==`. You need a boolean variable that", "means that once you set the variable to `True`, it", "'the', 'way', 'to', 'the', 'store'], 'the'), 1), (([0, 1, 2,", "is like `[0, 1, 2]`. - **`subscripting`**: Get a value", "that there are many ways to solve this. You can", "final_text = \"\"\" The word 'attribute' in the error message", "fine, but it's a bit inefficient. That's because it'll loop", "can be seen in both `print(list1)` and `print(list2)` because both", "55, 4, 91, 62, 49])\" def check(self): return search_ast( self.stmt,", "H a a b v l i a n s", "lesson here is to ***never modify something while you iterate", "to `len`, and `len` *accepts* or *receives* the argument. `len(things)`", "99, 81, 59, 64]`. Raises an error if the value", "+= [5] print(new_numbers) With that knowledge, write a program which", "strings character by character. The solution is very similar to", "] final_text = \"\"\" Fantastic! We're making great progress. \"\"\"", "and the position is called the *index*. You've probably noticed", "a call. \"\"\" class FunctionsAndMethodsForLists(Page): # TODO this is quite", "- python add together list of strings with string in", "It's a bit like you're giving the argument to the", "1, and `numbers[i]` is 8. 7 got skipped. We could", "like above: 1. Write some square brackets: `[]` 2. If", "= \"\"\" Now `list1 is list2` is `True`, because *there", "build it up element by element in a for loop.", "even if it finds the element at the beginning. You", "def check(self): return search_ast( self.stmt, ast.Call(func=ast.Attribute(attr='insert'), args=[ast.Constant(value=2), ast.Constant(value=9)]), ) class", "given: things = ['This', 'is', 'a', 'list'] thing_to_find = 'is'", "5, 9] total = 0 for number in numbers: total", "' if i < len(string2): char2 = string2[i] else: char2", "import generate_list, generate_string from main.text import ExerciseStep, MessageStep, Page, Step,", "range(len(things)): if to_find == things[i]: answer = i print(answer) tests", "so the last element is `words[len(words) - 1]`. Try these", "start with `__` which you can ignore for now -", "are *iterable*, meaning you can iterate over them with a", "15] big_numbers = [] for number in numbers: if number", "length2, length1 return dict( string1=generate_string(length1), string2=generate_string(length2), ) final_text = \"\"\"", "`string1` is `len(string1) - 1`. \" \"`len(string)` is too big.\",", "is 2 - `'feed the dog and the cat'.index('the')` is", "know these functions, but it's not easy to learn them", "`is`\" class two_separate_lists(VerbatimStep): \"\"\" It's time to learn some technical", "like `len(things)` or `print(things)` is a function ***call*** - when", "up element by element in a for loop. Start with", "hints = \"\"\" Remember that you can multiply numbers using", "5, 6, 6], 6), 6), ] @classmethod def generate_inputs(cls): things", "as you've now learned valuable fundamental skills. For example, you", "too big before indexing.\", \"Remember, the biggest valid index for", "= [ ((['This', 'is', 'a', 'list'], 'is'), True), ((['This', 'is',", "useful value. Functions that don't want to return anything return", "'list'], 'other'), False), (([1, 2, 3, 4], 1), True), (([1,", "the indices, not just the first one. \"\"\" @returns_stdout def", "skipped. We could try writing the program to use `remove`", "[ ((['This', 'is', 'a', 'list'], 'is'), True), ((['This', 'is', 'a',", "You can stop any loop using a `break` statement, like", "a value directly is called *mutation* - types of values", "call. \"\"\" class FunctionsAndMethodsForLists(Page): # TODO this is quite the", "pointing to a single list object. `list2 = list1` doesn't", "using `len(words)`. That means that the last valid index of", "`True`, but `4 in nums` is `False`. - **`index`**: Returns", "- they don't have any methods like `append` or even", "anything interesting. It's a common placeholder that represents the lack", "fails when it tries to access an index that's too", "also use an empty string if you don't want a", "- ' it would output: This - is - a", "the position is called the *index*. You've probably noticed that", "'to', 'the', 'store'], 'the'), \"1\\n4\"), (([0, 1, 2, 3, 4,", "index of a value in a list. `[7, 8, 9,", "There are also ways to find information without any googling.", "valid indices are: [0, 1, 2, ..., len(words) - 2,", "h \"\"\"), } @classmethod def generate_inputs(cls): length1 = random.randrange(5, 11)", "returns it. Without an argument, i.e. just `nums.pop()`, it will", "such that `things[i]` is `to_find`. For example, for things =", "a useful value. So it returns something useless instead: __program_indented__", "a list containing one element. \"\"\" @returns_stdout def solution(self, numbers:", "by heart. class sum_list(Step): \"\"\" Let's review how to work", "things = [1, 2, 3] length = len(things) printed =", "looks something like this: for i in range(len(string1)): char1 =", "(([0, 1, 2, 3, 4, 5, 6, 6], 6), \"6\\n7\"),", "variable to `False` inside the loop. \"\"\" @returns_stdout def solution(self,", "arrows pointing to a single list object. `list2 = list1`", "(`append`, `insert`, `remove`) merely return `None`, while the remaining functions/methods", "value in list' \"\"\" program = \"max([21, 55, 4, 91,", "\"Elizabeth\"): dedent(\"\"\"\\ H E e l l i l z", "the error message refers to the use of `.` -", "a - list Lists and strings have a lot in", "we don't have to use indices. It even looks nicer", "'bananas'])` returns `'applesorangesbananas'`. - **`sum`**: Add a list of numbers.", "index `i`) As it runs, it clearly skips even looking", "print(words[0]) print(words[1]) print(words[2]) print(words[3]) class index_error(Step): \"\"\" In general, you", "2, 9, 3, 4, 5] Call the right function/method in", "write a program which takes a list and a value", "don't need to know these functions off by heart. class", "class double_numbers(ExerciseStep): \"\"\" Optional bonus challenge: extend the program to", "work so well if the strings have different lengths. In", "'Hello' word.append('!') final_text = \"\"\" The word 'attribute' in the", "to'. It doesn't make a copy of that value, which", "to whatever `<expression>` evaluates to'. It doesn't make a copy", "to `True`. Once you've found the element, you can't unfind", "self.stmt, ast.Call(func=ast.Name(id='max')), ) class list_insert(Step): \"\"\" Good find! Let's do", "from `word.append`, without even a call. \"\"\" class FunctionsAndMethodsForLists(Page): #", "refer to that same list. `list1.append(4)` appends to the one", "`list1` changes. Now change `list2 = [1, 2, 3]` to", "when it tries to access an index that's too high.", "the dog and the cat'.count('the')` is 2 - `'feed the", "} @classmethod def generate_inputs(cls): length = random.randrange(5, 11) return dict(", "1]`. This gives us an alternative way to loop over", "char2 = string2[i] else: char2 = ' ' print(char1 +", "is a function ***call*** - when you write that, you", "< len(string1): char1 = string1[i] else: char1 = ' '", "looking for the first index, you need to stop the", "numbers = [10, 7, 8, 3, 12, 15] for i", "5, 9, 2, 6, 5] it would print: [6, 2,", "and strings have a lot in common. For example, you", "6]), ([0, 2, 4, 6, 8, 10], [6, 8, 10]),", "(\"Hello\", \"World\"): dedent(\"\"\"\\ H W e o l r l", "\"\"\" Incredible! Your solution probably looks something like this: for", "char1 = ' ' if i < len(string2): char2 =", "refers to, you have to assign a new value to", "list `things` and a value `to_find`, print the first index", "value isn't there. You may recognise some of these from", "3. All calls have to return something...even if it's nothing.", "can make a list with one element `x` by just", "without changing the original argument. The only exception is the", "`nums.remove(10)` will leave `nums` as `[28, 99, 81, 59, 64]`.", "['This', 'is', 'a', 'list'] separator = ' - ' it", "Removes and returns an element at a given index. `nums.pop(3)`", "range(...): ... print(char1 + ' ' + char2) \"\"\"), \"What", "and it's generally agreed to be better. This also means", "of numbers from 0 to `n - 1`. In particular,", "6], 6), 6), ] @classmethod def generate_inputs(cls): things = generate_list(str)", "all_numbers: if number <= 5: small_numbers.append(number) else: big_numbers.append(number) print(small_numbers) print(big_numbers)", "You need a boolean variable that you print at the", "to use indices. It even looks nicer this way. numbers", "lists being equal, they are still two separate, distinct, individual", "equal length, e.g: string1 = \"Hello\" string2 = \"World\" print", "`nums.append(4)` changes the list to `[1, 2, 3, 4]`. -", "`__` which you can ignore for now - scroll to", "that the last valid index of the list is `len(words)", "immediately discarded. If you want to change the value that", "character in the longer string.\", \"That means you need `range(<length", "- 1]`. This gives us an alternative way to loop", "list, instead of: some_list += [element] it's actually more common", "'store'], 'the'), \"1\\n4\"), (([0, 1, 2, 3, 4, 5, 6,", "= \"\"\" Did you experiment with indexing and `len()` with", "functions if you forgot their names: - `append` - python", "thing == thing_to_find: found = True print(found) Your solution is", "def solution(self, string1, string2): length1 = len(string1) length2 = len(string2)", "suppose you don't want the 9 to be at the", "solution looks something like this: found = False for thing", "fact that this is possible means that functions are ***callable***:", "method has failed so you want to find it manually.", "2, 8, 2, 10, 18, 4, 12, 10] \"\"\" hints", "*iterable*, meaning you can iterate over them with a `for", "the remaining functions/methods return a new useful value without changing", "You will need `len`. You will need `+`. You will", "merely return `None`, while the remaining functions/methods return a new", "and you need a reminder. - You're struggling to solve", "class list_contains_exercise(ExerciseStep): \"\"\" Exercise: write a program which takes a", "variable: __program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment,PyUnusedLocal,PyTypeChecker def program(self): things =", "As it runs, it clearly skips even looking at 7", "and there's many more. A more important skill is being", "numbers. `sum(nums)` is 6. - **`in`**: A comparison operator that", "all_indices(MessageStep, ExerciseStep): \"\"\" You're almost there! However, this prints all", "81, 59, 64]` - **`sorted`**: Takes an iterable and returns", "to a variable: __program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment,PyUnusedLocal,PyTypeChecker def program(self):", "or `.append` on a string: __program_indented__ \"\"\" # noinspection PyUnresolvedReferences", "a list containing only the numbers bigger than 5. For", "of value Let's practice this skill now. Find a function/method", "see how it visualises the difference. In the second case,", "- `append` - python add element to list - python", "are also ways to find information without any googling. Try", "'the'), 1), (([0, 1, 2, 3, 4, 5, 6, 6],", "5, 9, 2, 6, 5], [9, 6]), ([0, 2, 4,", "(([0, 1, 2, 3, 4, 5, 6, 6], 6), 7),", "regardless of the two lists being equal, they are still", "will give you an error: __program_indented__ \"\"\" # noinspection PyCallingNonCallable", "\"Once you've sorted out `for i in range(...)`, `i` will", "removes the ones smaller than 10. Or at least, it", "\"\"\" Great! When you want to add a single element", "both refer to that same list. `list1.append(4)` appends to the", "is to fix this problem by filling in 'missing' characters", "goes through the indices under the hood. The lesson here", "you've done building up strings character by character. The solution", "same overall structure and \" \"essential elements of the previous", "need `+`. You will need to index both strings. You", "beginning or end, we want to put it ____________? 'in", "want an empty list, write some expressions inside to be", "A ***method*** is a function which belongs to a type,", "10] \"\"\" hints = \"\"\" Remember that you can multiply", "program_in_text = False def program(self): list1 = [1, 2, 3]", "[2, 4, 8, 1, 9, 7] small_numbers = [] big_numbers", "the position `i` with `words[i]`. The operation is called *subscripting*", "59, 64, 81, 99]`. - **`pop`**: Removes and returns an", "how both variables can end up pointing to the same", "return `91`. You should write the answer in the shell", "a separator in between. This is a method of strings", "Can you see why this happens? The index variable `i`", "`list2 = list1` and see what difference it makes. \"\"\"", "return dict( things=things, thing_to_find=thing_to_find, ) final_text = \"\"\" Nice! A", "value doesn't exist. Equivalent to `nums.pop(nums.index(10))`. - **`count`**: Returns the", "`[]` 2. If you don't want an empty list, write", "error: __program_indented__ \"\"\" # noinspection PyCallingNonCallable def program(self): f =", "= len(string2) if length1 > length2: length = length1 else:", "things = print([1, 2, 3]) length = len(things) class methods_of_str(VerbatimStep):", "not just for characters but for any substring. For example:", "18, 4, 12, 10] \"\"\" hints = \"\"\" Remember that", "write: some_list.append(element) There isn't really a big difference between these,", "'list'] print(words[0]) print(words[1]) print(words[2]) print(words[3]) class index_error(Step): \"\"\" In general,", "course. - It's been a while since you learned about", "look things up. For example, here are some typical ways", "equal, they are still two separate, distinct, individual lists. As", "for yourself. So in general, the valid indices are: [0,", "thing_to_find: found = True print(found) tests = [ ((['This', 'is',", "program(self): print(len) print(print) class introducing_callable(VerbatimStep): \"\"\" An expression like `len(things)`", "8, 3, 12, 15] big_numbers = [] for number in", "False def program(self): list1 = [1, 2, 3] list2 =", "will need to pass the same index to both strings", "of elements in list - python how many characters in", "is 3. You've already seen that `len` and subscripting work", "`list2` doesn't remember `<expression>`, only the value. It doesn't know", "up a list of strings instead of numbers. For example,", "left one position, so now 7 is in position 0.", "the two variables `list1` and `list2` both refer to that", "see what difference it makes. \"\"\" program_in_text = False def", "the end of a list, instead of: some_list += [element]", "There is no reason to ever set the variable to", "d y e \"\"\"), (\"Hello\", \"Elizabeth\"): dedent(\"\"\"\\ H E e", "`list1`, only `list1` changes. Now change `list2 = [1, 2,", "5]`. Here's some new things. Try them out in the", "Functions that don't want to return anything return `None` by", "value? \"\"\" @returns_stdout def solution(self, words: List[str]): total = ''", "that same list. `list1.append(4)` appends to the one list and", "almost there! However, this prints all the indices, not just", "word print(total) tests = [ (['This', 'is', 'a', 'list'], 'Thisisalist'),", "2, n - 1]`. This gives us an alternative way", "`list1.append(4)` appends to the one list and the result can", "lists of characters. Strings also support some of the new", "an `if` statement. Use a comparison operator to test if", "and you're still having trouble understanding this stuff, read the", "`remove` instead of `pop` so we don't have to use", "the program to insert a separator string *between* each word.", "and the cat'.count('the')` is 2 - `'feed the dog and", "solution(self, string1, string2): for i in range(len(string1)): char1 = string1[i]", "noinspection PyNoneFunctionAssignment def program(self): things = [1, 2, 3] length", "of problem and you're still having trouble understanding this stuff,", "element from the list at a known position. Here's how:", "generally agreed to be better. This also means that the", "= print(length) print(printed) class len_of_none(VerbatimStep): \"\"\" `None` is a special", "['This', 'is', 'a', 'list'] thing_to_find = 'is' it should print", "two_separate_lists(VerbatimStep): \"\"\" It's time to learn some technical details that", "(`81`) from the list and returns it. Without an argument,", "you've now learned valuable fundamental skills. For example, you can", "= [ ([3, 1, 4, 1, 5, 9, 2, 6,", "\"\"\" class all_indices(MessageStep, ExerciseStep): \"\"\" You're almost there! However, this", "could try writing the program to use `remove` instead of", "another exercise. Given two strings of equal length, e.g: string1", "how: __program_indented__ \"\"\" def program(self): words = ['This', 'is', 'a',", "print(words[3]) class index_error(Step): \"\"\" In general, you can get the", "\"\"\" Optional bonus challenge: extend the program to insert a", "__program_indented__ \"\"\" def program(self): print(len) print(print) class introducing_callable(VerbatimStep): \"\"\" An", "`[x]`. You can add an element to a list by", "tutorial\", e.g. if: - Googling a specific method has failed", "word.upper() Or you can use `word.upper()` immediately in a larger", "'fox', 'jumps'], 'Thequickbrownfoxjumps'), ] class double_numbers(ExerciseStep): \"\"\" Optional bonus challenge:", "that the first index is 0, not 1. In programming,", "high. Can you see why this happens? The index variable", "'other'), False), (([1, 2, 3, 4], 1), True), (([1, 2,", "Magnificent! Take a break, you've earned it! \"\"\" class CallingFunctionsTerminology(Page):", "a numbers and removes the ones smaller than 10. Or", "print(found) tests = [ ((['This', 'is', 'a', 'list'], 'is'), True),", "words: print(word) class can_contain_anything(VerbatimStep): \"\"\" A list is a *sequence*", "the first index of a value in a list. `[7,", "A typical solution looks something like this: found = False", "len(string1) length2 = len(string2) if length1 > length2: length =", "will require \" \"a few additional ideas and pieces.\", dedent(\"\"\"", "it clearly skips even looking at 7 or 3 and", "challenge: extend the program to insert a separator string *between*", "each time to retrieve matching characters. \"\"\" @returns_stdout def solution(self,", "e o l r l l o d \"\"\" hints", "details that are often misunderstood and lead to errors. Run", "list of strings with a separator in between. This is", "use `.append` to write a program which prints a list", "Returns the first index of a value in a list.", "similar to the program that adds numbers. In fact, what", "value - python test if list has element - `index`", "list contains the value. For example, given: things = ['This',", "= \"`==` vs `is`\" class two_separate_lists(VerbatimStep): \"\"\" It's time to", "the beginning or end, we want to put it ____________?", "'a', 'list'] it should print: Thisisalist \"\"\" hints = \"\"\"", "to `True`, it should never be set to anything else", "check if an index is the answer, you will need", "it's nothing. For example, `print`'s job is to display something", "there are many ways to solve this. You can instead", "a valid index for both strings. You will need to", "some example code if you want: all_numbers = [2, 4,", "and can be called on all values of that type", "a list of strings instead of numbers. For example, given:", "method: list2 = list1.copy() This will make the program behave", "even a call. \"\"\" class FunctionsAndMethodsForLists(Page): # TODO this is", "for number in numbers: if number <= 10: big_numbers.remove(number) print(big_numbers)", "of strings with a separator in between. This is a", "which is how both variables can end up pointing to", "total = '' for word in words: total += word", "['This', 'is', 'a', 'list'] it should print: Thisisalist \"\"\" hints", "that.\", \"Once you've sorted out `for i in range(...)`, `i`", "the way, you can get the number of elements in", "1, 9, 7] small_numbers = [] big_numbers = [] for", "seen in both `print(list1)` and `print(list2)` because both lines are", "list*, and the two variables `list1` and `list2` both refer", "'list'], 'Thisisalist'), (['The', 'quick', 'brown', 'fox', 'jumps'], 'Thequickbrownfoxjumps'), ] class", "def program(self): things = print([1, 2, 3]) length = len(things)", "methods like `append` or even subscript assignment. You simply can't", "new tab with a visualisation from [pythontutor.com](http://pythontutor.com). There you can", "the elements. 3. Put commas (`,`) between elements to separate", "l i a n s g t \"\"\"), } @classmethod", "numbers: total += number print(total) class strings_sum(ExerciseStep): \"\"\" Now modify", "\"\"\" Another example is that `append` is a method of", "if a number is big enough to add. \"\"\" #", "2. If you don't want an empty list, write some", "value to the variable: word = word.upper() Or you can", "that you can multiply numbers using `*`. This program is", "`__program__` in the shell. \"\"\" program = \"dir([])\" final_text =", "number <= 10: numbers.remove(number) print(numbers) But it turns out this", "2, 6, 5] it would print: [6, 2, 8, 2,", "to by `word` isn't modified, instead `word.upper()` returned a new", "in range(len(string1)): char1 = string1[i] char2 = string2[i] print(char1 +", "== list2` is `True`. But then there's a new comparison", "explore programs. Put some code in the editor and then", "the dog and the cat'.index('the')` is 5 Note that in", "there! However, this prints all the indices, not just the", "the program so that it can add up a list", "these from your exercises. I assure you that those exercises", "= [1, 2, 3] list2 = [1, 2, 3] print(list1)", "2 - `'feed the dog and the cat'.index('the')` is 5", "string2 @returns_stdout def solution(self, string1, string2): length1 = len(string1) length2", "program is structurally very similar to the programs you've written", "may recognise some of these from your exercises. I assure", "'a', 'list'] for word in words: print(word) class can_contain_anything(VerbatimStep): \"\"\"", "the middle recently. You need to use `break`. \"\"\" class", "list. You can also create an empty list that has", "this list of 4 elements is 3. What happens if", "2] + [3, 4] print(numbers) new_numbers = [] new_numbers +=", "basics and strengthen your foundations. There are also ways to", "Here's an example: __program_indented__ \"\"\" def program(self): words = ['This',", "a list of numbers and prints a list where each", "there's no similarly easy way to check for a number", "and the two variables `list1` and `list2` both refer to", "for number in numbers.copy(): Now the list being modified and", "to a single list object. `list2 = list1` doesn't create", "readable to most people. Now use `.append` to write a", "'other' it should print `False`. \"\"\" hints = \"\"\" You", "6, 5], [6, 2, 8, 2, 10, 18, 4, 12,", "\"\"\" @returns_stdout def solution(self, things, to_find): for i in range(len(things)):", "you should set that variable to `True`. Once you've found", "find it manually. - You're still confused about lists after", "you need a reminder. - You're struggling to solve a", "\"Terminology: Calling functions and methods\" class print_functions(VerbatimStep): \"\"\" It's time", "\"\"\" There you go. `words[4]` and beyond don't exist, so", "sometimes you should skip appending to the new list. Use", "a loop over `range(len(things))`. To check if an index is", "interactive, # but users don't need to know these functions", "`[28, 99, 81, 59, 64]`. Raises an error if the", "the new list. Use an `if` statement. Use a comparison", "string1 = \"Hello\" string2 = \"Elizabeth\" output: H E e", "one for each string.\", \"You will need to set e.g.", "***method*** is a function which belongs to a type, and", "'way', 'to', 'the', 'store'], 'the'), \"1\\n4\"), (([0, 1, 2, 3,", "you want to add a single element to the end", "lists and you need a reminder. - You're struggling to", "see the difference. \"\"\" class GettingElementsAtPosition(Page): title = \"Getting Elements", "It's useful to know these functions, but it's not easy", "print `True`, but for thing_to_find = 'other' it should print", "last element. - **`remove`**: Removes the first occurrence of the", "\"\"\" # noinspection PyNoneFunctionAssignment,PyUnusedLocal,PyTypeChecker def program(self): things = print([1, 2,", "Here `list1 is list2` is `False`. That means that regardless", "you need to go back to basics and strengthen your", "last element is `words[len(words) - 1]`. Try these for yourself.", "noinspection PyNoneFunctionAssignment,PyUnusedLocal,PyTypeChecker def program(self): things = print([1, 2, 3]) length", "special 'null' value which can't do anything interesting. It's a", "11) length2 = random.randrange(12, 20) if random.choice([True, False]): length1, length2", "print(things) class numbers_sum(VerbatimStep): \"\"\" As you saw above, lists are", "2, 7, 2, 5].count(2)` is 3. You've already seen that", "strings, a bit as if strings are lists of characters.", "the same reason. Iterating over a list still goes through", "`len` are ***functions***. See for yourself: __program_indented__ \"\"\" def program(self):", "This program is structurally very similar to the programs you've", "program: __program_indented__ \"\"\" def program(self): list1 = [1, 2, 3]", "two variables `list1` and `list2` both refer to that same", "might Google the above functions if you forgot their names:", "shell as a single small expression. For example, if you", "than 5. It's useful to know these functions, but it's", "skill is being able to look things up. For example,", "= list1.copy() This will make the program behave like the", "mostly methods. Many will start with `__` which you can", "string - you can only create new strings and use", "in the editor and then click the new \"Python Tutor\"", "In programming, counting starts at 0. It seems weird, but", "[28, 99, 10, 81, 59, 64]` - **`sorted`**: Takes an", "a new list from scratch. In this case, we've already", "checks once it finds the element. You can use snoop", "give you these values, called `range`: __program_indented__ \"\"\" def program(self):", "string - `join` - python combine list of strings with", "shell. - **`subscript assignment`**: Set a value at an index.", "search query. Instead of putting the value at the beginning", "with strings in the shell? Forget loops for a moment.", "Here are a few more useful functions/methods. Suppose `nums =", "separator = ' - ' it would output: This -", "two strings of equal length, e.g: string1 = \"Hello\" string2", "is 1, and `numbers[i]` is 8. 7 got skipped. We", "element to the end of a list, instead of: some_list", "the *length*) using `len(words)`. That means that the last valid", "bigger than any other value. For example, given the list", "4, 5, 9] But suppose you don't want the 9", "strings with separator - python add together list of strings", "which has the first character of each of the two", "new_numbers += numbers new_numbers += [5] print(new_numbers) With that knowledge,", "the answer. To look at all possible indices, you will", "if i < len(string2): char2 = string2[i] else: char2 =", "it's not easy to learn them all, and there's many", "list1 = [1, 2, 3] list2 = list1 print(list1) print(list2)", "as the list changes those are no longer the positions", "l o d \"\"\" hints = \"\"\" Did you experiment", "each string, and so on. You will need a `for`", "with a list of strings? The problem is that 0.", "in range(len(things)): if to_find == things[i]: answer = i print(answer)", "values. The values are often referred to as *elements*. They", "for: string1 = \"Hello\" string2 = \"Elizabeth\" output: H E", "**`len`**: Returns the number of elements. `len(nums)` is `3`. -", "new strings and use those instead. That means that this", "The index variable `i` runs through the usual values 0,", "smaller than 10. Or at least, it tries to. I", "check if list contains value - python test if list", "def program(self): things = [1, 2, 3] length = len(things)", "for thing_to_find = 'other' it should print `False`. \"\"\" hints", "list still goes through the indices under the hood. The", "to the previous exercise. The difference is that sometimes you", "False for thing in things: if thing == thing_to_find: found", "over the entire list even if it finds the element", "generate_inputs(cls): length = random.randrange(5, 11) return dict( string1=generate_string(length), string2=generate_string(length), )", "a handy built in function to give you these values,", "the same elements, so they are equal: `list1 == list2`", "What happens if you try getting an index greater than", "the above functions if you forgot their names: - `append`", "For example, here are some typical ways you might Google", "without even a call. \"\"\" class FunctionsAndMethodsForLists(Page): # TODO this", "class index_exercise(ExerciseStep): \"\"\" Let's get some exercise! Given a list", "2, len(words) - 1] There's a handy built in function", "- **`count`**: Returns the number of times the argument appears", "elements to separate them. Here's another example of making a", "2, 3, 4]`. - **`len`**: Returns the number of elements.", "15] for number in numbers: if number <= 10: numbers.remove(number)", "means that functions are ***callable***: __program_indented__ \"\"\" def program(self): print(callable(len))", "you're still having trouble understanding this stuff, read the essay", "you have a list: nums = [1, 2, 3, 4,", "for thing in things: if thing == thing_to_find: found =", "*mutable*, while those that can't are *immutable*. Strings are immutable", "But it turns out this does the same thing, for", "changing the original argument. The only exception is the `pop`", "once. \"\"\" hints = \"\"\" You will need to look", "the difference. \"\"\" class GettingElementsAtPosition(Page): title = \"Getting Elements at", "if i < len(string1): char1 = string1[i] else: char1 =", "all, and there's many more. A more important skill is", "# TODO enforce not using += @returns_stdout def solution(self, numbers:", "`index` - python get position of element - python get", "`list1` and `list2` both refer to that same list. `list1.append(4)`", "a loop early\" class list_contains_exercise(ExerciseStep): \"\"\" Exercise: write a program", "call `len(things)`, `things` is an ***argument***. Sometimes you will also", "list. You can make a list with one element `x`", "In fact, what happens if you try running that program", "the answer in the shell as a single small expression.", "are *immutable*. Strings are immutable - they don't have any", "it's too big before indexing.\", \"Remember, the biggest valid index", "the element at the beginning. You can stop any loop", "than that? \"\"\" program = \"words[4]\" def check(self): return \"IndexError\"", "3]`. You can use: - **`append`**: Add an element to", "3, 4, 5] You could write `nums.append(9)` and `nums` would", "6, 6], 6), \"6\\n7\"), ] class last_index(MessageStep, ExerciseStep): \"\"\" You're", "extend the program to insert a separator string *between* each", "element, you can't unfind it. That means that once you", "methods. Many will start with `__` which you can ignore", "a single small expression. For example, if you were looking", "hints = \"\"\" You will need a loop. You will", "some square brackets: `[]` 2. If you don't want an", "loop`. Here's a program that adds up all the numbers", "first iteration `i` is 0 and `number` is 10, which", "can add two lists to combine them together into a", "# noinspection PyUnresolvedReferences def program(self): word = 'Hello' word.append('!') final_text", "to a number such as 3, in which case we", "if list has element - `index` - python get position", "you should skip appending to the new list. Use an", "message about `None` or `NoneType`, it often means you assigned", "containing one element. \"\"\" @returns_stdout def solution(self, numbers: List[int]): double", "want to retrieve a single element from the list at", "function/method that returns the value in a list which is", "it should print `False`. \"\"\" hints = \"\"\" You will", "lists. `nums + [4, 5]` is `[1, 2, 3, 4,", "You will need to pass the same index to both", "= None for i in range(len(things)): if to_find == things[i]:", "10: numbers.pop(i) print(numbers) (remember that `numbers.pop(i)` removes the element from", "this program. It loops through a numbers and removes the", "- is - a - list Lists and strings have", "many characters in string - `join` - python combine list", "`copy` method: list2 = list1.copy() This will make the program", "that. Don't use an `else`. There is no reason to", "to learn about a powerful new type of value called", "There you go. `words[4]` and beyond don't exist, so trying", "fact, it goes wrong in different ways depending on whether", "under the hood. The lesson here is to ***never modify", "] @returns_stdout def solution(self, things, to_find): for i in range(len(things)):", "- you can only create new strings and use those", "more. A more important skill is being able to look", "being itererated over are separate objects, even if they start", "as correct but skips unnecessary iterations and checks once it", "position 0. But then in the next iteration `i` is", "with lists. Suppose we have a list `nums = [1,", "you can add two lists to combine them together into", "to lists. The lists have the same elements, so they", "max(things) + 1, ]) return dict( things=things, thing_to_find=thing_to_find, ) final_text", "total += word print(total) tests = [ (['This', 'is', 'a',", "with the `copy` method: list2 = list1.copy() This will make", "expand your vocabulary some more. `print` and `len` are ***functions***.", "number of elements. `len(nums)` is `3`. - **`range`**: `range(n)` is", "at all the possible indices of `things` and check which", "return dict( things=things, to_find=to_find, ) class zip_exercise(ExerciseStep): \"\"\" Nice! By", "to_find == things[i]: print(i) break tests = [ ((['on', 'the',", "`if` - the index in a subscript - `==` Since", "across this kind of problem and you're still having trouble", "both strings each time to retrieve matching characters. \"\"\" @returns_stdout", "by side, with a space between each character: H W", "thing, for the same reason. Iterating over a list still", "That's because it'll loop over the entire list even if", "a new useful value without changing the original argument. The", "a `for loop`. Here's a program that adds up all", "== list2) print(list1 is list2) list1.append(4) print(list1) print(list2) class same_list(VerbatimStep):", "and `len()` with strings in the shell? Forget loops for", "original argument. The only exception is the `pop` method. Modifying", "string2 = \"World\" print them vertically side by side, with", "the *last* index, not the first one. \"\"\" @returns_stdout def", "new value to the variable: word = word.upper() Or you", "'python' and 'list' in your search query. Instead of putting", "print(big_numbers) The button will open a new tab with a", "[7, 8, 9]`, the other variable will be unaffected and", "`i` will sometimes be too big \" \"to be a", "0), False), ] @classmethod def generate_inputs(cls): contained = random.choice([True, False])", "= numbers[i] if number <= 10: numbers.pop(i) print(numbers) (remember that", "loop iteration for every character in the longer string.\", \"That", "3. You've already seen that `len` and subscripting work with", "error actually comes just from `word.append`, without even a call.", "<= 10: numbers.pop(i) print(numbers) (remember that `numbers.pop(i)` removes the element", "things like \"python list tutorial\", e.g. if: - Googling a", "def program(self): word = 'Hello' word.append('!') final_text = \"\"\" The", "You've already done an exercise like that.\", \"Once you've sorted", "be anything: numbers, strings, booleans, even lists! They can also", "'attribute' in the error message refers to the use of", "strings as an argument. `'--'.join(['apples', 'oranges', 'bananas'])` returns `'apples--oranges--bananas'`. You", "has element - `index` - python get position of element", "problem with lists and you need to go back to", "- `'feed the dog and the cat'.index('the')` is 5 Note", "means you need `range(<length of the longest string>)`\", \"In other", "[1, 2, 3]` to `list2 = list1` and see what", "random.randrange(5, 11) return dict( string1=generate_string(length), string2=generate_string(length), ) class zip_longest_exercise(ExerciseStep): \"\"\"", "thing as argument. It's a bit like you're giving the", "be a valid index for both strings. You will need", "`len(nums)` is `3`. - **`range`**: `range(n)` is an object similar", "a known position. Here's how: __program_indented__ \"\"\" def program(self): words", "element to list - python add item at end of", "It even looks nicer this way. numbers = [10, 7,", "variables can end up pointing to the same list. But", "them out in the shell. - **`subscript assignment`**: Set a", "still confused about lists after this course. - It's been", "again. If you come across this kind of problem and", "True), ((['This', 'is', 'a', 'list'], 'other'), False), (([1, 2, 3,", "while the remaining functions/methods return a new useful value without", "you find the element in the list you should set", "would change to: [1, 2, 3, 4, 5, 9] But", "\"\"\" def program(self): words = ['This', 'is', 'a', 'list'] print(words[0])", "class len_of_none(VerbatimStep): \"\"\" `None` is a special 'null' value which", "a moment. How would you print just the first line,", "1, 5, 9] total = 0 for number in numbers:", "length1 else: length = length2 for i in range(length): if", "== things[i]: answer = i print(answer) tests = [ ((['on',", "these for yourself. So in general, the valid indices are:", "an index is the answer, you will need to use:", "have to assign a new value to the variable: word", "`pop` so we don't have to use indices. It even", "variable that you print at the end. If you find", "Use the words 'python' and 'list' in your search query.", "variables. If you assign a new value to *either* of", "two values \" \"`len(string1)` and `len(string2)`. You've already done an", "\"\"\" # noinspection PyNoneFunctionAssignment def program(self): things = [1, 2,", "\"\"\" hints = \"\"\" Did you experiment with indexing and", "you've earned it! \"\"\" class CallingFunctionsTerminology(Page): title = \"Terminology: Calling", "character of each of the two strings? In the second", "i l z o a b e t h \"\"\"),", "refers to the use of `.` - the error actually", "python add list of numbers - python total of numbers", "code if you want: all_numbers = [2, 4, 8, 1,", "message refers to the use of `.` - the error", "Given two strings of equal length, e.g: string1 = \"Hello\"", "number in numbers: if number <= 10: big_numbers.remove(number) print(big_numbers) Or", "in both `print(list1)` and `print(list2)` because both lines are now", "lists and you need to go back to basics and", "failed so you want to find it manually. - You're", "is `to_find`. For example, for things = ['on', 'the', 'way',", "by element in a for loop. Start with an empty", "A blank initial value? \"\"\" @returns_stdout def solution(self, words: List[str]):", "no_append_for_str(VerbatimStep): \"\"\" Another example is that `append` is a method", "immutable - they don't have any methods like `append` or", "to Google things like \"python list tutorial\", e.g. if: -", "need to pass the same index to both strings each", "the indices under the hood. The lesson here is to", "the middle' or 'at an index' or 'at a particular", "error if the value doesn't exist. Equivalent to `nums.pop(nums.index(10))`. -", "If you come across this kind of problem and you're", "strings instead of numbers. For example, given: words = ['This',", "7 got skipped. We could try writing the program to", "@returns_stdout def solution(self, numbers: List[int]): big_numbers = [] for number", "\"\"\" You will need a loop. You will need an", "d l b d y e \"\"\"), (\"Hello\", \"Elizabeth\"): dedent(\"\"\"\\", "filter_numbers(ExerciseStep): \"\"\" Great! When you want to add a single", "is that 0. You can't add 0 to a string", "a value `to_find`, print the first index of `to_find` in", "0. It seems weird, but that's how most programming languages", "entire list even if it finds the element at the", "a new string which was immediately discarded. If you want", "It loops through a numbers and removes the ones smaller", "' + char2) This doesn't work so well if the", "Fantastic! We're making great progress. \"\"\" class UsingBreak(Page): title =", "happens if you try running that program with a list", "list1 print(list1) print(list2) print(list1 == list2) print(list1 is list2) list1.append(4)", "a `break` statement, like so: for thing in things: if", "64]` - **`sorted`**: Takes an iterable and returns a list", "49])`. Don't solve this manually with a loop. \"\"\" hints", "assign a new value to the variable: word = word.upper()", "do it, and it's generally agreed to be better. This", "the new methods we've learned, not just for characters but", "def program(self): words = ['This', 'is', 'a', 'list'] for word", "8, 2, 10, 18, 4, 12, 10] \"\"\" hints =", "class zip_exercise(ExerciseStep): \"\"\" Nice! By the way, indexing and `len()`", "- types of values which can be mutated are *mutable*,", "class no_append_for_str(VerbatimStep): \"\"\" Another example is that `append` is a", "can ignore for now - scroll to the end of", "2, 6, 5], [6, 2, 8, 2, 10, 18, 4,", "you try getting an index greater than that? \"\"\" program", "that returns the value in a list which is bigger", "character by character. The solution is very similar to the", "ordered collection/container) of any number of values. The values are", "__program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment def program(self): things = [1,", "the 9 to be at the end, you want it", "3, 4], 0), False), ] @classmethod def generate_inputs(cls): contained =", "`sum(nums)` is 6. - **`in`**: A comparison operator that checks", "`[1, 2, 3, 4, 5]`. Here's some new things. Try", "from `numbers` at index `i`) As it runs, it clearly", "number is big enough to add. \"\"\" # TODO enforce", "inside the loop. \"\"\" @returns_stdout def solution(self, things, thing_to_find): found", "print `False`. \"\"\" hints = \"\"\" You will need a", "as `[28, 99, 81, 59, 64]`. Raises an error if", "for i in range(len(things)): if to_find == things[i]: print(i) break", "Did you experiment with indexing and `len()` with strings in", "separate, distinct, individual lists. As a result, when you append", "knowledge, write a program which takes a list of numbers", "= \"\"\" Fantastic! We're making great progress. \"\"\" class UsingBreak(Page):", "least, it tries to. I recommend running it with Python", "you might Google the above functions if you forgot their", "\"Hello\" string2 = \"Elizabeth\" output: H E e l l", "3, 12, 15] big_numbers = numbers.copy() for number in numbers:", "in general, the valid indices are: [0, 1, 2, ...,", "want to change the value that `word` refers to, you", "if it's too big before indexing.\", \"Remember, the biggest valid", "already done a similar thing in an exercise: numbers =", "no similarly easy way to check for a number bigger", "'is', 'a', 'list'] separator = ' - ' it would", "concept among strings to 0? A blank initial value? \"\"\"", "out with equal contents. Similarly, you could loop over the", "recently. You need to use `break`. \"\"\" class all_indices(MessageStep, ExerciseStep):", "] class filter_numbers(ExerciseStep): \"\"\" Great! When you want to add", "if length1 > length2: length = length1 else: length =", "12, 15] for number in numbers: if number <= 10:", "or `print(things)` is a function ***call*** - when you write", "+= @returns_stdout def solution(self, numbers: List[int]): big_numbers = [] for", "it finds the element at the beginning. You can stop", "See for yourself: __program_indented__ \"\"\" def program(self): print(len) print(print) class", "\"\"\" Now modify the program so that it can add", "Here's a program that adds up all the numbers in", "makes. \"\"\" program_in_text = False def program(self): list1 = [1,", "((['This', 'is', 'a', 'list'], 'other'), False), (([1, 2, 3, 4],", "list with the `copy` method: list2 = list1.copy() This will", "called *mutation* - types of values which can be mutated", "in the list `[21, 55, 4, 91, 62, 49]`? 'biggest'", "number <= 10: big_numbers.remove(number) print(big_numbers) Or you could build up", "'yes': \"\"\" class UnderstandingProgramsWithPythonTutor(Page): final_text = \"\"\" It's time to", "click the new \"Python Tutor\" button. Here's some example code", "element. You can use snoop to see the difference. \"\"\"", "in the shell to do that. \"\"\" hints = \"\"\"", "methods which modify a list in place (`append`, `insert`, `remove`)", "code in the editor and then click the new \"Python", "in list - python how many characters in string -", "generate_string() things += [to_find] * random.randint(1, 3) random.shuffle(things) return dict(", "class print_functions(VerbatimStep): \"\"\" It's time to expand your vocabulary some", "3) random.shuffle(things) return dict( things=things, to_find=to_find, ) class zip_exercise(ExerciseStep): \"\"\"", "loop. You will need an `if` statement. You will need", "of value called lists. Here's an example: __program_indented__ \"\"\" def", "instead of: some_list += [element] it's actually more common to", "a list of strings with a separator in between. This", "= 'Hello' print(word.upper) print(word.upper()) class no_append_for_str(VerbatimStep): \"\"\" Another example is", "else: length = length2 for i in range(length): if i", "\"\"\" Good find! Let's do one more. If you have", "indexing.\", \"Remember, the biggest valid index for `string1` is `len(string1)", "You will need to look at all the possible indices", "this stuff, read the essay [Facts and myths about Python", "python add together list of strings with string in between", ") final_text = \"\"\" Magnificent! Take a break, you've earned", "words = ['This', 'is', 'a', 'list'] for index in range(len(words)):", "return anything return `None` by default. If you see an", "build up strings character by character. Make a new list,", "\"\"\" program = \"words[4]\" def check(self): return \"IndexError\" in self.result", "to check if it's too big before indexing.\", \"Remember, the", "being equal, they are still two separate, distinct, individual lists.", "side, with a space between each character: H W e", "it should print `True`, but for thing_to_find = 'other' it", "length = length2 for i in range(length): if i <", "program step by step with the \"Prev\" or \"Next\" buttons,", "returns_stdout class IntroducingLists(Page): class first_list(VerbatimStep): \"\"\" It's time to learn", "Similarly, you could loop over the original and modify a", "the call `len(things)`, `things` is an ***argument***. Sometimes you will", "program(self): print(callable(len)) class not_callable(VerbatimStep): \"\"\" Most things are not callable,", "a single list object. `list2 = list1` doesn't create an", "print(numbers) But it turns out this does the same thing,", "want to find it manually. - You're still confused about", "= list1` doesn't create an eternal link between the variables.", "some of these from your exercises. I assure you that", "some technical details that are often misunderstood and lead to", "are often misunderstood and lead to errors. Run this program:", "' + char2) tests = { (\"Goodbye\", \"World\"): dedent(\"\"\"\\ G", "to explore programs. Put some code in the editor and", "function/method in the shell to do that. \"\"\" hints =", "that `append` is a method of lists. But you can't", "`word.upper()`: __program_indented__ \"\"\" def program(self): word = 'Hello' print(word.upper) print(word.upper())", "the first index, you need to stop the loop once", "list tutorial\", e.g. if: - Googling a specific method has", "12, 15] big_numbers = numbers.copy() for number in numbers: if", "All calls have to return something...even if it's nothing. For", "Run this program: __program_indented__ \"\"\" def program(self): list1 = [1,", "a number bigger than 5. It's useful to know these", "about lists and you need a reminder. - You're struggling", "2, 8, 2, 10, 18, 4, 12, 10]), ([0, 1,", "be a mixture of types. To create a list directly,", "def check(self): return \"IndexError\" in self.result class introducing_len_and_range(VerbatimStep): \"\"\" There", "way to check for a number bigger than 5. It's", "create an empty list that has no elements. Check for", "\"\"\" Nice! A typical solution looks something like this: found", "is great, but often you just want to retrieve a", "if an index is the answer, you will need to", "`len`. You will need `+`. You will need to index", "understanding this stuff, read the essay [Facts and myths about", "are ***functions***. See for yourself: __program_indented__ \"\"\" def program(self): print(len)", "functions, but it's not easy to learn them all, and", "similar to the programs you've written to build up strings", "and `len(string2)`. You've already done an exercise like that.\", \"Once", "number print(total) class strings_sum(ExerciseStep): \"\"\" Now modify the program so", "which case we say that `len` ***returned*** 3. All calls", "- You're struggling to solve a problem with lists and", "6, 5], [9, 6]), ([0, 2, 4, 6, 8, 10],", "once you set the variable to `True`, it should never", "1, 4, 1, 5, 9, 2, 6, 5], [6, 2,", "'the', 'way', 'to', 'the', 'store'] to_find = 'the' your program", "`n - 1`. In particular, `range(len(nums))` is like `[0, 1,", "to stop a loop in the middle recently. You need", "You can also use an empty string if you don't", "you can iterate over them with a `for loop`. Here's", "powerful new type of value called lists. Here's an example:", "strings, which are called with e.g. `word.upper()`: __program_indented__ \"\"\" def", "the list to `[1, 2, 3, 4]`. - **`len`**: Returns", "strings each time to retrieve matching characters. \"\"\" @returns_stdout def", "3, 2, 7, 2, 5].count(2)` is 3. You've already seen", "len_of_none(VerbatimStep): \"\"\" `None` is a special 'null' value which can't", "def program(self): x = 1 things = ['Hello', x, x", "things, to_find): for i in range(len(things)): if to_find == things[i]:", "any googling. Try `__program__` in the shell. \"\"\" program =", "list by adding a list containing one element. \"\"\" @returns_stdout", "button. Here's some example code if you want: all_numbers =", "stop any loop using a `break` statement, like so: for", "\"words[4]\" def check(self): return \"IndexError\" in self.result class introducing_len_and_range(VerbatimStep): \"\"\"", "- python size of list - python number of elements", "**`range`**: `range(n)` is an object similar to the list of", "you can't unfind it. That means that once you set", "\"\"\" A list is a *sequence* (an ordered collection/container) of", "r l l o d \"\"\" hints = \"\"\" Did", "`append` is a method of lists. But you can't use", "pass the same index to both strings each time to", "i in range(len(string1)): char1 = string1[i] char2 = string2[i] print(char1", "the cat'.count('the')` is 2 - `'feed the dog and the", "class FunctionsAndMethodsForLists(Page): # TODO this is quite the information dump", "[4, 5]` is `[1, 2, 3, 4, 5]`. Here's some", "numbers = [3, 1, 4, 1, 5, 9, 2, 6,", "`nums[3]` (`81`) from the list and returns it. Without an", "word = 'Hello' word.append('!') final_text = \"\"\" The word 'attribute'", "return \"IndexError\" in self.result class introducing_len_and_range(VerbatimStep): \"\"\" There you go.", "- `'feed the dog and the cat'.count('the')` is 2 -", "to_find): answer = None for i in range(len(things)): if to_find", "middle' or 'at an index' or 'at a particular position'", "`list2 = [1, 2, 3]` to `list2 = list1` and", "this problem by filling in 'missing' characters with spaces. For", "happens if you try getting an index greater than that?", "test if a number is big enough to add. \"\"\"", "with a space between each character: H W e o", "length2 = len(string2) if length1 > length2: length = length1", "break, you've earned it! \"\"\" class CallingFunctionsTerminology(Page): title = \"Terminology:", "you that those exercises were not pointless, as you've now", "write `nums.append(9)` and `nums` would change to: [1, 2, 3,", "'is', 'a', 'list'] thing_to_find = 'is' it should print `True`,", "python check if list contains value - python test if", "[0, 2, 4, 6]), ] class filter_numbers(ExerciseStep): \"\"\" Great! When", "found = True break This is just as correct but", "search query. In one word, what's special about `91` in", "and you'll see some familiar methods. Here are a few", "I recommend running both versions with Python Tutor to see", "e l l i l z o a b e", "The word 'attribute' in the error message refers to the", "`i` runs through the usual values 0, 1, 2, ...", "[ ((['on', 'the', 'way', 'to', 'the', 'store'], 'the'), \"1\\n4\"), (([0,", "answer = i print(answer) tests = [ ((['on', 'the', 'way',", "element - python get index of value Let's practice this", "strings to 0? A blank initial value? \"\"\" @returns_stdout def", "to access an index that's too high. Can you see", "open a new tab with a visualisation from [pythontutor.com](http://pythontutor.com). There", "if a value is in a list. `2 in nums`", "thing_to_find=thing_to_find, ) final_text = \"\"\" Nice! A typical solution looks", "exercises you've done building up strings character by character. The", "(\"Having\", \"ablast\"): dedent(\"\"\"\\ H a a b v l i", "output: This - is - a - list Lists and", "on all values of that type using `.`. For example,", "with the \"Prev\" or \"Next\" buttons, or drag the slider", "error. By the way, you can get the number of", "now. Find a function/method that returns the value in a", "the program behave like the first version again. If you", "`append` or even subscript assignment. You simply can't change a", "length = len(things) printed = print(length) print(printed) class len_of_none(VerbatimStep): \"\"\"", "names: - `append` - python add element to list -", "putting the value at the beginning or end, we want", "= length2 for i in range(length): if i < len(string1):", "lists to combine them together into a new list. You", "together into a new list. You can also create an", "\"\"\" hints = \"\"\" You will need to look at", "+ [3, 4] print(numbers) new_numbers = [] new_numbers += numbers", "and `list2` both refer to that same list. `list1.append(4)` appends", "However, this prints the *last* index, not the first one.", "6], 6), \"6\\n7\"), ] class last_index(MessageStep, ExerciseStep): \"\"\" You're almost", "*there is only one list*, and the two variables `list1`", "the first iteration `i` is 0 and `number` is 10,", "list even if it finds the element at the beginning.", "before indexing.\", \"Remember, the biggest valid index for `string1` is", "string, and so on. You will need a `for` loop.", "list2) list1.append(4) print(list1) print(list2) class same_list(VerbatimStep): \"\"\" This program is", "new_numbers += [5] print(new_numbers) With that knowledge, write a program", "argument to the function - specifically we say that the", "that those exercises were not pointless, as you've now learned", "Make a new list, and then build it up element", "the variable to `False` inside the loop. \"\"\" @returns_stdout def", "] @classmethod def generate_inputs(cls): contained = random.choice([True, False]) things =", "assignment. You simply can't change a string - you can", "can also be useful to Google things like \"python list", "last valid index of the list is `len(words) - 1`,", "and looping separate. The good news is that there are", "than any other value. For example, given the list `[21,", "be set to anything else after that. Don't use an", "That means that this is a useless statement on its", "difference. \"\"\" class GettingElementsAtPosition(Page): title = \"Getting Elements at a", "nums` is `True`, but `4 in nums` is `False`. -", "a powerful new type of value called lists. Here's an", "in the middle recently. You need to use `break`. \"\"\"", "need to check if it's too big before indexing.\", \"Remember,", "\"\"\" The word 'attribute' in the error message refers to", "`.` - the error actually comes just from `word.append`, without", "numbers bigger than 5. For example, given: numbers = [3,", "for each string.\", \"You will need to set e.g. `char1", "***callable***: __program_indented__ \"\"\" def program(self): print(callable(len)) class not_callable(VerbatimStep): \"\"\" Most", "a loop in the middle recently. You need to use", "\" \"but it's significantly longer and will require \" \"a", "9, 3, 4, 5] Call the right function/method in the", "us an alternative way to loop over a list: __program_indented__", "dog and the cat'.index('the')` is 5 Note that in most", "the editor and then click the new \"Python Tutor\" button.", "comparison operator: `is`. Here `list1 is list2` is `False`. That", "ignore for now - scroll to the end of the", "don't have to use indices. It even looks nicer this", "takes an iterable of strings as an argument. `'--'.join(['apples', 'oranges',", "structurally very similar to the programs you've written to build", "class IntroducingLists(Page): class first_list(VerbatimStep): \"\"\" It's time to learn about", "things[i]: print(i) tests = [ ((['on', 'the', 'way', 'to', 'the',", "giving the argument to the function - specifically we say", "of characters. Strings also support some of the new methods", "'is', 'a', 'list'] for word in words: print(word) class can_contain_anything(VerbatimStep):", "having trouble understanding this stuff, read the essay [Facts and", "as in: for number in numbers.copy(): Now the list being", "is an ***argument***. Sometimes you will also see the word", "*indexing*, and the position is called the *index*. You've probably", "For example, if you were looking for the function `sum`,", "iterable and returns a list of the elements in order.", "first one. \"\"\" @returns_stdout def solution(self, things, to_find): answer =", "things=things, to_find=to_find, ) class zip_exercise(ExerciseStep): \"\"\" Nice! By the way,", "is good enough.\", \"You want a loop iteration for every", "return dict( string1=generate_string(length1), string2=generate_string(length2), ) final_text = \"\"\" Magnificent! Take", "program is quite straightforward and mostly consists of things you're", "enough to add. \"\"\" # TODO enforce not using +=", "of `to_find` in the list, i.e. the lowest number `i`", "return a new useful value without changing the original argument.", "an ***argument***. Sometimes you will also see the word ***parameter***,", "but for thing_to_find = 'other' it should print `False`. \"\"\"", "need to stop the loop once you find one. You", "to use: - `if` - the index in a subscript", "If you assign a new value to *either* of the", "'is', 'a', 'list'] it should print: Thisisalist \"\"\" hints =", "4] print(numbers) new_numbers = [] new_numbers += numbers new_numbers +=", "in the list, i.e. the lowest number `i` such that", "assignment`**: Set a value at an index. `nums[0] = 9`", "`for` loop. You will need indexing (subscripting). You will need", "2, 3, 4, 5, 6, 6], 6), 6), ] @classmethod", "space between each character: H W e o l r", "you an error: __program_indented__ \"\"\" # noinspection PyCallingNonCallable def program(self):", "can_contain_anything(VerbatimStep): \"\"\" A list is a *sequence* (an ordered collection/container)", "like so: for thing in things: if thing == thing_to_find:", "you want it to go between the second and third", "elements in a list (commonly called the *length*) using `len(words)`.", "to list - python add item at end of list", "'at an index' or 'at a particular position' 'python add", "gets removed. This shifts the rest of the numbers left", "use snoop to see the difference. \"\"\" class GettingElementsAtPosition(Page): title", "are a few more useful functions/methods. Suppose `nums = [28,", "= [] for number in numbers: if number > 10:", "`char1 = ' '` when `string1[i]` is not valid.\", ]", "make a list with one element `x` by just writing", "lists after this course. - It's been a while since", "just want to retrieve a single element from the list", "You will need `range`. You will need `len`. You will", "Let's practice this skill now. Find a function/method that returns", "some familiar methods. Here are a few more useful functions/methods.", "big_numbers.append(number) print(big_numbers) tests = [ ([3, 1, 4, 1, 5,", "\"\"\" hints = \"\"\" Use the words 'python' and 'list'", "<= 10: numbers.remove(number) print(numbers) But it turns out this does", "program(self): words = ['This', 'is', 'a', 'list'] for word in", "need to use `break`. \"\"\" class all_indices(MessageStep, ExerciseStep): \"\"\" You're", "methods we've learned, not just for characters but for any", "biggest of the two values \" \"`len(string1)` and `len(string2)`. You've", "= generate_string() things += [to_find] * random.randint(1, 3) random.shuffle(things) return", "can instead just loop over a copy, as in: for", "last index in this list of 4 elements is 3.", "program which prints a list containing only the numbers bigger", "and beyond don't exist, so trying that will give you", "any substring. For example: - `'the' in 'feed the dog", "for the first index, you need to stop the loop", "in a list which is bigger than any other value.", "i in range(len(things)): if to_find == things[i]: print(i) tests =", "this is possible means that functions are ***callable***: __program_indented__ \"\"\"", "`[21, 55, 4, 91, 62, 49]`, it will return `91`.", "55, 4, 91, 62, 49]`, it will return `91`. You", "They can be anything: numbers, strings, booleans, even lists! They", "which is bigger than any other value. For example, given", "\"1\\n4\"), (([0, 1, 2, 3, 4, 5, 6, 6], 6),", "is a function which belongs to a type, and can", "H W e o l r l l o d", "use `.upper` on a list or `.append` on a string:", "Once you've found the element, you can't unfind it. That", "iterate over them with a `for loop`. Here's a program", "' + char2) tests = { (\"Hello\", \"World\"): dedent(\"\"\"\\ H", "single element from the list at a known position. Here's", "return search_ast( self.stmt, ast.Call(func=ast.Name(id='max')), ) class list_insert(Step): \"\"\" Good find!", "end, you want it to go between the second and", "7, 8, 3, 12, 15] big_numbers = numbers.copy() for number", "([0, 1, 2, 3], [0, 2, 4, 6]), ] class", "= { (\"Goodbye\", \"World\"): dedent(\"\"\"\\ G W o o o", "value is in a list. `2 in nums` is `True`,", "a list: __program_indented__ \"\"\" def program(self): x = 1 things", "= \"World\" output: G W o o o r d", "a type, and can be called on all values of", "program should print `1`. You can assume that `to_find` appears", "the words 'python' and 'list' in your search query. Instead", "list - python how many characters in string - `join`", "program(self): list1 = [1, 2, 3] list2 = [1, 2,", "6] \"\"\" hints = \"\"\" This is very similar to", "For example, given: things = ['This', 'is', 'a', 'list'] thing_to_find", "for both strings. You will need to check if it's", "break tests = [ ((['on', 'the', 'way', 'to', 'the', 'store'],", "[6, 8, 10]), ] final_text = \"\"\" Fantastic! We're making", "(the separator) which takes an iterable of strings as an", "list changes those are no longer the positions we want.", "in an exercise: numbers = [10, 7, 8, 3, 12,", "you can navigate through the program step by step with", "Concatenates lists. `nums + [4, 5]` is `[1, 2, 3,", "you these values, called `range`: __program_indented__ \"\"\" def program(self): for", "2, 3, 4, 5] You could write `nums.append(9)` and `nums`", "operation is called *subscripting* or *indexing*, and the position is", "and removes the ones smaller than 10. Or at least,", "contained: thing_to_find = random.choice(things) else: thing_to_find = random.choice([ min(things) -", "specifically we say that the argument `things` is *passed* to", "learn about another tool to explore programs. Put some code", "few additional ideas and pieces.\", dedent(\"\"\" In particular, it should", "it tries to access an index that's too high. Can", "\"World\" output: G W o o o r d l", "4 elements is 3. What happens if you try getting", "similarly easy way to check for a number bigger than", "separator - python add together list of strings with string", "index in this list of 4 elements is 3. What", "0. But then in the next iteration `i` is 1,", "and you need to go back to basics and strengthen", "the essay [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html).", "go back to basics and strengthen your foundations. There are", "in self.result class introducing_len_and_range(VerbatimStep): \"\"\" There you go. `words[4]` and", "now learned valuable fundamental skills. For example, you can use", "use `break`. \"\"\" class all_indices(MessageStep, ExerciseStep): \"\"\" You're almost there!", "'to', 'the', 'store'] to_find = 'the' your program should print", "errors. Run this program: __program_indented__ \"\"\" def program(self): list1 =", "of numbers - python total of numbers - `in` -", "just as correct but skips unnecessary iterations and checks once", "to the end of a list, instead of: some_list +=", "((['on', 'the', 'way', 'to', 'the', 'store'], 'the'), \"1\\n4\"), (([0, 1,", "string referred to by `word` isn't modified, instead `word.upper()` returned", "and returns it. Without an argument, i.e. just `nums.pop()`, it", "if to_find == things[i]: print(i) tests = [ ((['on', 'the',", "**`pop`**: Removes and returns an element at a given index.", "substring. For example: - `'the' in 'feed the dog and", "you've written to build up strings character by character. Make", "by filling in 'missing' characters with spaces. For example, for:", "you don't want an empty list, write some expressions inside", "word ***parameter***, which means basically the same thing as argument.", "separator in between. This is a method of strings (the", "the original and modify a copy: numbers = [10, 7,", "string>)`\", \"In other words you need to find the biggest", "\"\"\" Let's review how to work with lists. Suppose we", "for a moment. How would you print just the first", "called *subscripting* or *indexing*, and the position is called the", "anything: numbers, strings, booleans, even lists! They can also be", "and 'list' in your search query. Instead of putting the", "you'll see some familiar methods. Here are a few more", "Put some code in the editor and then click the", "strings in the shell? Forget loops for a moment. How", "don't want to return anything return `None` by default. If", "\"Using `break` to end a loop early\" class list_contains_exercise(ExerciseStep): \"\"\"", "'is', 'a', 'list'], 'other'), False), (([1, 2, 3, 4], 1),", "'quick', 'brown', 'fox', 'jumps'], 'Thequickbrownfoxjumps'), ] class double_numbers(ExerciseStep): \"\"\" Optional", "to test if a number is big enough to add.", "but for any substring. For example: - `'the' in 'feed", "the program to use `remove` instead of `pop` so we", "string2 = \"World\" output: G W o o o r", "(['The', 'quick', 'brown', 'fox', 'jumps'], 'Thequickbrownfoxjumps'), ] class double_numbers(ExerciseStep): \"\"\"", "instead just loop over a copy, as in: for number", "`upper` and `lower` are methods of strings, which are called", "list. Basically, an assignment like: list2 = <expression> means 'make", "2, `nums[2]` is 3. - **`+`**: Concatenates lists. `nums +", "== thing_to_find: found = True print(found) tests = [ ((['This',", "right. You can also see the values of variables on", "***argument***. Sometimes you will also see the word ***parameter***, which", "a list and a value and checks if the list", "`append` - python add element to list - python add", "how to work with lists. Suppose we have a list", "blank initial value? \"\"\" @returns_stdout def solution(self, words: List[str]): total", "main.text import ExerciseStep, MessageStep, Page, Step, VerbatimStep, search_ast from main.utils", "in numbers.copy(): Now the list being modified and the list", "5], [9, 6]), ([0, 2, 4, 6, 8, 10], [6,", "straightforward and mostly consists of things you're familiar with. We", "moment. How would you print just the first line, which", "8, 9, 8].index(8)` is 1. Raises an error if the", "the elements in order. `sorted(nums)` returns `[10, 28, 59, 64,", "As a result, when you append 4 to `list1`, only", "'the'), \"1\\n4\"), (([0, 1, 2, 3, 4, 5, 6, 6],", "python get index of value Let's practice this skill now.", "***functions***. See for yourself: __program_indented__ \"\"\" def program(self): print(len) print(print)", "between the second and third elements: [1, 2, 9, 3,", "string1[i] char2 = string2[i] print(char1 + ' ' + char2)", "so well if the strings have different lengths. In fact,", "don't want the 9 to be at the end, you", "to know these functions off by heart. class sum_list(Step): \"\"\"", "ast.Call(func=ast.Attribute(attr='insert'), args=[ast.Constant(value=2), ast.Constant(value=9)]), ) class dir_list(VerbatimStep): \"\"\" Perfect! It can", "if thing == thing_to_find: found = True print(found) Your solution", "small_numbers = [] big_numbers = [] for number in all_numbers:", "separate. The good news is that there are many ways", "+ ' ' + char2) tests = { (\"Goodbye\", \"World\"):", "new type of value called lists. Here's an example: __program_indented__", "new useful value without changing the original argument. The only", "list `nums = [1, 2, 3]`. You can use: -", "can add an element to a list by adding a", "be more familiar and readable to most people. Now use", "class methods_of_str(VerbatimStep): \"\"\" A ***method*** is a function which belongs", "looking at 7 or 3 and doesn't remove them, and", "print(printed) class len_of_none(VerbatimStep): \"\"\" `None` is a special 'null' value", "dedent(\"\"\"\\ H a a b v l i a n", "if number <= 10: big_numbers.remove(number) print(big_numbers) Or you could build", "[1, 2, 3] print(list1) print(list2) print(list1 == list2) print(list1 is", "== 'yes': \"\"\" class UnderstandingProgramsWithPythonTutor(Page): final_text = \"\"\" It's time", "for i in range(10): print(i) class range_len(VerbatimStep): \"\"\" `range(n)` is", "remove and return the last element. - **`remove`**: Removes the", "is list2` is `False`. That means that regardless of the", "You should write the answer in the shell as a", "that knowledge, write a program which takes a list of", "previous solution, \" \"but it's significantly longer and will require", "instead: __program_indented__ \"\"\" # noinspection PyNoneFunctionAssignment def program(self): things =", "a bit as if strings are lists of characters. Strings", "random.shuffle(things) return dict( things=things, to_find=to_find, ) class zip_exercise(ExerciseStep): \"\"\" Nice!", "the list is `len(words) - 1`, so the last element", "your search query. Instead of putting the value at the", "have the same elements, so they are equal: `list1 ==", "- 1`. \" \"`len(string)` is too big.\", \"You will need", "8, 9]`, the other variable will be unaffected and will", "for a number bigger than 5. It's useful to know", "right. \"\"\" class EqualsVsIs(Page): title = \"`==` vs `is`\" class", "***calling*** the function `len` or `print`. The fact that this", "None for i in range(len(things)): if to_find == things[i]: answer", "function which belongs to a type, and can be called", "bit as if strings are lists of characters. Strings also", "8].index(8)` is 1. Raises an error if the value isn't", "referred to by `word` isn't modified, instead `word.upper()` returned a", "then there's a new comparison operator: `is`. Here `list1 is", "if list contains value - python test if list has", "program(self): f = 'a string' print(callable(f)) f() class print_returns_none(VerbatimStep): \"\"\"", "of making a list: __program_indented__ \"\"\" def program(self): x =", "you see why this happens? The index variable `i` runs", "There's a handy built in function to give you these", "using += @returns_stdout def solution(self, numbers: List[int]): big_numbers = []", "can also create an empty list that has no elements.", "most people. Now use `.append` to write a program which", "runs, it clearly skips even looking at 7 or 3", "all_numbers = [2, 4, 8, 1, 9, 7] small_numbers =", "random.choice([ min(things) - 1, max(things) + 1, ]) return dict(", "from main.exercises import generate_list, generate_string from main.text import ExerciseStep, MessageStep,", "`list2` both refer to that same list. `list1.append(4)` appends to", "in numbers: total += number print(total) class strings_sum(ExerciseStep): \"\"\" Now", "commas (`,`) between elements to separate them. Here's another example", "a list or `.append` on a string: __program_indented__ \"\"\" #", "change a string - you can only create new strings", "incompatible. Is there a similar concept among strings to 0?", "variable `i` runs through the usual values 0, 1, 2,", "counting starts at 0. It seems weird, but that's how", "It's time to learn about a powerful new type of", "will need to index both strings. You will need to", "+ char2) \"\"\"), \"What should go inside `range()`? Neither `len(string1)`", "lead to errors. Run this program: __program_indented__ \"\"\" def program(self):", "have a list: nums = [1, 2, 3, 4, 5]", "In this case, we've already done a similar thing in", "\"\"\" class GettingElementsAtPosition(Page): title = \"Getting Elements at a Position\"", "example, given: words = ['This', 'is', 'a', 'list'] it should", "are called with e.g. `word.upper()`: __program_indented__ \"\"\" def program(self): word", "will need to check if it's too big before indexing.\",", "exercise. Given two strings of equal length, e.g: string1 =", "new list. You can also create an empty list that", "= string2[i] print(char1 + ' ' + char2) tests =", "class GettingElementsAtPosition(Page): title = \"Getting Elements at a Position\" class", "only exception is the `pop` method. Modifying a value directly", "2, 10, 18, 4, 12, 10] \"\"\" hints = \"\"\"", "= ['This', 'is', 'a', 'list'] separator = ' - '", "variable to `True`, it should never be set to anything", "operator: `is`. Here `list1 is list2` is `False`. That means", "you have to assign a new value to the variable:", "e.g. if: - Googling a specific method has failed so", "`sum`, you could write `sum([21, 55, 4, 91, 62, 49])`.", "3] length = len(things) printed = print(length) print(printed) class len_of_none(VerbatimStep):", "r l l o d \"\"\"), (\"Having\", \"ablast\"): dedent(\"\"\"\\ H", "' - ' it would output: This - is -", "words = ['This', 'is', 'a', 'list'] for word in words:", "adds numbers. In fact, what happens if you try running", "things=things, thing_to_find=thing_to_find, ) final_text = \"\"\" Nice! A typical solution", "... print(char1 + ' ' + char2) \"\"\"), \"What should", "min(things) - 1, max(things) + 1, ]) return dict( things=things,", "things = generate_list(int) if contained: thing_to_find = random.choice(things) else: thing_to_find", "+= number print(total) class strings_sum(ExerciseStep): \"\"\" Now modify the program", "a program which prints a list containing only the numbers", "3, 4, 5, 6, 6], 6), 6), ] @classmethod def", "with Python Tutor to see how it visualises the difference.", "\"\"\" You will need to look at all the possible", "= string1[i] char2 = string2[i] print(char1 + ' ' +", "'is', 'a', 'list'], 'is'), True), ((['This', 'is', 'a', 'list'], 'other'),", "a list. `[7, 8, 9, 8].index(8)` is 1. Raises an", "3, 4, 5, 6, 6], 6), \"6\\n7\"), ] class last_index(MessageStep,", "word.lower() == 'yes': \"\"\" class UnderstandingProgramsWithPythonTutor(Page): final_text = \"\"\" It's", "comes just from `word.append`, without even a call. \"\"\" class", "y e \"\"\"), (\"Hello\", \"Elizabeth\"): dedent(\"\"\"\\ H E e l", "program to insert a separator string *between* each word. For", "`to_find` in the list, i.e. the lowest number `i` such", "value directly is called *mutation* - types of values which", "if contained: thing_to_find = random.choice(things) else: thing_to_find = random.choice([ min(things)", "at 0. It seems weird, but that's how most programming", "the given element. `nums.remove(10)` will leave `nums` as `[28, 99,", "you will need to use: - `if` - the index", "7, 8, 3, 12, 15] for number in numbers: if", "make the program behave like the first version again. If", "`for i in range(...)`, `i` will sometimes be too big", "generate_list, generate_string from main.text import ExerciseStep, MessageStep, Page, Step, VerbatimStep,", "object. `list2 = list1` doesn't create an eternal link between", "finds the element. You can use snoop to see the", "list2 = list1.copy() This will make the program behave like", "`False`. \"\"\" hints = \"\"\" You will need a loop.", "\"\"\" It's time to expand your vocabulary some more. `print`", "solve this. You can instead just loop over a copy,", "I assure you that those exercises were not pointless, as", "program(self): things = print([1, 2, 3]) length = len(things) class", "this. You can instead just loop over a copy, as", "10. Or at least, it tries to. I recommend running", "to most people. Now use `.append` to write a program", "= [10, 7, 8, 3, 12, 15] big_numbers = []", "over `range(len(things))`. To check if an index is the answer,", "them will give you an error: __program_indented__ \"\"\" # noinspection", "and use those instead. That means that this is a", "element at the position `i` with `words[i]`. The operation is", "interesting. It's a common placeholder that represents the lack of", "append 4 to `list1`, only `list1` changes. Now change `list2", "= ' ' if i < len(string2): char2 = string2[i]", "the first line, which has the first character of each", "overall structure and \" \"essential elements of the previous solution,", "over a list: __program_indented__ \"\"\" def program(self): words = ['This',", "only `list1` changes. Now change `list2 = [1, 2, 3]`", "[9, 6]), ([0, 2, 4, 6, 8, 10], [6, 8,", "just the first line, which has the first character of", "a lot in common. For example, you can add two", "answer in the shell as a single small expression. For", "end of a list, instead of: some_list += [element] it's", "is big enough to add. \"\"\" # TODO enforce not", "each word. For example, given words = ['This', 'is', 'a',", "r d l b d y e and for: string1", "W e o l r l l o d \"\"\"),", "an example: __program_indented__ \"\"\" def program(self): words = ['This', 'is',", "print(numbers) new_numbers = [] new_numbers += numbers new_numbers += [5]", "copy: numbers = [10, 7, 8, 3, 12, 15] big_numbers", "very similar to the exercises you've done building up strings", "o o o r d l b d y e", "by character. Make a new list, and then build it", "\" \"to be a valid index for both strings. You", "\"\"\" `range(n)` is similar to the list `[0, 1, 2,", "0, 1, 2, ... as it's supposed to, but as", "2, 3, 4, 5, 6, 6], 6), \"6\\n7\"), ] class", "even lists! They can also be a mixture of types.", "4, 8, 1, 9, 7] small_numbers = [] big_numbers =", "[1, 2, 3, 4, 5] You could write `nums.append(9)` and", "numbers and prints a list where each number has been", "can use `word.upper()` immediately in a larger expression, e.g. if", "`len(things)` will evaluate to a number such as 3, in", "TODO catch user writing string1 < string2 @returns_stdout def solution(self,", "b d y e and for: string1 = \"Hello\" string2", "4, 91, 62, 49]`, it will return `91`. You should", "second case, the two variables both have arrows pointing to", "attributes, which are mostly methods. Many will start with `__`", ") class dir_list(VerbatimStep): \"\"\" Perfect! It can also be useful", "a comparison operator. Specifically `==`. You need a boolean variable", "an index greater than that? \"\"\" program = \"words[4]\" def", "print(words[2]) print(words[3]) class index_error(Step): \"\"\" In general, you can get", "element. - **`remove`**: Removes the first occurrence of the given", "= ['This', 'is', 'a', 'list'] thing_to_find = 'is' it should", "The lesson here is to ***never modify something while you", "appears at least once. \"\"\" hints = \"\"\" You will", "if you want: all_numbers = [2, 4, 8, 1, 9,", "((['on', 'the', 'way', 'to', 'the', 'store'], 'the'), 1), (([0, 1,", "elements in order. `sorted(nums)` returns `[10, 28, 59, 64, 81,", "= list1` and see what difference it makes. \"\"\" program_in_text", "it! \"\"\" class CallingFunctionsTerminology(Page): title = \"Terminology: Calling functions and", "`len(things)` or `print(things)` is a function ***call*** - when you", "could build up a new list from scratch. In this", "Note that in most cases, methods which modify a list", "The problem is that 0. You can't add 0 to", "actually comes just from `word.append`, without even a call. \"\"\"", "- **`len`**: Returns the number of elements. `len(nums)` is `3`.", "can't are *immutable*. Strings are immutable - they don't have", "word 'attribute' in the error message refers to the use", "2, 3] list2 = [1, 2, 3] print(list1) print(list2) print(list1", "\"\"\" program = \"dir([])\" final_text = \"\"\" `dir()` returns a", "string' print(callable(f)) f() class print_returns_none(VerbatimStep): \"\"\" In the call `len(things)`,", "`list1 == list2` is `True`. But then there's a new", "of the list. `nums.append(4)` changes the list to `[1, 2,", "PyNoneFunctionAssignment def program(self): things = [1, 2, 3] length =", "and a value and checks if the list contains the", "numbers and strings are incompatible. Is there a similar concept", "a similar concept among strings to 0? A blank initial", "`sum([21, 55, 4, 91, 62, 49])`. Don't solve this manually", "will need two `if` statements, one for each string.\", \"You", "rest of the numbers left one position, so now 7", "drag the slider left or right. You can also see", "has been doubled. For example, given: numbers = [3, 1,", "through the indices under the hood. The lesson here is", "can also be a mixture of types. To create a", "the variables. If you assign a new value to *either*", "first index of a value in a list. `[7, 8,", "modify the program so that it can add up a", "def program(self): for i in range(10): print(i) class range_len(VerbatimStep): \"\"\"", "function `len` or `print`. The fact that this is possible", "about `91` in the list `[21, 55, 4, 91, 62,", "other variable will be unaffected and will still point to", "separate objects, even if they start out with equal contents.", "called lists. Here's an example: __program_indented__ \"\"\" def program(self): words", "= \"Goodbye\" string2 = \"World\" output: G W o o", "o a b e t h \"\"\"), } @classmethod def", "'list'], 'is'), True), ((['This', 'is', 'a', 'list'], 'other'), False), (([1,", "8, 10], [6, 8, 10]), ] final_text = \"\"\" Fantastic!", "weird, but that's how most programming languages do it, and", "18, 4, 12, 10]), ([0, 1, 2, 3], [0, 2,", "on a string: __program_indented__ \"\"\" # noinspection PyUnresolvedReferences def program(self):", "you can't use `.upper` on a list or `.append` on", "to ever set the variable to `False` inside the loop.", "hints = \"\"\" Did you experiment with indexing and `len()`", "49]`, it will return `91`. You should write the answer", "go. `words[4]` and beyond don't exist, so trying that will", "then click the new \"Python Tutor\" button. Here's some example", "dedent(\"\"\" In particular, it should still contain something like: for", "That means that once you set the variable to `True`,", "for: string1 = \"Goodbye\" string2 = \"World\" output: G W", "if random.choice([True, False]): length1, length2 = length2, length1 return dict(", "- **`in`**: A comparison operator that checks if a value", "indices, not just the first one. \"\"\" @returns_stdout def solution(self,", "a list still goes through the indices under the hood.", "need to set e.g. `char1 = ' '` when `string1[i]`", "catch user writing string1 < string2 @returns_stdout def solution(self, string1,", "one is the answer. To look at all possible indices,", "range(len(things)): if to_find == things[i]: print(i) break tests = [", "iterations and checks once it finds the element. You can", "you can use `word.upper()` immediately in a larger expression, e.g.", "and for: string1 = \"Hello\" string2 = \"Elizabeth\" output: H", "`*`. This program is structurally very similar to the programs", "example, here are some typical ways you might Google the", "numbers.copy() for number in numbers: if number <= 10: big_numbers.remove(number)", "of values. The values are often referred to as *elements*.", "= \"nums.insert(2, 9)\" def check(self): return search_ast( self.stmt, ast.Call(func=ast.Attribute(attr='insert'), args=[ast.Constant(value=2),", "to the program that adds numbers. In fact, what happens", "= numbers.copy() for number in numbers: if number <= 10:", "at 7 or 3 and doesn't remove them, and at", "for every character in the longer string.\", \"That means you", "list that has no elements. Check for yourself: numbers =", "string *between* each word. For example, given words = ['This',", "where each number has been doubled. For example, given: numbers", "number of times the argument appears in the list. `[1,", "import List from main.exercises import generate_list, generate_string from main.text import", "with lists and you need to go back to basics", "> length2: length = length1 else: length = length2 for", "`nums.pop()`, it will remove and return the last element. -", "2, 6, 5] it would print: [9, 6] \"\"\" hints", "[5] print(new_numbers) With that knowledge, write a program which takes", "'to', 'the', 'store'], 'the'), 1), (([0, 1, 2, 3, 4,", "number of values. The values are often referred to as", "add an element to a list by adding a list", "strengthen your foundations. There are also ways to find information", "list to `[1, 2, 3, 4]`. - **`len`**: Returns the", "not the first one. \"\"\" @returns_stdout def solution(self, things, to_find):", "is 0, not 1. In programming, counting starts at 0.", "before, `list2` doesn't remember `<expression>`, only the value. It doesn't", "write some expressions inside to be the elements. 3. Put", "[Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html). \"\"\" class", "learn them all, and there's many more. A more important", "program(self): things = [1, 2, 3] length = len(things) printed", "the argument to the function - specifically we say that", "one element. \"\"\" @returns_stdout def solution(self, numbers: List[int]): double =", "string1[i] else: char1 = ' ' if i < len(string2):", "from [pythontutor.com](http://pythontutor.com). There you can navigate through the program step", "any other value. For example, given the list `[21, 55,", "and pieces.\", dedent(\"\"\" In particular, it should still contain something", "after this course. - It's been a while since you", "`+`. You will need to index both strings. You will", "to_find = 'the' your program should print `1`. You can", "and `nums` would change to: [1, 2, 3, 4, 5,", "return `None`, while the remaining functions/methods return a new useful", "1. Raises an error if the value isn't there. You", "9, 7] small_numbers = [] big_numbers = [] for number", "3]` to `list2 = list1` and see what difference it", "The fact that this is possible means that functions are", "the program step by step with the \"Prev\" or \"Next\"", "modified and the list being itererated over are separate objects,", "number bigger than 5. It's useful to know these functions,", "runs through the usual values 0, 1, 2, ... as", "the first one. \"\"\" @returns_stdout def solution(self, things, to_find): answer", "that adds numbers. In fact, what happens if you try" ]
[ "argparse \"\"\" Follows the StackExchange best practice for creating a", "push a task and publish a message that a task", "\"--port\", help=\"redis server port (default is 6379)\", type=int, default=6379) args", "= parser.parse_args() if args.queue is None or args.task is None", "import json import argparse \"\"\" Follows the StackExchange best practice", "args.server is None: parser.print_help() else: client=redis.StrictRedis(host=args.server, args.port) PushTask(client, args.queue, args.task,", "= argparse.ArgumentParser() parser.add_argument(\"-q\", \"--queue\", help=\"The queue from which workers will", "or args.task is None or args.topic is None or args.server", "type=int, default=6379) args = parser.parse_args() if args.queue is None or", "task, topic): client.lpush(queue, task) client.publish(topic, queue) if __name__ == \"__main__\":", "help=\"redis server port (default is 6379)\", type=int, default=6379) args =", "None or args.server is None: parser.print_help() else: client=redis.StrictRedis(host=args.server, args.port) PushTask(client,", "server host or IP\") parser.add_argument(\"-p\", \"--port\", help=\"redis server port (default", "workers are subscribed\") parser.add_argument(\"-s\", \"--server\", help=\"redis server host or IP\")", "a message that a task is there.\"\"\" def PushTask(client, queue,", "creating a work queue. Basically push a task and publish", "args = parser.parse_args() if args.queue is None or args.task is", "task) client.publish(topic, queue) if __name__ == \"__main__\": parser = argparse.ArgumentParser()", "parser = argparse.ArgumentParser() parser.add_argument(\"-q\", \"--queue\", help=\"The queue from which workers", "client.publish(topic, queue) if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"-q\",", "which workers will grab tasks\") parser.add_argument(\"-t\", \"--task\", help=\"The task data\")", "task is there.\"\"\" def PushTask(client, queue, task, topic): client.lpush(queue, task)", "if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"-q\", \"--queue\", help=\"The", "server port (default is 6379)\", type=int, default=6379) args = parser.parse_args()", "a task and publish a message that a task is", "subscribed\") parser.add_argument(\"-s\", \"--server\", help=\"redis server host or IP\") parser.add_argument(\"-p\", \"--port\",", "help=\"The topic to which workers are subscribed\") parser.add_argument(\"-s\", \"--server\", help=\"redis", "queue. Basically push a task and publish a message that", "IP\") parser.add_argument(\"-p\", \"--port\", help=\"redis server port (default is 6379)\", type=int,", "== \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"-q\", \"--queue\", help=\"The queue from", "parser.parse_args() if args.queue is None or args.task is None or", "\"--task\", help=\"The task data\") parser.add_argument(\"-o\", \"--topic\", help=\"The topic to which", "if args.queue is None or args.task is None or args.topic", "default=6379) args = parser.parse_args() if args.queue is None or args.task", "import time import redis import json import argparse \"\"\" Follows", "message that a task is there.\"\"\" def PushTask(client, queue, task,", "Follows the StackExchange best practice for creating a work queue.", "is None or args.server is None: parser.print_help() else: client=redis.StrictRedis(host=args.server, args.port)", "import argparse \"\"\" Follows the StackExchange best practice for creating", "or args.server is None: parser.print_help() else: client=redis.StrictRedis(host=args.server, args.port) PushTask(client, args.queue,", "queue from which workers will grab tasks\") parser.add_argument(\"-t\", \"--task\", help=\"The", "are subscribed\") parser.add_argument(\"-s\", \"--server\", help=\"redis server host or IP\") parser.add_argument(\"-p\",", "def PushTask(client, queue, task, topic): client.lpush(queue, task) client.publish(topic, queue) if", "host or IP\") parser.add_argument(\"-p\", \"--port\", help=\"redis server port (default is", "which workers are subscribed\") parser.add_argument(\"-s\", \"--server\", help=\"redis server host or", "queue) if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"-q\", \"--queue\",", "6379)\", type=int, default=6379) args = parser.parse_args() if args.queue is None", "is None: parser.print_help() else: client=redis.StrictRedis(host=args.server, args.port) PushTask(client, args.queue, args.task, args.topic)", "that a task is there.\"\"\" def PushTask(client, queue, task, topic):", "time import redis import json import argparse \"\"\" Follows the", "Basically push a task and publish a message that a", "topic): client.lpush(queue, task) client.publish(topic, queue) if __name__ == \"__main__\": parser", "task and publish a message that a task is there.\"\"\"", "for creating a work queue. Basically push a task and", "will grab tasks\") parser.add_argument(\"-t\", \"--task\", help=\"The task data\") parser.add_argument(\"-o\", \"--topic\",", "\"\"\" Follows the StackExchange best practice for creating a work", "practice for creating a work queue. Basically push a task", "port (default is 6379)\", type=int, default=6379) args = parser.parse_args() if", "help=\"The queue from which workers will grab tasks\") parser.add_argument(\"-t\", \"--task\",", "argparse.ArgumentParser() parser.add_argument(\"-q\", \"--queue\", help=\"The queue from which workers will grab", "publish a message that a task is there.\"\"\" def PushTask(client,", "\"--server\", help=\"redis server host or IP\") parser.add_argument(\"-p\", \"--port\", help=\"redis server", "\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"-q\", \"--queue\", help=\"The queue from which", "and publish a message that a task is there.\"\"\" def", "parser.add_argument(\"-q\", \"--queue\", help=\"The queue from which workers will grab tasks\")", "parser.add_argument(\"-s\", \"--server\", help=\"redis server host or IP\") parser.add_argument(\"-p\", \"--port\", help=\"redis", "work queue. Basically push a task and publish a message", "import redis import json import argparse \"\"\" Follows the StackExchange", "the StackExchange best practice for creating a work queue. Basically", "None or args.task is None or args.topic is None or", "from which workers will grab tasks\") parser.add_argument(\"-t\", \"--task\", help=\"The task", "is None or args.task is None or args.topic is None", "args.task is None or args.topic is None or args.server is", "data\") parser.add_argument(\"-o\", \"--topic\", help=\"The topic to which workers are subscribed\")", "\"--topic\", help=\"The topic to which workers are subscribed\") parser.add_argument(\"-s\", \"--server\",", "a task is there.\"\"\" def PushTask(client, queue, task, topic): client.lpush(queue,", "<filename>redisSeed.py import time import redis import json import argparse \"\"\"", "__name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"-q\", \"--queue\", help=\"The queue", "or IP\") parser.add_argument(\"-p\", \"--port\", help=\"redis server port (default is 6379)\",", "args.queue is None or args.task is None or args.topic is", "PushTask(client, queue, task, topic): client.lpush(queue, task) client.publish(topic, queue) if __name__", "there.\"\"\" def PushTask(client, queue, task, topic): client.lpush(queue, task) client.publish(topic, queue)", "help=\"The task data\") parser.add_argument(\"-o\", \"--topic\", help=\"The topic to which workers", "parser.add_argument(\"-o\", \"--topic\", help=\"The topic to which workers are subscribed\") parser.add_argument(\"-s\",", "grab tasks\") parser.add_argument(\"-t\", \"--task\", help=\"The task data\") parser.add_argument(\"-o\", \"--topic\", help=\"The", "\"--queue\", help=\"The queue from which workers will grab tasks\") parser.add_argument(\"-t\",", "(default is 6379)\", type=int, default=6379) args = parser.parse_args() if args.queue", "is None or args.topic is None or args.server is None:", "is there.\"\"\" def PushTask(client, queue, task, topic): client.lpush(queue, task) client.publish(topic,", "topic to which workers are subscribed\") parser.add_argument(\"-s\", \"--server\", help=\"redis server", "to which workers are subscribed\") parser.add_argument(\"-s\", \"--server\", help=\"redis server host", "StackExchange best practice for creating a work queue. Basically push", "parser.add_argument(\"-t\", \"--task\", help=\"The task data\") parser.add_argument(\"-o\", \"--topic\", help=\"The topic to", "queue, task, topic): client.lpush(queue, task) client.publish(topic, queue) if __name__ ==", "help=\"redis server host or IP\") parser.add_argument(\"-p\", \"--port\", help=\"redis server port", "redis import json import argparse \"\"\" Follows the StackExchange best", "task data\") parser.add_argument(\"-o\", \"--topic\", help=\"The topic to which workers are", "None or args.topic is None or args.server is None: parser.print_help()", "a work queue. Basically push a task and publish a", "or args.topic is None or args.server is None: parser.print_help() else:", "tasks\") parser.add_argument(\"-t\", \"--task\", help=\"The task data\") parser.add_argument(\"-o\", \"--topic\", help=\"The topic", "client.lpush(queue, task) client.publish(topic, queue) if __name__ == \"__main__\": parser =", "args.topic is None or args.server is None: parser.print_help() else: client=redis.StrictRedis(host=args.server,", "json import argparse \"\"\" Follows the StackExchange best practice for", "best practice for creating a work queue. Basically push a", "is 6379)\", type=int, default=6379) args = parser.parse_args() if args.queue is", "parser.add_argument(\"-p\", \"--port\", help=\"redis server port (default is 6379)\", type=int, default=6379)", "workers will grab tasks\") parser.add_argument(\"-t\", \"--task\", help=\"The task data\") parser.add_argument(\"-o\"," ]
[ "all celery-related configuration keys # should have a `CELERY_` prefix.", "serialize # the configuration object to child processes. # -", "celery import Celery # set the default Django settings module", "all registered Django app configs. app.autodiscover_tasks() app.conf.update( task_serializer=\"json\", accept_content=[\"json\"], #", "object to child processes. # - namespace='CELERY' means all celery-related", "task_serializer=\"json\", accept_content=[\"json\"], # Ignore other content result_serializer=\"json\", timezone=\"Europe/Oslo\", enable_utc=True, )", "app.config_from_object(\"django.conf:settings\", namespace=\"CELERY\") # Load task modules from all registered Django", "the configuration object to child processes. # - namespace='CELERY' means", "Django app configs. app.autodiscover_tasks() app.conf.update( task_serializer=\"json\", accept_content=[\"json\"], # Ignore other", "other content result_serializer=\"json\", timezone=\"Europe/Oslo\", enable_utc=True, ) @app.task(bind=True) def debug_task(self): print(\"Request:", "default Django settings module for the 'celery' program. os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")", "to child processes. # - namespace='CELERY' means all celery-related configuration", "from celery import Celery # set the default Django settings", "\"app.settings\") app = Celery(\"app\") # Using a string here means", "unicode_literals import os from celery import Celery # set the", "# - namespace='CELERY' means all celery-related configuration keys # should", "namespace='CELERY' means all celery-related configuration keys # should have a", "worker doesn't have to serialize # the configuration object to", "means the worker doesn't have to serialize # the configuration", "Load task modules from all registered Django app configs. app.autodiscover_tasks()", "# should have a `CELERY_` prefix. app.config_from_object(\"django.conf:settings\", namespace=\"CELERY\") # Load", "import os from celery import Celery # set the default", "from all registered Django app configs. app.autodiscover_tasks() app.conf.update( task_serializer=\"json\", accept_content=[\"json\"],", "have to serialize # the configuration object to child processes.", "Ignore other content result_serializer=\"json\", timezone=\"Europe/Oslo\", enable_utc=True, ) @app.task(bind=True) def debug_task(self):", "<reponame>TIHLDE/Lepton<filename>app/celery.py from __future__ import absolute_import, unicode_literals import os from celery", "string here means the worker doesn't have to serialize #", "task modules from all registered Django app configs. app.autodiscover_tasks() app.conf.update(", "module for the 'celery' program. os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\") app = Celery(\"app\")", "keys # should have a `CELERY_` prefix. app.config_from_object(\"django.conf:settings\", namespace=\"CELERY\") #", "os from celery import Celery # set the default Django", "configuration object to child processes. # - namespace='CELERY' means all", "# Using a string here means the worker doesn't have", "should have a `CELERY_` prefix. app.config_from_object(\"django.conf:settings\", namespace=\"CELERY\") # Load task", "Celery # set the default Django settings module for the", "a string here means the worker doesn't have to serialize", "= Celery(\"app\") # Using a string here means the worker", "processes. # - namespace='CELERY' means all celery-related configuration keys #", "for the 'celery' program. os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\") app = Celery(\"app\") #", "# Load task modules from all registered Django app configs.", "configs. app.autodiscover_tasks() app.conf.update( task_serializer=\"json\", accept_content=[\"json\"], # Ignore other content result_serializer=\"json\",", "Django settings module for the 'celery' program. os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\") app", "Using a string here means the worker doesn't have to", "modules from all registered Django app configs. app.autodiscover_tasks() app.conf.update( task_serializer=\"json\",", "have a `CELERY_` prefix. app.config_from_object(\"django.conf:settings\", namespace=\"CELERY\") # Load task modules", "the 'celery' program. os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\") app = Celery(\"app\") # Using", "'celery' program. os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\") app = Celery(\"app\") # Using a", "the default Django settings module for the 'celery' program. os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\",", "Celery(\"app\") # Using a string here means the worker doesn't", "here means the worker doesn't have to serialize # the", "- namespace='CELERY' means all celery-related configuration keys # should have", "`CELERY_` prefix. app.config_from_object(\"django.conf:settings\", namespace=\"CELERY\") # Load task modules from all", "from __future__ import absolute_import, unicode_literals import os from celery import", "app.conf.update( task_serializer=\"json\", accept_content=[\"json\"], # Ignore other content result_serializer=\"json\", timezone=\"Europe/Oslo\", enable_utc=True,", "doesn't have to serialize # the configuration object to child", "os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\") app = Celery(\"app\") # Using a string here", "app.autodiscover_tasks() app.conf.update( task_serializer=\"json\", accept_content=[\"json\"], # Ignore other content result_serializer=\"json\", timezone=\"Europe/Oslo\",", "a `CELERY_` prefix. app.config_from_object(\"django.conf:settings\", namespace=\"CELERY\") # Load task modules from", "settings module for the 'celery' program. os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\") app =", "the worker doesn't have to serialize # the configuration object", "prefix. app.config_from_object(\"django.conf:settings\", namespace=\"CELERY\") # Load task modules from all registered", "accept_content=[\"json\"], # Ignore other content result_serializer=\"json\", timezone=\"Europe/Oslo\", enable_utc=True, ) @app.task(bind=True)", "content result_serializer=\"json\", timezone=\"Europe/Oslo\", enable_utc=True, ) @app.task(bind=True) def debug_task(self): print(\"Request: {0!r}\".format(self.request))", "# the configuration object to child processes. # - namespace='CELERY'", "means all celery-related configuration keys # should have a `CELERY_`", "app = Celery(\"app\") # Using a string here means the", "absolute_import, unicode_literals import os from celery import Celery # set", "child processes. # - namespace='CELERY' means all celery-related configuration keys", "import absolute_import, unicode_literals import os from celery import Celery #", "# Ignore other content result_serializer=\"json\", timezone=\"Europe/Oslo\", enable_utc=True, ) @app.task(bind=True) def", "set the default Django settings module for the 'celery' program.", "celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object(\"django.conf:settings\",", "app configs. app.autodiscover_tasks() app.conf.update( task_serializer=\"json\", accept_content=[\"json\"], # Ignore other content", "import Celery # set the default Django settings module for", "namespace=\"CELERY\") # Load task modules from all registered Django app", "program. os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\") app = Celery(\"app\") # Using a string", "configuration keys # should have a `CELERY_` prefix. app.config_from_object(\"django.conf:settings\", namespace=\"CELERY\")", "__future__ import absolute_import, unicode_literals import os from celery import Celery", "# set the default Django settings module for the 'celery'", "to serialize # the configuration object to child processes. #", "registered Django app configs. app.autodiscover_tasks() app.conf.update( task_serializer=\"json\", accept_content=[\"json\"], # Ignore" ]
[ "garage.core.serializable import Serializable from garage.core.parameterized import Parameterized # noqa: I100", "from garage.core.parameterized import Parameterized # noqa: I100 __all__ = ['Serializable',", "from garage.core.serializable import Serializable from garage.core.parameterized import Parameterized # noqa:", "Serializable from garage.core.parameterized import Parameterized # noqa: I100 __all__ =", "import Serializable from garage.core.parameterized import Parameterized # noqa: I100 __all__", "garage.core.parameterized import Parameterized # noqa: I100 __all__ = ['Serializable', 'Parameterized']", "<reponame>researchai/unsupervised_meta_rl<filename>src/garage/core/__init__.py from garage.core.serializable import Serializable from garage.core.parameterized import Parameterized #" ]
[ "\"\"\" The format field skips the rendering with the label", "attribute in the form level (i.e => form.as_p() doesn't have", "avoid the label # generation: self.label = None class HelpTextBoundField(FormatBoundField):", "label for format field). This boundfield has this main goal.", "*args, **kwargs): super().__init__(*args, **kwargs) # This attribute is used to", "skips the rendering with the label attribute in the form", "# with html tags. We force the label to None", "tags. We force the label to None to avoid the", "used to generate (or not) the final label # with", "form.as_p() doesn't have to generate any label for format field).", "TitleBoundField(FormatBoundField): def value(self): return self.field.label class SeparatorBoundField(FormatBoundField): def value(self): return", "def value(self): return self.field.text class TitleBoundField(FormatBoundField): def value(self): return self.field.label", "None to avoid the label # generation: self.label = None", "label attribute in the form level (i.e => form.as_p() doesn't", "any label for format field). This boundfield has this main", "boundfield has this main goal. \"\"\" def __init__(self, *args, **kwargs):", "the label attribute in the form level (i.e => form.as_p()", "class HelpTextBoundField(FormatBoundField): def value(self): return self.field.text class TitleBoundField(FormatBoundField): def value(self):", "# This attribute is used to generate (or not) the", "to generate (or not) the final label # with html", "**kwargs): super().__init__(*args, **kwargs) # This attribute is used to generate", "form level (i.e => form.as_p() doesn't have to generate any", "label to None to avoid the label # generation: self.label", "value(self): return self.field.text class TitleBoundField(FormatBoundField): def value(self): return self.field.label class", "label # with html tags. We force the label to", "self.label = None class HelpTextBoundField(FormatBoundField): def value(self): return self.field.text class", "super().__init__(*args, **kwargs) # This attribute is used to generate (or", "return self.field.text class TitleBoundField(FormatBoundField): def value(self): return self.field.label class SeparatorBoundField(FormatBoundField):", "force the label to None to avoid the label #", "forms class FormatBoundField(forms.BoundField): \"\"\" The format field skips the rendering", "with html tags. We force the label to None to", "to None to avoid the label # generation: self.label =", "=> form.as_p() doesn't have to generate any label for format", "field skips the rendering with the label attribute in the", "doesn't have to generate any label for format field). This", "has this main goal. \"\"\" def __init__(self, *args, **kwargs): super().__init__(*args,", "We force the label to None to avoid the label", "html tags. We force the label to None to avoid", "goal. \"\"\" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This", "import forms class FormatBoundField(forms.BoundField): \"\"\" The format field skips the", "<reponame>jayvdb/django-formidable from django.forms import forms class FormatBoundField(forms.BoundField): \"\"\" The format", "from django.forms import forms class FormatBoundField(forms.BoundField): \"\"\" The format field", "**kwargs) # This attribute is used to generate (or not)", "HelpTextBoundField(FormatBoundField): def value(self): return self.field.text class TitleBoundField(FormatBoundField): def value(self): return", "this main goal. \"\"\" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)", "def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This attribute is", "This attribute is used to generate (or not) the final", "# generation: self.label = None class HelpTextBoundField(FormatBoundField): def value(self): return", "main goal. \"\"\" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #", "not) the final label # with html tags. We force", "level (i.e => form.as_p() doesn't have to generate any label", "the label # generation: self.label = None class HelpTextBoundField(FormatBoundField): def", "None class HelpTextBoundField(FormatBoundField): def value(self): return self.field.text class TitleBoundField(FormatBoundField): def", "The format field skips the rendering with the label attribute", "the label to None to avoid the label # generation:", "(i.e => form.as_p() doesn't have to generate any label for", "the form level (i.e => form.as_p() doesn't have to generate", "format field skips the rendering with the label attribute in", "is used to generate (or not) the final label #", "__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This attribute is used", "with the label attribute in the form level (i.e =>", "\"\"\" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This attribute", "django.forms import forms class FormatBoundField(forms.BoundField): \"\"\" The format field skips", "have to generate any label for format field). This boundfield", "FormatBoundField(forms.BoundField): \"\"\" The format field skips the rendering with the", "generation: self.label = None class HelpTextBoundField(FormatBoundField): def value(self): return self.field.text", "the rendering with the label attribute in the form level", "rendering with the label attribute in the form level (i.e", "= None class HelpTextBoundField(FormatBoundField): def value(self): return self.field.text class TitleBoundField(FormatBoundField):", "format field). This boundfield has this main goal. \"\"\" def", "(or not) the final label # with html tags. We", "in the form level (i.e => form.as_p() doesn't have to", "field). This boundfield has this main goal. \"\"\" def __init__(self,", "label # generation: self.label = None class HelpTextBoundField(FormatBoundField): def value(self):", "final label # with html tags. We force the label", "class FormatBoundField(forms.BoundField): \"\"\" The format field skips the rendering with", "def value(self): return self.field.label class SeparatorBoundField(FormatBoundField): def value(self): return None", "the final label # with html tags. We force the", "generate (or not) the final label # with html tags.", "This boundfield has this main goal. \"\"\" def __init__(self, *args,", "attribute is used to generate (or not) the final label", "to avoid the label # generation: self.label = None class", "to generate any label for format field). This boundfield has", "for format field). This boundfield has this main goal. \"\"\"", "self.field.text class TitleBoundField(FormatBoundField): def value(self): return self.field.label class SeparatorBoundField(FormatBoundField): def", "class TitleBoundField(FormatBoundField): def value(self): return self.field.label class SeparatorBoundField(FormatBoundField): def value(self):", "generate any label for format field). This boundfield has this" ]
[ "A = int(input()) B = int(input()) C = int(input()) X", "for b in range(B+1): for c in range(C+1): total =", "total == X: counter += 1 print(counter) class TaskC: def", "TaskB: def run(self): A = int(input()) B = int(input()) C", "= map(int, input().split()) pass class TaskB: def run(self): A =", "= 0 for a in range(A+1): for b in range(B+1):", "in range(A+1): for b in range(B+1): for c in range(C+1):", "a + 100 * b + 50 * c if", "run(self): pass if __name__ == \"__main__\": task = TaskB() task.run()", "V, A, B, C = map(int, input().split()) pass class TaskB:", "if total == X: counter += 1 print(counter) class TaskC:", "run(self): V, A, B, C = map(int, input().split()) pass class", "int(input()) counter = 0 for a in range(A+1): for b", "counter = 0 for a in range(A+1): for b in", "B, C = map(int, input().split()) pass class TaskB: def run(self):", "class TaskA: def run(self): V, A, B, C = map(int,", "B = int(input()) C = int(input()) X = int(input()) counter", "* a + 100 * b + 50 * c", "A, B, C = map(int, input().split()) pass class TaskB: def", "+ 50 * c if total == X: counter +=", "def run(self): V, A, B, C = map(int, input().split()) pass", "in range(C+1): total = 500 * a + 100 *", "X: counter += 1 print(counter) class TaskC: def run(self): pass", "range(A+1): for b in range(B+1): for c in range(C+1): total", "a in range(A+1): for b in range(B+1): for c in", "c if total == X: counter += 1 print(counter) class", "class TaskC: def run(self): pass if __name__ == \"__main__\": task", "total = 500 * a + 100 * b +", "def run(self): pass if __name__ == \"__main__\": task = TaskB()", "* c if total == X: counter += 1 print(counter)", "int(input()) C = int(input()) X = int(input()) counter = 0", "C = int(input()) X = int(input()) counter = 0 for", "int(input()) B = int(input()) C = int(input()) X = int(input())", "= int(input()) counter = 0 for a in range(A+1): for", "* b + 50 * c if total == X:", "1 print(counter) class TaskC: def run(self): pass if __name__ ==", "print(counter) class TaskC: def run(self): pass if __name__ == \"__main__\":", "map(int, input().split()) pass class TaskB: def run(self): A = int(input())", "range(C+1): total = 500 * a + 100 * b", "b in range(B+1): for c in range(C+1): total = 500", "== X: counter += 1 print(counter) class TaskC: def run(self):", "TaskA: def run(self): V, A, B, C = map(int, input().split())", "def run(self): A = int(input()) B = int(input()) C =", "TaskC: def run(self): pass if __name__ == \"__main__\": task =", "range(B+1): for c in range(C+1): total = 500 * a", "= 500 * a + 100 * b + 50", "<filename>algorithm_training/abc87.py class TaskA: def run(self): V, A, B, C =", "0 for a in range(A+1): for b in range(B+1): for", "class TaskB: def run(self): A = int(input()) B = int(input())", "input().split()) pass class TaskB: def run(self): A = int(input()) B", "int(input()) X = int(input()) counter = 0 for a in", "C = map(int, input().split()) pass class TaskB: def run(self): A", "= int(input()) X = int(input()) counter = 0 for a", "run(self): A = int(input()) B = int(input()) C = int(input())", "= int(input()) C = int(input()) X = int(input()) counter =", "X = int(input()) counter = 0 for a in range(A+1):", "c in range(C+1): total = 500 * a + 100", "pass class TaskB: def run(self): A = int(input()) B =", "+ 100 * b + 50 * c if total", "for a in range(A+1): for b in range(B+1): for c", "500 * a + 100 * b + 50 *", "= int(input()) B = int(input()) C = int(input()) X =", "counter += 1 print(counter) class TaskC: def run(self): pass if", "+= 1 print(counter) class TaskC: def run(self): pass if __name__", "for c in range(C+1): total = 500 * a +", "in range(B+1): for c in range(C+1): total = 500 *", "50 * c if total == X: counter += 1", "b + 50 * c if total == X: counter", "100 * b + 50 * c if total ==" ]
[ ":', addr) data = conn.recv(BUFFER_SIZE) if data == \"m\" :", "addr = s.accept() print('Connection entrante :', addr) data = conn.recv(BUFFER_SIZE)", "= conn.recv(BUFFER_SIZE) if data == \"m\" : os.popen(\"chmod +w $PWD\")", "if data == \"m\" : os.popen(\"chmod +w $PWD\") else :", "= s.accept() print('Connection entrante :', addr) data = conn.recv(BUFFER_SIZE) if", "socket,sys,os TCP_IP = '127.0.0.1' TCP_PORT = 6262 BUFFER_SIZE = 1024", "6262 BUFFER_SIZE = 1024 s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((TCP_IP,TCP_PORT)) s.listen(5) conn, addr", "conn.recv(BUFFER_SIZE) print data if data == \"1\": break rep =", "1024 s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((TCP_IP,TCP_PORT)) s.listen(5) conn, addr = s.accept() print('Connection", "print data if data == \"1\": break rep = os.popen(data+\"", "'127.0.0.1' TCP_PORT = 6262 BUFFER_SIZE = 1024 s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((TCP_IP,TCP_PORT))", "data = conn.recv(BUFFER_SIZE) if data == \"m\" : os.popen(\"chmod +w", "BUFFER_SIZE = 1024 s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((TCP_IP,TCP_PORT)) s.listen(5) conn, addr =", ": data = conn.recv(BUFFER_SIZE) print data if data == \"1\":", "-w $PWD\") while 1 : data = conn.recv(BUFFER_SIZE) print data", "data == \"m\" : os.popen(\"chmod +w $PWD\") else : os.popen(\"chmod", "os.popen(\"chmod -w $PWD\") while 1 : data = conn.recv(BUFFER_SIZE) print", "data = conn.recv(BUFFER_SIZE) print data if data == \"1\": break", "print('Connection entrante :', addr) data = conn.recv(BUFFER_SIZE) if data ==", ": os.popen(\"chmod +w $PWD\") else : os.popen(\"chmod -w $PWD\") while", "1 : data = conn.recv(BUFFER_SIZE) print data if data ==", "entrante :', addr) data = conn.recv(BUFFER_SIZE) if data == \"m\"", ": os.popen(\"chmod -w $PWD\") while 1 : data = conn.recv(BUFFER_SIZE)", "TCP_IP = '127.0.0.1' TCP_PORT = 6262 BUFFER_SIZE = 1024 s=", "= 6262 BUFFER_SIZE = 1024 s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((TCP_IP,TCP_PORT)) s.listen(5) conn,", "#!/usr/bin/python import socket,sys,os TCP_IP = '127.0.0.1' TCP_PORT = 6262 BUFFER_SIZE", "\"1\": break rep = os.popen(data+\" 2>&1\") conn.send(\"reponse : \\n\"+rep.read()) conn.close()", "= 1024 s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((TCP_IP,TCP_PORT)) s.listen(5) conn, addr = s.accept()", "while 1 : data = conn.recv(BUFFER_SIZE) print data if data", "import socket,sys,os TCP_IP = '127.0.0.1' TCP_PORT = 6262 BUFFER_SIZE =", "== \"m\" : os.popen(\"chmod +w $PWD\") else : os.popen(\"chmod -w", "socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((TCP_IP,TCP_PORT)) s.listen(5) conn, addr = s.accept() print('Connection entrante :',", "s.bind((TCP_IP,TCP_PORT)) s.listen(5) conn, addr = s.accept() print('Connection entrante :', addr)", "s.listen(5) conn, addr = s.accept() print('Connection entrante :', addr) data", "TCP_PORT = 6262 BUFFER_SIZE = 1024 s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((TCP_IP,TCP_PORT)) s.listen(5)", "data == \"1\": break rep = os.popen(data+\" 2>&1\") conn.send(\"reponse :", "\"m\" : os.popen(\"chmod +w $PWD\") else : os.popen(\"chmod -w $PWD\")", "s.accept() print('Connection entrante :', addr) data = conn.recv(BUFFER_SIZE) if data", "addr) data = conn.recv(BUFFER_SIZE) if data == \"m\" : os.popen(\"chmod", "os.popen(\"chmod +w $PWD\") else : os.popen(\"chmod -w $PWD\") while 1", "s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((TCP_IP,TCP_PORT)) s.listen(5) conn, addr = s.accept() print('Connection entrante", "== \"1\": break rep = os.popen(data+\" 2>&1\") conn.send(\"reponse : \\n\"+rep.read())", "<gh_stars>0 #!/usr/bin/python import socket,sys,os TCP_IP = '127.0.0.1' TCP_PORT = 6262", "= conn.recv(BUFFER_SIZE) print data if data == \"1\": break rep", "$PWD\") while 1 : data = conn.recv(BUFFER_SIZE) print data if", "if data == \"1\": break rep = os.popen(data+\" 2>&1\") conn.send(\"reponse", "= '127.0.0.1' TCP_PORT = 6262 BUFFER_SIZE = 1024 s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)", "+w $PWD\") else : os.popen(\"chmod -w $PWD\") while 1 :", "else : os.popen(\"chmod -w $PWD\") while 1 : data =", "data if data == \"1\": break rep = os.popen(data+\" 2>&1\")", "$PWD\") else : os.popen(\"chmod -w $PWD\") while 1 : data", "conn.recv(BUFFER_SIZE) if data == \"m\" : os.popen(\"chmod +w $PWD\") else", "conn, addr = s.accept() print('Connection entrante :', addr) data =" ]
[ "{ 'token': token, 'user': UserSerializer(user, context={'request': request}).data } def get_token_from_request(request):", "context={'request': request}).data } def get_token_from_request(request): auth = request.META.get('HTTP_AUTHORIZATION', '').split() if", "User.DoesNotExist: return None return None def get_user_from_request(request): token = get_token_from_request(request)", "None def get_user_from_request(request): token = get_token_from_request(request) if token: return get_user_from_token(token)", "jwt_response_payload_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={'request':", "from users.models import User from users.serializers import UserSerializer def jwt_response_payload_handler(token,", "try: return User.objects.get(id=user_id) except User.DoesNotExist: return None return None def", "user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={'request': request}).data", "def get_user_from_token(token): data = jwt_decode_handler(token) user_id = data.get('user_id') if user_id:", "get_user_from_request(request): token = get_token_from_request(request) if token: return get_user_from_token(token) return None", "from users.serializers import UserSerializer def jwt_response_payload_handler(token, user=None, request=None): return {", "= request.META.get('HTTP_AUTHORIZATION', '').split() if len(auth) == 2: return auth[1] return", "'user': UserSerializer(user, context={'request': request}).data } def get_token_from_request(request): auth = request.META.get('HTTP_AUTHORIZATION',", "return auth[1] return None def get_user_from_token(token): data = jwt_decode_handler(token) user_id", "from rest_framework_jwt.utils import jwt_decode_handler from users.models import User from users.serializers", "auth = request.META.get('HTTP_AUTHORIZATION', '').split() if len(auth) == 2: return auth[1]", "None def get_user_from_token(token): data = jwt_decode_handler(token) user_id = data.get('user_id') if", "= jwt_decode_handler(token) user_id = data.get('user_id') if user_id: try: return User.objects.get(id=user_id)", "def get_token_from_request(request): auth = request.META.get('HTTP_AUTHORIZATION', '').split() if len(auth) == 2:", "} def get_token_from_request(request): auth = request.META.get('HTTP_AUTHORIZATION', '').split() if len(auth) ==", "return None def get_user_from_token(token): data = jwt_decode_handler(token) user_id = data.get('user_id')", "request}).data } def get_token_from_request(request): auth = request.META.get('HTTP_AUTHORIZATION', '').split() if len(auth)", "User.objects.get(id=user_id) except User.DoesNotExist: return None return None def get_user_from_request(request): token", "User from users.serializers import UserSerializer def jwt_response_payload_handler(token, user=None, request=None): return", "def jwt_response_payload_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user,", "jwt_decode_handler from users.models import User from users.serializers import UserSerializer def", "rest_framework_jwt.utils import jwt_decode_handler from users.models import User from users.serializers import", "except User.DoesNotExist: return None return None def get_user_from_request(request): token =", "import UserSerializer def jwt_response_payload_handler(token, user=None, request=None): return { 'token': token,", "<gh_stars>1-10 from rest_framework_jwt.utils import jwt_decode_handler from users.models import User from", "None return None def get_user_from_request(request): token = get_token_from_request(request) if token:", "'').split() if len(auth) == 2: return auth[1] return None def", "request.META.get('HTTP_AUTHORIZATION', '').split() if len(auth) == 2: return auth[1] return None", "request=None): return { 'token': token, 'user': UserSerializer(user, context={'request': request}).data }", "token, 'user': UserSerializer(user, context={'request': request}).data } def get_token_from_request(request): auth =", "get_token_from_request(request): auth = request.META.get('HTTP_AUTHORIZATION', '').split() if len(auth) == 2: return", "users.serializers import UserSerializer def jwt_response_payload_handler(token, user=None, request=None): return { 'token':", "data = jwt_decode_handler(token) user_id = data.get('user_id') if user_id: try: return", "UserSerializer(user, context={'request': request}).data } def get_token_from_request(request): auth = request.META.get('HTTP_AUTHORIZATION', '').split()", "def get_user_from_request(request): token = get_token_from_request(request) if token: return get_user_from_token(token) return", "if len(auth) == 2: return auth[1] return None def get_user_from_token(token):", "return User.objects.get(id=user_id) except User.DoesNotExist: return None return None def get_user_from_request(request):", "return None def get_user_from_request(request): token = get_token_from_request(request) if token: return", "UserSerializer def jwt_response_payload_handler(token, user=None, request=None): return { 'token': token, 'user':", "2: return auth[1] return None def get_user_from_token(token): data = jwt_decode_handler(token)", "users.models import User from users.serializers import UserSerializer def jwt_response_payload_handler(token, user=None,", "import User from users.serializers import UserSerializer def jwt_response_payload_handler(token, user=None, request=None):", "user_id = data.get('user_id') if user_id: try: return User.objects.get(id=user_id) except User.DoesNotExist:", "= data.get('user_id') if user_id: try: return User.objects.get(id=user_id) except User.DoesNotExist: return", "user_id: try: return User.objects.get(id=user_id) except User.DoesNotExist: return None return None", "return None return None def get_user_from_request(request): token = get_token_from_request(request) if", "import jwt_decode_handler from users.models import User from users.serializers import UserSerializer", "'token': token, 'user': UserSerializer(user, context={'request': request}).data } def get_token_from_request(request): auth", "== 2: return auth[1] return None def get_user_from_token(token): data =", "return { 'token': token, 'user': UserSerializer(user, context={'request': request}).data } def", "jwt_decode_handler(token) user_id = data.get('user_id') if user_id: try: return User.objects.get(id=user_id) except", "auth[1] return None def get_user_from_token(token): data = jwt_decode_handler(token) user_id =", "len(auth) == 2: return auth[1] return None def get_user_from_token(token): data", "if user_id: try: return User.objects.get(id=user_id) except User.DoesNotExist: return None return", "data.get('user_id') if user_id: try: return User.objects.get(id=user_id) except User.DoesNotExist: return None", "get_user_from_token(token): data = jwt_decode_handler(token) user_id = data.get('user_id') if user_id: try:" ]
[ "# and/or other materials provided with the distribution. # #", "set to -1. Both x and factor must otherwise be", "by the, REMOTE_VIVADO environment variable, otherwise return None\"\"\" try: return", "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR", "val=0, distr_pad=False): \"\"\"Pad each dimension of given NumPy ndarray using", "make_build_dir(prefix=\"\"): \"\"\"Creates a temporary folder with given prefix to be", "def remove_by_name(container, name, name_field=\"name\"): \"\"\"Remove item from container by .name", "remote Vivado synthesis server as set by the, REMOTE_VIVADO environment", "both signed vectors.\"\"\" min_prod = 2 ** 30 max_prod =", "dimension of the matrix is not 2. Currently this function", "amount is not divisible by two.\"\"\" if type(ndarray) != np.ndarray", "Exception if multiple items are found, since this violates the", "FINN datatype ({}), they will be rounded to match the", "return matrix_r def roundup_to_integer_multiple(x, factor): \"\"\"Round up integer x to", "os.environ[\"FINN_INST_NAME\"] + \"/\" return tempfile.mkdtemp(prefix=inst_prefix + prefix) except KeyError: raise", "\"\".join(random.choice(lettersAndDigits) for i in range(stringLength)) def interleave_matrix_outer_dim_from_partitions(matrix, n_partitions): \"\"\"Interleave the", "NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE", "desired = np.asarray(list(desired), dtype=np.int32) current = np.asarray(ndarray.shape, dtype=np.int32) pad_amt =", "# enabled by default return 1 def make_build_dir(prefix=\"\"): \"\"\"Creates a", "pad_to_dims value.\"\"\" # compute the desired shape desired = zip(list(ndarray.shape),", "the name of Xilinx nor the names of its #", "finn_dt == DataType.BINARY: tensor_values = np.random.randint(2, size=tensor_shape) elif \"INT\" in", "without specific prior written permission. # # THIS SOFTWARE IS", "for b_val in [dt_b.min(), dt_b.max()]: prod = a_val * b_val", "uses floating point tensors as a carrier data type to", "(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR", "are supposed to be integers are indeed integers. \"\"\" for", "If distr_pad is False, all padding will be inserted after", "GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS;", "float(os.environ[\"ERROR_THRESH\"]) except KeyError: return 1e-2 def get_sanitize_quant_tensors(): \"\"\"Return whether tensors", "a_val in [dt_a.min(), dt_a.max()]: for b_val in [dt_b.min(), dt_b.max()]: prod", "numpy for value in np.nditer(current_values): if not dtype.allowed(value): has_to_be_rounded =", "in [dt_a.min(), dt_a.max()]: for b_val in [dt_b.min(), dt_b.max()]: prod =", "x to the nearest integer multiple of integer factor. Returns", "np.asarray(list(desired), dtype=np.int32) current = np.asarray(ndarray.shape, dtype=np.int32) pad_amt = desired -", "notice, this # list of conditions and the following disclaimer.", "as container return tensor_values.astype(np.float32) def calculate_signed_dot_prod_range(dt_a, dt_b, len): \"\"\"Returns the", "inds[0] return container[ind] def remove_by_name(container, name, name_field=\"name\"): \"\"\"Remove item from", "the input datatype acc_min = perceptive_field_elems * min( min_weight *", "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH", "pynq_part_map[\"ZCU102\"] = \"xczu9eg-ffvb1156-2-e\" pynq_part_map[\"ZCU104\"] = \"xczu7ev-ffvc1156-2-e\" # native AXI HP", "self.include_paths.append(library_path) def append_sources(self, cpp_file): \"\"\"Adds given c++ file to cpp_files", "* b_val * len if prod < min_prod: min_prod =", "lists. Saves it in bash script in given folder and", "x and factor must otherwise be positive.\"\"\" # ensure integers", "self.compile_script = str(self.code_gen_dir) + \"/compile.sh\" with open(self.compile_script, \"w\") as f:", "if factor is set to -1. Both x and factor", "ensure positive values assert factor > 0 and x >", "allowed for rounding in FINN execution.\" try: return float(os.environ[\"ERROR_THRESH\"]) except", "sanitization, skip to next # introduces less quicker runtime if", "shows per full-layer I/O including FIFO count signals \"\"\" try:", "must otherwise be positive.\"\"\" # ensure integers assert int(x) ==", "int(os.environ[\"NUM_DEFAULT_WORKERS\"]) except KeyError: return 1 def get_finn_root(): \"Return the root", "existing values; otherwise it will be split evenly between before", "of letters and digits.\"\"\" lettersAndDigits = string.ascii_letters + string.digits return", "indicate no padding needed if factor == -1: return x", "== 0: return x else: return x + (factor -", "FINN_INST_NAME must be set correctly. Please ensure you have launched", "None\"\"\" try: return os.environ[\"REMOTE_VIVADO\"] except KeyError: return None def get_num_default_workers():", "the set FINN datatype ({}), they will be rounded to", "ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, #", "arithmetic can introduce rounding errors, e.g. (int_num * float_scale) /", "signals and yield smaller .vcd files. The following depth values", "2 * tensor_values - 1 elif finn_dt == DataType.BINARY: tensor_values", "is float) matrix = np.asarray(matrix, dtype=np.float32) shp = matrix.shape ndim", "= path def build(self, code_gen_dir): \"\"\"Builds the g++ compiler command", "if the amount of rounding is too large. Returns the", "and binary forms, with or without # modification, are permitted", "names of its # contributors may be used to endorse", "values are not too far from original values max_error =", "source code must retain the above copyright notice, this #", "one.\"\"\" return ret def calculate_matvec_accumulator_range(matrix, vec_dt): \"\"\"Calculate the minimum and", "= matrix.reshape(-1, n_partitions, shp[1]).transpose((1, 0, 2)) matrix_r = matrix_r.reshape(n_partitions, -1,", "OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON", "\"xcu250-figd2104-2L-e\" alveo_part_map[\"U280\"] = \"xcu280-fsvh2892-2L-e\" alveo_default_platform = dict() alveo_default_platform[\"U50\"] = \"xilinx_u50_gen3x16_xdma_201920_3\"", "an Exception if multiple items are found, since this violates", "# # * Neither the name of Xilinx nor the", "updated_values = current_values has_to_be_rounded = False # TODO: vectorize with", "SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)", "again if values can now be represented with set finn", "original values max_error = max(np.abs(current_values - updated_values).flatten()) if max_error <=", "high to match set FINN datatype ({}) for input {}\"\"\".format(", "REMOTE_VIVADO environment variable, otherwise return None\"\"\" try: return os.environ[\"REMOTE_VIVADO\"] except", "written permission. # # THIS SOFTWARE IS PROVIDED BY THE", "WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE", "= code_gen_dir self.compile_components.append(\"g++ -o \" + str(self.executable_path)) for cpp_file in", "THE POSSIBILITY OF SUCH DAMAGE. import numpy as np import", "other materials provided with the distribution. # # * Neither", "return x # ensure positive values assert factor > 0", "software without specific prior written permission. # # THIS SOFTWARE", "[dt_b.min(), dt_b.max()]: prod = a_val * b_val * len if", "set finn datatype # TODO: vectorize with numpy for value", "given partitions (n_partitions).\"\"\" if type(matrix) != np.ndarray or matrix.dtype !=", "current = np.asarray(ndarray.shape, dtype=np.int32) pad_amt = desired - current #", "you have launched the Docker contaier correctly. \"\"\" ) def", "supported, no tensor could be generated\".format(finn_dt) ) # always use", "for tensor in node_tensors: dtype = model.get_tensor_datatype(tensor) # floats don't", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "not divisable by the number of partitions.\"\"\" # only tested", "# native AXI HP port width (in bits) for PYNQ", "raise Exception( \"\"\"Values can't be represented with set finn datatype", "not dtype.allowed(value): raise Exception( \"\"\"Values can't be represented with set", "TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "generate a string of letters and digits.\"\"\" lettersAndDigits = string.ascii_letters", "has_to_be_rounded: updated_values = np.round(current_values) warnings.warn( \"The values of tensor {}", "of integer factor. Returns x if factor is set to", "matrices assert ( ndim == 2 ), \"\"\"The dimension of", "= a_val * b_val * len if prod < min_prod:", "(in bits) for PYNQ boards pynq_native_port_width = dict() pynq_native_port_width[\"Pynq-Z1\"] =", "ind = inds[0] return container[ind] def remove_by_name(container, name, name_field=\"name\"): \"\"\"Remove", "\"xcu50-fsvh2104-2L-e\" alveo_part_map[\"U200\"] = \"xcu200-fsgd2104-2-e\" alveo_part_map[\"U250\"] = \"xcu250-figd2104-2L-e\" alveo_part_map[\"U280\"] = \"xcu280-fsvh2892-2L-e\"", "len): \"\"\"Returns the (min,max) values a dot product between two", "# this software without specific prior written permission. # #", "array doesn't match the desired/expected one.\"\"\" return ret def calculate_matvec_accumulator_range(matrix,", "Controllable via the RTLSIM_TRACE_DEPTH environment variable. If the env.var. is", "if x % factor == 0: return x else: return", "desired = map(lambda x: roundup_to_integer_multiple(x[0], x[1]), desired) desired = np.asarray(list(desired),", "= \"xilinx_u250_xdma_201830_2\" alveo_default_platform[\"U280\"] = \"xilinx_u280_xdma_201920_3\" def get_rtlsim_trace_depth(): \"\"\"Return the trace", "Redistributions of source code must retain the above copyright notice,", "the desired shape if distr_pad: pad_before = (pad_amt // 2).astype(np.int32)", "e in enumerate(names) if e == name] if len(inds) >", "OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT", "of dims (MW, MH), and vector (1, MW) with datatype", "and vector (1, MW) with datatype vec_dt. Returns (acc_min, acc_max).", "to include_paths list.\"\"\" self.include_paths.append(library_path) def append_sources(self, cpp_file): \"\"\"Adds given c++", "variable \"executable_path\" to given path.\"\"\" self.executable_path = path def build(self,", "POSSIBILITY OF SUCH DAMAGE. import numpy as np import os", "pynq_native_port_width[\"ZCU104\"] = 128 # Alveo device and platform mappings alveo_part_map", "min( min_weight * max_input, min_weight * min_input, max_weight * max_input,", "Exception( \"\"\"Environment variable FINN_ROOT must be set correctly. Please ensure", "# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "could be generated\".format(finn_dt) ) # always use float type as", "if has_to_be_rounded: updated_values = np.round(current_values) warnings.warn( \"The values of tensor", "np.ndarray or matrix.dtype != np.float32: # try to convert to", "perceptive_field_elems * min( min_weight * max_input, min_weight * min_input, max_weight", "variable FINN_INST_NAME must be set correctly. Please ensure you have", "code_gen_dir which is passed to the function build() of this", "try: return int(os.environ[\"RTLSIM_TRACE_DEPTH\"]) except KeyError: return 1 def get_remote_vivado(): \"\"\"Return", "annotation). Will raise an assertion if the amount of rounding", "tensors as a carrier data type to represent integers. Floating", "alveo_part_map[\"U50\"] = \"xcu50-fsvh2104-2L-e\" alveo_part_map[\"U200\"] = \"xcu200-fsgd2104-2-e\" alveo_part_map[\"U250\"] = \"xcu250-figd2104-2L-e\" alveo_part_map[\"U280\"]", "return int(os.environ[\"RTLSIM_TRACE_DEPTH\"]) except KeyError: return 1 def get_remote_vivado(): \"\"\"Return the", "a float numpy array (container dtype is float) matrix =", "name_field=\"name\"): \"\"\"Remove item from container by .name field if it", "def build(self, code_gen_dir): \"\"\"Builds the g++ compiler command according to", "integer multiple of integer factor. Returns x if factor is", "shows top-level input/output streams - level 2 shows per-layer input/output", "that are supposed to be integers (as indicated by their", "item from container by .name field if it exists.\"\"\" item", "the FINN Docker container exits.\"\"\" try: inst_prefix = os.environ[\"FINN_INST_NAME\"] +", "desired = zip(list(ndarray.shape), list(pad_to_dims)) desired = map(lambda x: roundup_to_integer_multiple(x[0], x[1]),", "executable of the c++ code in code_gen_dir which is passed", "of accumulator # assume inputs span the whole range of", "* A, given matrix A of dims (MW, MH), and", "= dict() pynq_native_port_width[\"Pynq-Z1\"] = 64 pynq_native_port_width[\"Pynq-Z2\"] = 64 pynq_native_port_width[\"Ultra96\"] =", "for whole-network stitched IP rtlsim: - level 1 shows top-level", "the address of the remote Vivado synthesis server as set", "too far from original values max_error = max(np.abs(current_values - updated_values).flatten())", "nor the names of its # contributors may be used", "= False # TODO: vectorize with numpy for value in", "** 30 max_prod = -(2 ** 30) for a_val in", "tensors. Background: FINN uses floating point tensors as a carrier", "correctly. Please ensure you have launched the Docker contaier correctly.", "instead of tempfile.mkdtemp to ensure any generated files will survive", "name_field=\"name\"): \"\"\"Return item from container by .name field if it", "means do not pad that particular dimension. If distr_pad is", "return 1 def get_finn_root(): \"Return the root directory that FINN", "otherwise it will be split evenly between before and after", "sanitize_quant_values(model, node_tensors, execution_context, check_values=False): \"\"\"Sanitize given list of tensors in", "acc_min = perceptive_field_elems * min( min_weight * max_input, min_weight *", "\"xcu280-fsvh2892-2L-e\" alveo_default_platform = dict() alveo_default_platform[\"U50\"] = \"xilinx_u50_gen3x16_xdma_201920_3\" alveo_default_platform[\"U200\"] = \"xilinx_u200_xdma_201830_2\"", "except KeyError: # enabled by default return 1 def make_build_dir(prefix=\"\"):", "to the nearest integer multiple of integer factor. Returns x", "\"\"\" try: return int(os.environ[\"RTLSIM_TRACE_DEPTH\"]) except KeyError: return 1 def get_remote_vivado():", "pynq_part_map = dict() pynq_part_map[\"Ultra96\"] = \"xczu3eg-sbva484-1-e\" pynq_part_map[\"Pynq-Z1\"] = \"xc7z020clg400-1\" pynq_part_map[\"Pynq-Z2\"]", "caution.\"\"\" try: return int(os.environ[\"SANITIZE_QUANT_TENSORS\"]) except KeyError: # enabled by default", "BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF", "// 2).astype(np.int32) pad_after = pad_amt - pad_before pad_amt = list(zip(pad_before,", "KeyError: return 1 def get_finn_root(): \"Return the root directory that", "If the env.var. is undefined, the default value of 1", "the sanitized execution context. If check_values is specified, an extra", "random import string import subprocess import tempfile import warnings from", "dict() pynq_native_port_width[\"Pynq-Z1\"] = 64 pynq_native_port_width[\"Pynq-Z2\"] = 64 pynq_native_port_width[\"Ultra96\"] = 128", "if check_values is True: # check again if values can", "pad_before = (pad_amt // 2).astype(np.int32) pad_after = pad_amt - pad_before", "sanitized execution context. If check_values is specified, an extra DataType.allowed()", "desired shape if distr_pad: pad_before = (pad_amt // 2).astype(np.int32) pad_after", "execution but may give incorrect results. Use with caution.\"\"\" try:", "ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER", "factor)) def pad_tensor_to_multiple_of(ndarray, pad_to_dims, val=0, distr_pad=False): \"\"\"Pad each dimension of", "shp = matrix.shape ndim = matrix.ndim # ensure # partitions", "except KeyError: raise Exception( \"\"\"Environment variable FINN_ROOT must be set", "bash_compile = \"\" for component in self.compile_components: bash_compile += str(component)", "a carrier data type to represent integers. Floating point arithmetic", "form must reproduce the above copyright notice, # this list", "else: if x % factor == 0: return x else:", "== factor, \"The input factor is not an integer.\" #", "self.compile_components: bash_compile += str(component) + \" \" self.compile_script = str(self.code_gen_dir)", "CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,", "= dict() alveo_part_map[\"U50\"] = \"xcu50-fsvh2104-2L-e\" alveo_part_map[\"U200\"] = \"xcu200-fsgd2104-2-e\" alveo_part_map[\"U250\"] =", "streams - level 3 shows per full-layer I/O including FIFO", "that each dimension is a multiple of the respective value", "are empty self.code_gen_dir = code_gen_dir self.compile_components.append(\"g++ -o \" + str(self.executable_path))", "ndarray = np.asarray(ndarray, dtype=np.float32) assert ndarray.ndim == len( pad_to_dims ),", "else: raise ValueError( \"Datatype {} is not supported, no tensor", "FINN datatype ({}) for input {}\"\"\".format( dtype, tensor ) )", "We use this function to ensure that the values that", "dtype == DataType.FLOAT32: continue current_values = execution_context[tensor] updated_values = current_values", "alveo_default_platform = dict() alveo_default_platform[\"U50\"] = \"xilinx_u50_gen3x16_xdma_201920_3\" alveo_default_platform[\"U200\"] = \"xilinx_u200_xdma_201830_2\" alveo_default_platform[\"U250\"]", "return 1e-2 def get_sanitize_quant_tensors(): \"\"\"Return whether tensors with quantization annotations", "to next # introduces less quicker runtime if dtype ==", "2. Currently this function only works for matrices.\"\"\" # interleave", "# contributors may be used to endorse or promote products", "stitched IP rtlsim: - level 1 shows top-level input/output streams", "is undefined, the default value of 1 is returned. A", "int(os.environ[\"RTLSIM_TRACE_DEPTH\"]) except KeyError: return 1 def get_remote_vivado(): \"\"\"Return the address", "= 2 ** 30 max_prod = -(2 ** 30) for", "x[1]), desired) desired = np.asarray(list(desired), dtype=np.int32) current = np.asarray(ndarray.shape, dtype=np.int32)", "if dtype == DataType.FLOAT32: continue current_values = execution_context[tensor] updated_values =", "NUM_DEFAULT_WORKERS environment variable. If the env.var. is undefined, the default", "return float(os.environ[\"ERROR_THRESH\"]) except KeyError: return 1e-2 def get_sanitize_quant_tensors(): \"\"\"Return whether", "after the existing values pad_amt = list(map(lambda x: (0, x),", "positive.\"\"\" # ensure integers assert int(x) == x, \"The input", "dtype=np.int32) current = np.asarray(ndarray.shape, dtype=np.int32) pad_amt = desired - current", "Exception( \"\"\"Values can't be represented with set finn datatype ({})", "input x is not an integer.\" assert int(factor) == factor,", "finn_dt == DataType.BIPOLAR: tensor_values = np.random.randint(2, size=tensor_shape) tensor_values = 2", "__init__(self): self.include_paths = [] self.cpp_files = [] self.executable_path = \"\"", "factor == -1: return x # ensure positive values assert", "executes it.\"\"\" # raise error if includes are empty self.code_gen_dir", "behavior\") elif len(inds) == 0: return None else: ind =", "depth values are of interest for whole-network stitched IP rtlsim:", "np.pad(ndarray, pad_amt, mode=\"constant\", constant_values=val) assert ( np.asarray(ret.shape, dtype=np.int32) == desired", "only works for matrices.\"\"\" # interleave rows between PEs using", "= -(2 ** 30) for a_val in [dt_a.min(), dt_a.max()]: for", "f.write(bash_compile + \"\\n\") bash_command = [\"bash\", self.compile_script] process_compile = subprocess.Popen(bash_command,", "shape and with given FINN DataType.\"\"\" if type(tensor_shape) == list:", "except KeyError: return 1e-2 def get_sanitize_quant_tensors(): \"\"\"Return whether tensors with", "float_scale is not always equal to int_num. We use this", "be represented \" \"with the set FINN datatype ({}), they", "({}) for input {}\"\"\".format( dtype, tensor ) ) execution_context[tensor] =", "array don't match the length of the pad_to_dims value.\"\"\" #", "prod < min_prod: min_prod = prod if prod > max_prod:", "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES", "string of letters and digits.\"\"\" lettersAndDigits = string.ascii_letters + string.digits", "compute the desired shape desired = zip(list(ndarray.shape), list(pad_to_dims)) desired =", "padding will be inserted after the existing values; otherwise it", "tensor_values = np.random.randint(2, size=tensor_shape) tensor_values = 2 * tensor_values -", "finn_dt == DataType.TERNARY: tensor_values = np.random.randint( finn_dt.min(), high=finn_dt.max() + 1,", "return x + (factor - (x % factor)) def pad_tensor_to_multiple_of(ndarray,", "not supported, no tensor could be generated\".format(finn_dt) ) # always", "pynq_native_port_width[\"Ultra96\"] = 128 pynq_native_port_width[\"ZCU102\"] = 128 pynq_native_port_width[\"ZCU104\"] = 128 #", "# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL", "i, e in enumerate(names) if e == name] if len(inds)", "must retain the above copyright notice, this # list of", "the respective value in pad_to_dims. -1 means do not pad", "tensor_values.astype(np.float32) def calculate_signed_dot_prod_range(dt_a, dt_b, len): \"\"\"Returns the (min,max) values a", "\"\"\"The dimension of the matrix is not 2. Currently this", "matrix_r = matrix.reshape(-1, n_partitions, shp[1]).transpose((1, 0, 2)) matrix_r = matrix_r.reshape(n_partitions,", "return container[ind] def remove_by_name(container, name, name_field=\"name\"): \"\"\"Remove item from container", "command to produces the executable of the c++ code in", "FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT", "the following disclaimer in the documentation # and/or other materials", "# * Redistributions in binary form must reproduce the above", "Vivado synthesis server as set by the, REMOTE_VIVADO environment variable,", "the (min,max) values a dot product between two signed vectors", "\"\" for component in self.compile_components: bash_compile += str(component) + \"", "of types dt_a and dt_b of len elements can take.\"\"\"", "count signals \"\"\" try: return int(os.environ[\"RTLSIM_TRACE_DEPTH\"]) except KeyError: return 1", "padding to get to the desired shape if distr_pad: pad_before", "a float numpy array (container dtype is float) ndarray =", "code_gen_dir): \"\"\"Builds the g++ compiler command according to entries in", "DataType.FLOAT32: continue current_values = execution_context[tensor] updated_values = current_values has_to_be_rounded =", "matrix is not 2. Currently this function only works for", "use float type as container return tensor_values.astype(np.float32) def calculate_signed_dot_prod_range(dt_a, dt_b,", "split evenly between before and after the existing values, with", "updated_values else: raise Exception( \"\"\"Rounding error is too high to", "= list(zip(pad_before, pad_after)) else: # all padding is added after", "extra value inserted after if the padding amount is not", "assert ( ndim == 2 ), \"\"\"The dimension of the", "if x < factor: return factor else: if x %", "factor > 0 and x > 0, \"Factor and x", "undefined behavior\") elif len(inds) == 0: return None else: ind", "or ndarray.dtype != np.float32: # try to convert to a", "boards pynq_native_port_width = dict() pynq_native_port_width[\"Pynq-Z1\"] = 64 pynq_native_port_width[\"Pynq-Z2\"] = 64", "i in range(stringLength)) def interleave_matrix_outer_dim_from_partitions(matrix, n_partitions): \"\"\"Interleave the outermost dimension", "depth for rtlsim via PyVerilator. Controllable via the RTLSIM_TRACE_DEPTH environment", "cloned into.\" try: return os.environ[\"FINN_ROOT\"] except KeyError: raise Exception( \"\"\"Environment", "warnings from finn.core.datatype import DataType # mapping from PYNQ board", "val, so that each dimension is a multiple of the", "specific prior written permission. # # THIS SOFTWARE IS PROVIDED", "import numpy as np import os import random import string", "# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE", "if e == name] if len(inds) > 1: raise Exception(\"Found", "Exception( \"\"\"Environment variable FINN_INST_NAME must be set correctly. Please ensure", "to given path.\"\"\" self.executable_path = path def build(self, code_gen_dir): \"\"\"Builds", "via the RTLSIM_TRACE_DEPTH environment variable. If the env.var. is undefined,", "provided that the following conditions are met: # # *", "== 2 ), \"\"\"The dimension of the matrix is not", "0.\" if x < factor: return factor else: if x", "dtype is float) ndarray = np.asarray(ndarray, dtype=np.float32) assert ndarray.ndim ==", "as np import os import random import string import subprocess", "above copyright notice, this # list of conditions and the", "prod if prod > max_prod: max_prod = prod return (min_prod,", "/ float_scale is not always equal to int_num. We use", "alveo_part_map[\"U280\"] = \"xcu280-fsvh2892-2L-e\" alveo_default_platform = dict() alveo_default_platform[\"U50\"] = \"xilinx_u50_gen3x16_xdma_201920_3\" alveo_default_platform[\"U200\"]", "if finn_dt == DataType.BIPOLAR: tensor_values = np.random.randint(2, size=tensor_shape) tensor_values =", "input datatype acc_min = perceptive_field_elems * min( min_weight * max_input,", "return \"\".join(random.choice(lettersAndDigits) for i in range(stringLength)) def interleave_matrix_outer_dim_from_partitions(matrix, n_partitions): \"\"\"Interleave", "ensure integers assert int(x) == x, \"The input x is", "= os.environ[\"FINN_INST_NAME\"] + \"/\" return tempfile.mkdtemp(prefix=inst_prefix + prefix) except KeyError:", "as a build dir. Use this function instead of tempfile.mkdtemp", "64 pynq_native_port_width[\"Ultra96\"] = 128 pynq_native_port_width[\"ZCU102\"] = 128 pynq_native_port_width[\"ZCU104\"] = 128", "not an integer.\" # use -1 to indicate no padding", "pad_amt = list(map(lambda x: (0, x), pad_amt)) ret = np.pad(ndarray,", "HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER", "- level 3 shows per full-layer I/O including FIFO count", "def sanitize_quant_values(model, node_tensors, execution_context, check_values=False): \"\"\"Sanitize given list of tensors", ") acc_max = perceptive_field_elems * max( min_weight * max_input, min_weight", "\"\" self.code_gen_dir = \"\" self.compile_components = [] self.compile_script = \"\"", "of the matrix is not 2. Currently this function only", "bash script in given folder and executes it.\"\"\" # raise", "= \"xilinx_u50_gen3x16_xdma_201920_3\" alveo_default_platform[\"U200\"] = \"xilinx_u200_xdma_201830_2\" alveo_default_platform[\"U250\"] = \"xilinx_u250_xdma_201830_2\" alveo_default_platform[\"U280\"] =", "* Redistributions of source code must retain the above copyright", "get_execution_error_thresh(): \"Return the max error that is allowed for rounding", "container by .name field if it exists, None otherwise. Will", "= np.asarray(list(desired), dtype=np.int32) current = np.asarray(ndarray.shape, dtype=np.int32) pad_amt = desired", "for i, e in enumerate(names) if e == name] if", "x # ensure positive values assert factor > 0 and", "remove_by_name(container, name, name_field=\"name\"): \"\"\"Remove item from container by .name field", "pad_after)) else: # all padding is added after the existing", "and maximum values of accumulator # assume inputs span the", "including FIFO count signals \"\"\" try: return int(os.environ[\"RTLSIM_TRACE_DEPTH\"]) except KeyError:", "append_includes(self, library_path): \"\"\"Adds given library path to include_paths list.\"\"\" self.include_paths.append(library_path)", "is True: # check again if values can now be", "finn datatype ({}) for input {}\"\"\".format( dtype, tensor ) )", "try to convert to a float numpy array (container dtype", "dtype = model.get_tensor_datatype(tensor) # floats don't need sanitization, skip to", "# ensure # partitions evenly divide the outermost dimension assert", "which is passed to the function build() of this class.\"\"\"", "are found, since this violates the ONNX standard.\"\"\" names =", "include_paths and cpp_files lists. Saves it in bash script in", "must be set correctly. Please ensure you have launched the", "dtype=np.int32) pad_amt = desired - current # add padding to", "= prod return (min_prod, max_prod) def sanitize_quant_values(model, node_tensors, execution_context, check_values=False):", "\" + str(self.executable_path)) for cpp_file in self.cpp_files: self.compile_components.append(cpp_file) for lib", "ndarray.ndim == len( pad_to_dims ), \"\"\"The dimensions of the input", "# compute the desired shape desired = zip(list(ndarray.shape), list(pad_to_dims)) desired", "or promote products derived from # this software without specific", "take.\"\"\" assert ( dt_a.signed() and dt_b.signed() ), \"\"\"The input values", "type as container return tensor_values.astype(np.float32) def calculate_signed_dot_prod_range(dt_a, dt_b, len): \"\"\"Returns", "dot product between two signed vectors of types dt_a and", "), \"\"\"The dimension of the matrix is not 2. Currently", "zip(list(ndarray.shape), list(pad_to_dims)) desired = map(lambda x: roundup_to_integer_multiple(x[0], x[1]), desired) desired", "the minimum and maximum possible result (accumulator) values for a", "OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA,", "(acc_min, acc_max). \"\"\" min_weight = matrix.min() max_weight = matrix.max() perceptive_field_elems", "by default, disabling will yield faster ONNX execution but may", "check_values is specified, an extra DataType.allowed() check will be performed", "ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES", "factor must otherwise be positive.\"\"\" # ensure integers assert int(x)", "c++ code in code_gen_dir which is passed to the function", "execution_context class CppBuilder: \"\"\"Builds the g++ compiler command to produces", "INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF", "2 ), \"\"\"The dimension of the matrix is not 2.", "particular dimension. If distr_pad is False, all padding will be", "and maximum possible result (accumulator) values for a dot product", "items are found, since this violates the ONNX standard.\"\"\" names", "= 64 pynq_native_port_width[\"Pynq-Z2\"] = 64 pynq_native_port_width[\"Ultra96\"] = 128 pynq_native_port_width[\"ZCU102\"] =", "= str(self.code_gen_dir) + \"/compile.sh\" with open(self.compile_script, \"w\") as f: f.write(\"#!/bin/bash", "promote products derived from # this software without specific prior", "# introduces less quicker runtime if dtype == DataType.FLOAT32: continue", "the outermost dimension of a matrix from given partitions (n_partitions).\"\"\"", "will be split evenly between before and after the existing", "IP rtlsim: - level 1 shows top-level input/output streams -", "calculate_signed_dot_prod_range(dt_a, dt_b, len): \"\"\"Returns the (min,max) values a dot product", "folder with given prefix to be used as a build", "be sanitized. Enabled by default, disabling will yield faster ONNX", "# try to convert to a float numpy array (container", "calculate minimum and maximum values of accumulator # assume inputs", "import random import string import subprocess import tempfile import warnings", "of a matrix from given partitions (n_partitions).\"\"\" if type(matrix) !=", "tensor_values = 2 * tensor_values - 1 elif finn_dt ==", "from original values max_error = max(np.abs(current_values - updated_values).flatten()) if max_error", "ndarray using val, so that each dimension is a multiple", "min_input, ) return (acc_min, acc_max) def gen_finn_dt_tensor(finn_dt, tensor_shape): \"\"\"Generates random", "name, name_field) if item is not None: container.remove(item) def random_string(stringLength=6):", "= matrix.min() max_weight = matrix.max() perceptive_field_elems = matrix.shape[0] min_input =", "All rights reserved. # # Redistribution and use in source", "PYNQ board names to FPGA part names pynq_part_map = dict()", "matrix.reshape(-1, n_partitions, shp[1]).transpose((1, 0, 2)) matrix_r = matrix_r.reshape(n_partitions, -1, shp[1])", "\"xczu3eg-sbva484-1-e\" pynq_part_map[\"Pynq-Z1\"] = \"xc7z020clg400-1\" pynq_part_map[\"Pynq-Z2\"] = \"xc7z020clg400-1\" pynq_part_map[\"ZCU102\"] = \"xczu9eg-ffvb1156-2-e\"", "def get_num_default_workers(): \"\"\"Return the number of workers for parallel transformations.", "CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF", "[i for i, e in enumerate(names) if e == name]", "the pad_to_dims value.\"\"\" # compute the desired shape desired =", "name, name_field=\"name\"): \"\"\"Remove item from container by .name field if", "used to endorse or promote products derived from # this", "in bash script in given folder and executes it.\"\"\" #", "import warnings from finn.core.datatype import DataType # mapping from PYNQ", "len( pad_to_dims ), \"\"\"The dimensions of the input array don't", "return None def get_num_default_workers(): \"\"\"Return the number of workers for", "factor. Returns x if factor is set to -1. Both", "(1, MW) with datatype vec_dt. Returns (acc_min, acc_max). \"\"\" min_weight", "match the length of the pad_to_dims value.\"\"\" # compute the", "pad_amt - pad_before pad_amt = list(zip(pad_before, pad_after)) else: # all", "undefined, the default value of 1 is returned. \"\"\" try:", "def append_sources(self, cpp_file): \"\"\"Adds given c++ file to cpp_files list.\"\"\"", "one extra value inserted after if the padding amount is", "array (container dtype is float) matrix = np.asarray(matrix, dtype=np.float32) shp", "PYNQ boards pynq_native_port_width = dict() pynq_native_port_width[\"Pynq-Z1\"] = 64 pynq_native_port_width[\"Pynq-Z2\"] =", "the distribution. # # * Neither the name of Xilinx", "name] if len(inds) > 1: raise Exception(\"Found multiple get_by_name matches,", "it in bash script in given folder and executes it.\"\"\"", "values of tensor {} can't be represented \" \"with the", ").all(), \"\"\"The calculated output array doesn't match the desired/expected one.\"\"\"", "of the remote Vivado synthesis server as set by the,", "< factor: return factor else: if x % factor ==", "= np.pad(ndarray, pad_amt, mode=\"constant\", constant_values=val) assert ( np.asarray(ret.shape, dtype=np.int32) ==", "= \"xcu200-fsgd2104-2-e\" alveo_part_map[\"U250\"] = \"xcu250-figd2104-2L-e\" alveo_part_map[\"U280\"] = \"xcu280-fsvh2892-2L-e\" alveo_default_platform =", "large. Returns the sanitized execution context. If check_values is specified,", "else: ind = inds[0] return container[ind] def remove_by_name(container, name, name_field=\"name\"):", "Alveo device and platform mappings alveo_part_map = dict() alveo_part_map[\"U50\"] =", "len if prod < min_prod: min_prod = prod if prod", "DataType # mapping from PYNQ board names to FPGA part", "synthesis server as set by the, REMOTE_VIVADO environment variable, otherwise", "any generated files will survive on the host after the", "\"\"\" ) def get_execution_error_thresh(): \"Return the max error that is", "padding is added after the existing values pad_amt = list(map(lambda", "return 1 def get_remote_vivado(): \"\"\"Return the address of the remote", "function build() of this class.\"\"\" def __init__(self): self.include_paths = []", "tested for matrices assert ( ndim == 2 ), \"\"\"The", "# * Redistributions of source code must retain the above", "represent integers. Floating point arithmetic can introduce rounding errors, e.g.", "return (acc_min, acc_max) def gen_finn_dt_tensor(finn_dt, tensor_shape): \"\"\"Generates random tensor in", "matrix_r = matrix_r.reshape(n_partitions, -1, shp[1]) return matrix_r def roundup_to_integer_multiple(x, factor):", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"", "rtlsim via PyVerilator. Controllable via the RTLSIM_TRACE_DEPTH environment variable. If", "part names pynq_part_map = dict() pynq_part_map[\"Ultra96\"] = \"xczu3eg-sbva484-1-e\" pynq_part_map[\"Pynq-Z1\"] =", "of 1 will only show top-level signals and yield smaller", "is added after the existing values pad_amt = list(map(lambda x:", "STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING", "tensor {} can't be represented \" \"with the set FINN", "alveo_part_map[\"U250\"] = \"xcu250-figd2104-2L-e\" alveo_part_map[\"U280\"] = \"xcu280-fsvh2892-2L-e\" alveo_default_platform = dict() alveo_default_platform[\"U50\"]", "so that each dimension is a multiple of the respective", "size=tensor_shape ) else: raise ValueError( \"Datatype {} is not supported,", "1: raise Exception(\"Found multiple get_by_name matches, undefined behavior\") elif len(inds)", "to endorse or promote products derived from # this software", "+ 1, size=tensor_shape ) else: raise ValueError( \"Datatype {} is", "is not None: container.remove(item) def random_string(stringLength=6): \"\"\"Randomly generate a string", "the amount of rounding is too large. Returns the sanitized", "from PYNQ board names to FPGA part names pynq_part_map =", "of len elements can take.\"\"\" assert ( dt_a.signed() and dt_b.signed()", "cpp_files list.\"\"\" self.cpp_files.append(cpp_file) def set_executable_path(self, path): \"\"\"Sets member variable \"executable_path\"", "pad_amt = list(zip(pad_before, pad_after)) else: # all padding is added", "can't be represented with set finn datatype ({}) for input", "BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY", "its # contributors may be used to endorse or promote", "INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY,", "whole range of the input datatype acc_min = perceptive_field_elems *", "break if has_to_be_rounded: updated_values = np.round(current_values) warnings.warn( \"The values of", "np.round(current_values) warnings.warn( \"The values of tensor {} can't be represented", "give incorrect results. Use with caution.\"\"\" try: return int(os.environ[\"SANITIZE_QUANT_TENSORS\"]) except", "according to entries in include_paths and cpp_files lists. Saves it", "INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT", "= matrix_r.reshape(n_partitions, -1, shp[1]) return matrix_r def roundup_to_integer_multiple(x, factor): \"\"\"Round", "and cpp_files lists. Saves it in bash script in given", "otherwise be positive.\"\"\" # ensure integers assert int(x) == x,", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS", "otherwise. Will throw an Exception if multiple items are found,", "shows per-layer input/output streams - level 3 shows per full-layer", "of its # contributors may be used to endorse or", "\"\" def append_includes(self, library_path): \"\"\"Adds given library path to include_paths", "don't need sanitization, skip to next # introduces less quicker", "if max_error <= get_execution_error_thresh(): if check_values is True: # check", "for lib in self.include_paths: self.compile_components.append(lib) bash_compile = \"\" for component", "THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A", ".name field if it exists.\"\"\" item = get_by_name(container, name, name_field)", "to match the \" \"FINN datatype.\".format(tensor, dtype) ) # check", "need sanitization, skip to next # introduces less quicker runtime", "I/O including FIFO count signals \"\"\" try: return int(os.environ[\"RTLSIM_TRACE_DEPTH\"]) except", "as set by the, REMOTE_VIVADO environment variable, otherwise return None\"\"\"", "the host after the FINN Docker container exits.\"\"\" try: inst_prefix", "1, size=tensor_shape ) else: raise ValueError( \"Datatype {} is not", ") else: raise ValueError( \"Datatype {} is not supported, no", "will be rounded to match the \" \"FINN datatype.\".format(tensor, dtype)", "script in given folder and executes it.\"\"\" # raise error", "factor): \"\"\"Round up integer x to the nearest integer multiple", "check will be performed on any rounded tensors. Background: FINN", "cpp_file in self.cpp_files: self.compile_components.append(cpp_file) for lib in self.include_paths: self.compile_components.append(lib) bash_compile", "tensors with quantization annotations should be sanitized. Enabled by default,", "except KeyError: raise Exception( \"\"\"Environment variable FINN_INST_NAME must be set", ") ) return execution_context class CppBuilder: \"\"\"Builds the g++ compiler", "FINN uses floating point tensors as a carrier data type", "of 1 is returned. \"\"\" try: return int(os.environ[\"NUM_DEFAULT_WORKERS\"]) except KeyError:", "\"Factor and x are <= 0.\" if x < factor:", "error if includes are empty self.code_gen_dir = code_gen_dir self.compile_components.append(\"g++ -o", "integer.\" # use -1 to indicate no padding needed if", "return None\"\"\" try: return os.environ[\"REMOTE_VIVADO\"] except KeyError: return None def", "input array don't match the length of the pad_to_dims value.\"\"\"", "2020 Xilinx, Inc. # All rights reserved. # # Redistribution", "Xilinx, Inc. # All rights reserved. # # Redistribution and", "of the pad_to_dims value.\"\"\" # compute the desired shape desired", "build(self, code_gen_dir): \"\"\"Builds the g++ compiler command according to entries", "shape desired = zip(list(ndarray.shape), list(pad_to_dims)) desired = map(lambda x: roundup_to_integer_multiple(x[0],", "the trace depth for rtlsim via PyVerilator. Controllable via the", "np.asarray(ndarray, dtype=np.float32) assert ndarray.ndim == len( pad_to_dims ), \"\"\"The dimensions", "\"\"\"Builds the g++ compiler command according to entries in include_paths", "EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO,", "subprocess import tempfile import warnings from finn.core.datatype import DataType #", "interleave_matrix_outer_dim_from_partitions(matrix, n_partitions): \"\"\"Interleave the outermost dimension of a matrix from", "1e-2 def get_sanitize_quant_tensors(): \"\"\"Return whether tensors with quantization annotations should", "must reproduce the above copyright notice, # this list of", "None otherwise. Will throw an Exception if multiple items are", "\"\"\"Rounding error is too high to match set FINN datatype", "lettersAndDigits = string.ascii_letters + string.digits return \"\".join(random.choice(lettersAndDigits) for i in", "respective value in pad_to_dims. -1 means do not pad that", "supposed to be integers are indeed integers. \"\"\" for tensor", "outermost dimension of a matrix from given partitions (n_partitions).\"\"\" if", "raise Exception( \"\"\"Environment variable FINN_ROOT must be set correctly. Please", "True break if has_to_be_rounded: updated_values = np.round(current_values) warnings.warn( \"The values", "(int_num * float_scale) / float_scale is not always equal to", "for input {}\"\"\".format( dtype, tensor ) ) execution_context[tensor] = updated_values", "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT", "have launched the Docker contaier correctly. \"\"\" ) def get_by_name(container,", "1 def get_remote_vivado(): \"\"\"Return the address of the remote Vivado", "* Neither the name of Xilinx nor the names of", "A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL", "class CppBuilder: \"\"\"Builds the g++ compiler command to produces the", "!= np.ndarray or ndarray.dtype != np.float32: # try to convert", "g++ compiler command to produces the executable of the c++", "\"\"\"Return the address of the remote Vivado synthesis server as", "float type as container return tensor_values.astype(np.float32) def calculate_signed_dot_prod_range(dt_a, dt_b, len):", "import string import subprocess import tempfile import warnings from finn.core.datatype", "dtype=np.int32) == desired ).all(), \"\"\"The calculated output array doesn't match", "to the function build() of this class.\"\"\" def __init__(self): self.include_paths", "between before and after the existing values, with one extra", "== 0: return None else: ind = inds[0] return container[ind]", "shape if distr_pad: pad_before = (pad_amt // 2).astype(np.int32) pad_after =", "ONNX execution but may give incorrect results. Use with caution.\"\"\"", "are supposed to be integers (as indicated by their quantization", "(0, x), pad_amt)) ret = np.pad(ndarray, pad_amt, mode=\"constant\", constant_values=val) assert", "dtype is float) matrix = np.asarray(matrix, dtype=np.float32) shp = matrix.shape", "matrix_r def roundup_to_integer_multiple(x, factor): \"\"\"Round up integer x to the", "map(lambda x: roundup_to_integer_multiple(x[0], x[1]), desired) desired = np.asarray(list(desired), dtype=np.int32) current", "value in np.nditer(updated_values): if not dtype.allowed(value): raise Exception( \"\"\"Values can't", "of source code must retain the above copyright notice, this", "name_field) if item is not None: container.remove(item) def random_string(stringLength=6): \"\"\"Randomly", "SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR", "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED.", "partitions (n_partitions).\"\"\" if type(matrix) != np.ndarray or matrix.dtype != np.float32:", "of Xilinx nor the names of its # contributors may", "AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED", "launched the Docker contaier correctly. \"\"\" ) def get_execution_error_thresh(): \"Return", "current_values has_to_be_rounded = False # TODO: vectorize with numpy for", "following depth values are of interest for whole-network stitched IP", "an assertion if the amount of rounding is too large.", "USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE", "for value in np.nditer(updated_values): if not dtype.allowed(value): raise Exception( \"\"\"Values", "= 128 # Alveo device and platform mappings alveo_part_map =", "errors, e.g. (int_num * float_scale) / float_scale is not always", "= (pad_amt // 2).astype(np.int32) pad_after = pad_amt - pad_before pad_amt", "A trace depth of 1 will only show top-level signals", "this software without specific prior written permission. # # THIS", "OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY", "node_tensors: dtype = model.get_tensor_datatype(tensor) # floats don't need sanitization, skip", "the length of the pad_to_dims value.\"\"\" # compute the desired", "\"The input factor is not an integer.\" # use -1", "gen_finn_dt_tensor(finn_dt, tensor_shape): \"\"\"Generates random tensor in given shape and with", "dtype) ) # check if rounded values are not too", "-1. Both x and factor must otherwise be positive.\"\"\" #", "\"The input x is not an integer.\" assert int(factor) ==", "matrix.shape[0] min_input = vec_dt.min() max_input = vec_dt.max() # calculate minimum", "works for matrices.\"\"\" # interleave rows between PEs using reshape", "is cloned into.\" try: return os.environ[\"FINN_ROOT\"] except KeyError: raise Exception(", "can take.\"\"\" assert ( dt_a.signed() and dt_b.signed() ), \"\"\"The input", "self.cpp_files = [] self.executable_path = \"\" self.code_gen_dir = \"\" self.compile_components", "is not divisible by two.\"\"\" if type(ndarray) != np.ndarray or", "+ prefix) except KeyError: raise Exception( \"\"\"Environment variable FINN_INST_NAME must", "list.\"\"\" self.include_paths.append(library_path) def append_sources(self, cpp_file): \"\"\"Adds given c++ file to", "\"\"\"The calculated output array doesn't match the desired/expected one.\"\"\" return", "* Redistributions in binary form must reproduce the above copyright", "\"\"\"Environment variable FINN_ROOT must be set correctly. Please ensure you", "+ \" \" self.compile_script = str(self.code_gen_dir) + \"/compile.sh\" with open(self.compile_script,", "by .name field if it exists, None otherwise. Will throw", "Exception( \"\"\"Rounding error is too high to match set FINN", "OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY", "None: container.remove(item) def random_string(stringLength=6): \"\"\"Randomly generate a string of letters", "CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,", "x * A, given matrix A of dims (MW, MH),", "\"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "the NUM_DEFAULT_WORKERS environment variable. If the env.var. is undefined, the", "n_partitions, shp[1]).transpose((1, 0, 2)) matrix_r = matrix_r.reshape(n_partitions, -1, shp[1]) return", "CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES,", "native AXI HP port width (in bits) for PYNQ boards", "KeyError: raise Exception( \"\"\"Environment variable FINN_INST_NAME must be set correctly.", "on the host after the FINN Docker container exits.\"\"\" try:", "input factor is not an integer.\" # use -1 to", "the root directory that FINN is cloned into.\" try: return", "undefined, the default value of 1 is returned. A trace", "annotations should be sanitized. Enabled by default, disabling will yield", "output array doesn't match the desired/expected one.\"\"\" return ret def", "whole-network stitched IP rtlsim: - level 1 shows top-level input/output", "# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR", "pad_to_dims, val=0, distr_pad=False): \"\"\"Pad each dimension of given NumPy ndarray", "\"xcu200-fsgd2104-2-e\" alveo_part_map[\"U250\"] = \"xcu250-figd2104-2L-e\" alveo_part_map[\"U280\"] = \"xcu280-fsvh2892-2L-e\" alveo_default_platform = dict()", "input values are not both signed vectors.\"\"\" min_prod = 2", "the default value of 1 is returned. \"\"\" try: return", "may give incorrect results. Use with caution.\"\"\" try: return int(os.environ[\"SANITIZE_QUANT_TENSORS\"])", "doesn't match the desired/expected one.\"\"\" return ret def calculate_matvec_accumulator_range(matrix, vec_dt):", "files will survive on the host after the FINN Docker", "for a_val in [dt_a.min(), dt_a.max()]: for b_val in [dt_b.min(), dt_b.max()]:", "x if factor is set to -1. Both x and", "for cpp_file in self.cpp_files: self.compile_components.append(cpp_file) for lib in self.include_paths: self.compile_components.append(lib)", "default, disabling will yield faster ONNX execution but may give", "bash_compile += str(component) + \" \" self.compile_script = str(self.code_gen_dir) +", "library_path): \"\"\"Adds given library path to include_paths list.\"\"\" self.include_paths.append(library_path) def", "alveo_default_platform[\"U200\"] = \"xilinx_u200_xdma_201830_2\" alveo_default_platform[\"U250\"] = \"xilinx_u250_xdma_201830_2\" alveo_default_platform[\"U280\"] = \"xilinx_u280_xdma_201920_3\" def", "str(self.code_gen_dir) + \"/compile.sh\" with open(self.compile_script, \"w\") as f: f.write(\"#!/bin/bash \\n\")", "try: return os.environ[\"REMOTE_VIVADO\"] except KeyError: return None def get_num_default_workers(): \"\"\"Return", "the RTLSIM_TRACE_DEPTH environment variable. If the env.var. is undefined, the", "# Copyright (c) 2020 Xilinx, Inc. # All rights reserved.", "- (x % factor)) def pad_tensor_to_multiple_of(ndarray, pad_to_dims, val=0, distr_pad=False): \"\"\"Pad", "IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE", "or without # modification, are permitted provided that the following", "np.random.randint(2, size=tensor_shape) elif \"INT\" in finn_dt.name or finn_dt == DataType.TERNARY:", "check_values is True: # check again if values can now", "execution_context[tensor] updated_values = current_values has_to_be_rounded = False # TODO: vectorize", "= map(lambda x: roundup_to_integer_multiple(x[0], x[1]), desired) desired = np.asarray(list(desired), dtype=np.int32)", "\"xilinx_u50_gen3x16_xdma_201920_3\" alveo_default_platform[\"U200\"] = \"xilinx_u200_xdma_201830_2\" alveo_default_platform[\"U250\"] = \"xilinx_u250_xdma_201830_2\" alveo_default_platform[\"U280\"] = \"xilinx_u280_xdma_201920_3\"", "sanitized. Enabled by default, disabling will yield faster ONNX execution", "HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT,", "{}\"\"\".format( dtype, tensor ) ) execution_context[tensor] = updated_values else: raise", "is not an integer.\" # use -1 to indicate no", "will be inserted after the existing values; otherwise it will", "\" self.compile_script = str(self.code_gen_dir) + \"/compile.sh\" with open(self.compile_script, \"w\") as", "will yield faster ONNX execution but may give incorrect results.", "1 is returned. A trace depth of 1 will only", "if len(inds) > 1: raise Exception(\"Found multiple get_by_name matches, undefined", "via PyVerilator. Controllable via the RTLSIM_TRACE_DEPTH environment variable. If the", "return tempfile.mkdtemp(prefix=inst_prefix + prefix) except KeyError: raise Exception( \"\"\"Environment variable", "extra DataType.allowed() check will be performed on any rounded tensors.", "datatype # TODO: vectorize with numpy for value in np.nditer(updated_values):", "names = [getattr(x, name_field) for x in container] inds =", "elif \"INT\" in finn_dt.name or finn_dt == DataType.TERNARY: tensor_values =", "mapping from PYNQ board names to FPGA part names pynq_part_map", "= [i for i, e in enumerate(names) if e ==", "KeyError: # enabled by default return 1 def make_build_dir(prefix=\"\"): \"\"\"Creates", "of the respective value in pad_to_dims. -1 means do not", "compiler command according to entries in include_paths and cpp_files lists.", "\"\"\"Remove item from container by .name field if it exists.\"\"\"", "prod = a_val * b_val * len if prod <", "given prefix to be used as a build dir. Use", "type(ndarray) != np.ndarray or ndarray.dtype != np.float32: # try to", "> max_prod: max_prod = prod return (min_prod, max_prod) def sanitize_quant_values(model,", "ValueError( \"Datatype {} is not supported, no tensor could be", "Docker contaier correctly. \"\"\" ) def get_execution_error_thresh(): \"Return the max", "\"xc7z020clg400-1\" pynq_part_map[\"Pynq-Z2\"] = \"xc7z020clg400-1\" pynq_part_map[\"ZCU102\"] = \"xczu9eg-ffvb1156-2-e\" pynq_part_map[\"ZCU104\"] = \"xczu7ev-ffvc1156-2-e\"", "existing values, with one extra value inserted after if the", "always use float type as container return tensor_values.astype(np.float32) def calculate_signed_dot_prod_range(dt_a,", "needed if factor == -1: return x # ensure positive", "pynq_part_map[\"Pynq-Z2\"] = \"xc7z020clg400-1\" pynq_part_map[\"ZCU102\"] = \"xczu9eg-ffvb1156-2-e\" pynq_part_map[\"ZCU104\"] = \"xczu7ev-ffvc1156-2-e\" #", "== DataType.BIPOLAR: tensor_values = np.random.randint(2, size=tensor_shape) tensor_values = 2 *", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL #", "input {}\"\"\".format( dtype, tensor ) ) return execution_context class CppBuilder:", "e == name] if len(inds) > 1: raise Exception(\"Found multiple", "dimensions of the input array don't match the length of", "acc_max) def gen_finn_dt_tensor(finn_dt, tensor_shape): \"\"\"Generates random tensor in given shape", "\"xilinx_u280_xdma_201920_3\" def get_rtlsim_trace_depth(): \"\"\"Return the trace depth for rtlsim via", "execution.\" try: return float(os.environ[\"ERROR_THRESH\"]) except KeyError: return 1e-2 def get_sanitize_quant_tensors():", "except KeyError: return 1 def get_remote_vivado(): \"\"\"Return the address of", "= \"\" for component in self.compile_components: bash_compile += str(component) +", "0 ), \"\"\"The outermost dimension is not divisable by the", "list(map(lambda x: (0, x), pad_amt)) ret = np.pad(ndarray, pad_amt, mode=\"constant\",", "max_weight * max_input, max_weight * min_input, ) return (acc_min, acc_max)", "outermost dimension is not divisable by the number of partitions.\"\"\"", "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND", "check again if values can now be represented with set", "use in source and binary forms, with or without #", "* max_input, min_weight * min_input, max_weight * max_input, max_weight *", "np.random.randint(2, size=tensor_shape) tensor_values = 2 * tensor_values - 1 elif", "code_gen_dir self.compile_components.append(\"g++ -o \" + str(self.executable_path)) for cpp_file in self.cpp_files:", "datatype vec_dt. Returns (acc_min, acc_max). \"\"\" min_weight = matrix.min() max_weight", "Docker container exits.\"\"\" try: inst_prefix = os.environ[\"FINN_INST_NAME\"] + \"/\" return", "), \"\"\"The outermost dimension is not divisable by the number", "= dict() alveo_default_platform[\"U50\"] = \"xilinx_u50_gen3x16_xdma_201920_3\" alveo_default_platform[\"U200\"] = \"xilinx_u200_xdma_201830_2\" alveo_default_platform[\"U250\"] =", "tensor in given shape and with given FINN DataType.\"\"\" if", "carrier data type to represent integers. Floating point arithmetic can", "pad_before pad_amt = list(zip(pad_before, pad_after)) else: # all padding is", "use this function to ensure that the values that are", "with open(self.compile_script, \"w\") as f: f.write(\"#!/bin/bash \\n\") f.write(bash_compile + \"\\n\")", "\"xc7z020clg400-1\" pynq_part_map[\"ZCU102\"] = \"xczu9eg-ffvb1156-2-e\" pynq_part_map[\"ZCU104\"] = \"xczu7ev-ffvc1156-2-e\" # native AXI", "in enumerate(names) if e == name] if len(inds) > 1:", ") return execution_context class CppBuilder: \"\"\"Builds the g++ compiler command", "field if it exists, None otherwise. Will throw an Exception", "- current # add padding to get to the desired", "and the following disclaimer. # # * Redistributions in binary", "def get_execution_error_thresh(): \"Return the max error that is allowed for", "to be used as a build dir. Use this function", "now be represented with set finn datatype # TODO: vectorize", "and digits.\"\"\" lettersAndDigits = string.ascii_letters + string.digits return \"\".join(random.choice(lettersAndDigits) for", "each dimension of given NumPy ndarray using val, so that", "PEs using reshape + transpose matrix_r = matrix.reshape(-1, n_partitions, shp[1]).transpose((1,", "inserted after the existing values; otherwise it will be split", "COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT,", "product x * A, given matrix A of dims (MW,", "# # * Redistributions of source code must retain the", "def append_includes(self, library_path): \"\"\"Adds given library path to include_paths list.\"\"\"", "violates the ONNX standard.\"\"\" names = [getattr(x, name_field) for x", "\"w\") as f: f.write(\"#!/bin/bash \\n\") f.write(bash_compile + \"\\n\") bash_command =", "in container] inds = [i for i, e in enumerate(names)", "to ensure any generated files will survive on the host", "rounded values are not too far from original values max_error", "values can now be represented with set finn datatype #", "- 1 elif finn_dt == DataType.BINARY: tensor_values = np.random.randint(2, size=tensor_shape)", "padding needed if factor == -1: return x # ensure", "prod > max_prod: max_prod = prod return (min_prod, max_prod) def", "be inserted after the existing values; otherwise it will be", "datatype ({}) for input {}\"\"\".format( dtype, tensor ) ) execution_context[tensor]", "\"executable_path\" to given path.\"\"\" self.executable_path = path def build(self, code_gen_dir):", "matrix = np.asarray(matrix, dtype=np.float32) shp = matrix.shape ndim = matrix.ndim", "\"\"\"Return whether tensors with quantization annotations should be sanitized. Enabled", "this violates the ONNX standard.\"\"\" names = [getattr(x, name_field) for", "always equal to int_num. We use this function to ensure", "return (min_prod, max_prod) def sanitize_quant_values(model, node_tensors, execution_context, check_values=False): \"\"\"Sanitize given", "FINN execution.\" try: return float(os.environ[\"ERROR_THRESH\"]) except KeyError: return 1e-2 def", "max( min_weight * max_input, min_weight * min_input, max_weight * max_input,", "return int(os.environ[\"SANITIZE_QUANT_TENSORS\"]) except KeyError: # enabled by default return 1", "else: return x + (factor - (x % factor)) def", "min_prod: min_prod = prod if prod > max_prod: max_prod =", "finn_dt.name or finn_dt == DataType.TERNARY: tensor_values = np.random.randint( finn_dt.min(), high=finn_dt.max()", "= 64 pynq_native_port_width[\"Ultra96\"] = 128 pynq_native_port_width[\"ZCU102\"] = 128 pynq_native_port_width[\"ZCU104\"] =", "inputs span the whole range of the input datatype acc_min", "return None else: ind = inds[0] return container[ind] def remove_by_name(container,", "prior written permission. # # THIS SOFTWARE IS PROVIDED BY", "will only show top-level signals and yield smaller .vcd files.", "x % factor == 0: return x else: return x", "are indeed integers. \"\"\" for tensor in node_tensors: dtype =", "append_sources(self, cpp_file): \"\"\"Adds given c++ file to cpp_files list.\"\"\" self.cpp_files.append(cpp_file)", "floats don't need sanitization, skip to next # introduces less", "HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR", "prefix to be used as a build dir. Use this", "list: tensor_shape = tuple(tensor_shape) if finn_dt == DataType.BIPOLAR: tensor_values =", "are of interest for whole-network stitched IP rtlsim: - level", "+ str(self.executable_path)) for cpp_file in self.cpp_files: self.compile_components.append(cpp_file) for lib in", "set by the, REMOTE_VIVADO environment variable, otherwise return None\"\"\" try:", "= \"xcu280-fsvh2892-2L-e\" alveo_default_platform = dict() alveo_default_platform[\"U50\"] = \"xilinx_u50_gen3x16_xdma_201920_3\" alveo_default_platform[\"U200\"] =", "# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS", "= \"xilinx_u200_xdma_201830_2\" alveo_default_platform[\"U250\"] = \"xilinx_u250_xdma_201830_2\" alveo_default_platform[\"U280\"] = \"xilinx_u280_xdma_201920_3\" def get_rtlsim_trace_depth():", "constant_values=val) assert ( np.asarray(ret.shape, dtype=np.int32) == desired ).all(), \"\"\"The calculated", "finn_dt.min(), high=finn_dt.max() + 1, size=tensor_shape ) else: raise ValueError( \"Datatype", "an extra DataType.allowed() check will be performed on any rounded", "def gen_finn_dt_tensor(finn_dt, tensor_shape): \"\"\"Generates random tensor in given shape and", "value of 1 is returned. \"\"\" try: return int(os.environ[\"NUM_DEFAULT_WORKERS\"]) except", "result (accumulator) values for a dot product x * A,", "between PEs using reshape + transpose matrix_r = matrix.reshape(-1, n_partitions,", "(as indicated by their quantization annotation). Will raise an assertion", "variable, otherwise return None\"\"\" try: return os.environ[\"REMOTE_VIVADO\"] except KeyError: return", "AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT", "string.digits return \"\".join(random.choice(lettersAndDigits) for i in range(stringLength)) def interleave_matrix_outer_dim_from_partitions(matrix, n_partitions):", "-1: return x # ensure positive values assert factor >", "equal to int_num. We use this function to ensure that", "with one extra value inserted after if the padding amount", "the desired/expected one.\"\"\" return ret def calculate_matvec_accumulator_range(matrix, vec_dt): \"\"\"Calculate the", "string import subprocess import tempfile import warnings from finn.core.datatype import", "be integers (as indicated by their quantization annotation). Will raise", "the existing values, with one extra value inserted after if", "\"\"\"Interleave the outermost dimension of a matrix from given partitions", "the default value of 1 is returned. A trace depth", "the matrix is not 2. Currently this function only works", "assert ( dt_a.signed() and dt_b.signed() ), \"\"\"The input values are", "rounded to match the \" \"FINN datatype.\".format(tensor, dtype) ) #", "be represented with set finn datatype # TODO: vectorize with", "of tensor {} can't be represented \" \"with the set", "Xilinx nor the names of its # contributors may be", "names to FPGA part names pynq_part_map = dict() pynq_part_map[\"Ultra96\"] =", "-o \" + str(self.executable_path)) for cpp_file in self.cpp_files: self.compile_components.append(cpp_file) for", "dimension assert ( shp[0] % n_partitions == 0 ), \"\"\"The", "floating point tensors as a carrier data type to represent", "64 pynq_native_port_width[\"Pynq-Z2\"] = 64 pynq_native_port_width[\"Ultra96\"] = 128 pynq_native_port_width[\"ZCU102\"] = 128", "in self.compile_components: bash_compile += str(component) + \" \" self.compile_script =", "f.write(\"#!/bin/bash \\n\") f.write(bash_compile + \"\\n\") bash_command = [\"bash\", self.compile_script] process_compile", "dict() pynq_part_map[\"Ultra96\"] = \"xczu3eg-sbva484-1-e\" pynq_part_map[\"Pynq-Z1\"] = \"xc7z020clg400-1\" pynq_part_map[\"Pynq-Z2\"] = \"xc7z020clg400-1\"", "address of the remote Vivado synthesis server as set by", "\" \"FINN datatype.\".format(tensor, dtype) ) # check if rounded values", "with numpy for value in np.nditer(updated_values): if not dtype.allowed(value): raise", "and x > 0, \"Factor and x are <= 0.\"", "# list of conditions and the following disclaimer. # #", "that are supposed to be integers are indeed integers. \"\"\"", "it exists.\"\"\" item = get_by_name(container, name, name_field) if item is", "default return 1 def make_build_dir(prefix=\"\"): \"\"\"Creates a temporary folder with", "in finn_dt.name or finn_dt == DataType.TERNARY: tensor_values = np.random.randint( finn_dt.min(),", "entries in include_paths and cpp_files lists. Saves it in bash", "> 0 and x > 0, \"Factor and x are", "Redistributions in binary form must reproduce the above copyright notice,", "x: roundup_to_integer_multiple(x[0], x[1]), desired) desired = np.asarray(list(desired), dtype=np.int32) current =", "a multiple of the respective value in pad_to_dims. -1 means", "not 2. Currently this function only works for matrices.\"\"\" #", "int(os.environ[\"SANITIZE_QUANT_TENSORS\"]) except KeyError: # enabled by default return 1 def", "AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN", "\"\"\"Generates random tensor in given shape and with given FINN", "if type(ndarray) != np.ndarray or ndarray.dtype != np.float32: # try", ") # check if rounded values are not too far", "- updated_values).flatten()) if max_error <= get_execution_error_thresh(): if check_values is True:", "multiple of integer factor. Returns x if factor is set", "variable. If the env.var. is undefined, the default value of", "return execution_context class CppBuilder: \"\"\"Builds the g++ compiler command to", "= execution_context[tensor] updated_values = current_values has_to_be_rounded = False # TODO:", "= np.round(current_values) warnings.warn( \"The values of tensor {} can't be", "generated files will survive on the host after the FINN", "# mapping from PYNQ board names to FPGA part names", "len(inds) > 1: raise Exception(\"Found multiple get_by_name matches, undefined behavior\")", "desired) desired = np.asarray(list(desired), dtype=np.int32) current = np.asarray(ndarray.shape, dtype=np.int32) pad_amt", "\"\"\"Return the trace depth for rtlsim via PyVerilator. Controllable via", "NumPy ndarray using val, so that each dimension is a", "pad_after = pad_amt - pad_before pad_amt = list(zip(pad_before, pad_after)) else:", "* min_input, max_weight * max_input, max_weight * min_input, ) return", "pynq_native_port_width[\"ZCU102\"] = 128 pynq_native_port_width[\"ZCU104\"] = 128 # Alveo device and", "dir. Use this function instead of tempfile.mkdtemp to ensure any", "port width (in bits) for PYNQ boards pynq_native_port_width = dict()", "letters and digits.\"\"\" lettersAndDigits = string.ascii_letters + string.digits return \"\".join(random.choice(lettersAndDigits)", "FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO", "pad that particular dimension. If distr_pad is False, all padding", "= 128 pynq_native_port_width[\"ZCU102\"] = 128 pynq_native_port_width[\"ZCU104\"] = 128 # Alveo", "given c++ file to cpp_files list.\"\"\" self.cpp_files.append(cpp_file) def set_executable_path(self, path):", "warnings.warn( \"The values of tensor {} can't be represented \"", "reshape + transpose matrix_r = matrix.reshape(-1, n_partitions, shp[1]).transpose((1, 0, 2))", "matrix.shape ndim = matrix.ndim # ensure # partitions evenly divide", "all padding will be inserted after the existing values; otherwise", "self.include_paths = [] self.cpp_files = [] self.executable_path = \"\" self.code_gen_dir", "of interest for whole-network stitched IP rtlsim: - level 1", "+ \"\\n\") bash_command = [\"bash\", self.compile_script] process_compile = subprocess.Popen(bash_command, stdout=subprocess.PIPE)", "given path.\"\"\" self.executable_path = path def build(self, code_gen_dir): \"\"\"Builds the", "integer x to the nearest integer multiple of integer factor.", "as f: f.write(\"#!/bin/bash \\n\") f.write(bash_compile + \"\\n\") bash_command = [\"bash\",", "= \"xcu50-fsvh2104-2L-e\" alveo_part_map[\"U200\"] = \"xcu200-fsgd2104-2-e\" alveo_part_map[\"U250\"] = \"xcu250-figd2104-2L-e\" alveo_part_map[\"U280\"] =", "by rounding values that are supposed to be integers (as", "correctly. \"\"\" ) def get_execution_error_thresh(): \"Return the max error that", "copyright notice, # this list of conditions and the following", "alveo_default_platform[\"U250\"] = \"xilinx_u250_xdma_201830_2\" alveo_default_platform[\"U280\"] = \"xilinx_u280_xdma_201920_3\" def get_rtlsim_trace_depth(): \"\"\"Return the", "\"Return the max error that is allowed for rounding in", "values max_error = max(np.abs(current_values - updated_values).flatten()) if max_error <= get_execution_error_thresh():", "dtype.allowed(value): raise Exception( \"\"\"Values can't be represented with set finn", "Controllable via the NUM_DEFAULT_WORKERS environment variable. If the env.var. is", "an integer.\" assert int(factor) == factor, \"The input factor is", "for a dot product x * A, given matrix A", "using reshape + transpose matrix_r = matrix.reshape(-1, n_partitions, shp[1]).transpose((1, 0,", "\"\"\" ) def get_by_name(container, name, name_field=\"name\"): \"\"\"Return item from container", "given library path to include_paths list.\"\"\" self.include_paths.append(library_path) def append_sources(self, cpp_file):", "calculate_matvec_accumulator_range(matrix, vec_dt): \"\"\"Calculate the minimum and maximum possible result (accumulator)", "passed to the function build() of this class.\"\"\" def __init__(self):", "name of Xilinx nor the names of its # contributors", "max_input, max_weight * min_input, ) return (acc_min, acc_max) def gen_finn_dt_tensor(finn_dt,", "dtype=np.float32) shp = matrix.shape ndim = matrix.ndim # ensure #", "root directory that FINN is cloned into.\" try: return os.environ[\"FINN_ROOT\"]", "be used as a build dir. Use this function instead", "the outermost dimension assert ( shp[0] % n_partitions == 0", "* min_input, ) acc_max = perceptive_field_elems * max( min_weight *", "== DataType.BINARY: tensor_values = np.random.randint(2, size=tensor_shape) elif \"INT\" in finn_dt.name", "ndim = matrix.ndim # ensure # partitions evenly divide the", "[getattr(x, name_field) for x in container] inds = [i for", "with datatype vec_dt. Returns (acc_min, acc_max). \"\"\" min_weight = matrix.min()", "of rounding is too large. Returns the sanitized execution context.", "mappings alveo_part_map = dict() alveo_part_map[\"U50\"] = \"xcu50-fsvh2104-2L-e\" alveo_part_map[\"U200\"] = \"xcu200-fsgd2104-2-e\"", "Returns x if factor is set to -1. Both x", "LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", "self.executable_path = \"\" self.code_gen_dir = \"\" self.compile_components = [] self.compile_script", "* max_input, max_weight * min_input, ) return (acc_min, acc_max) def", "pynq_native_port_width[\"Pynq-Z1\"] = 64 pynq_native_port_width[\"Pynq-Z2\"] = 64 pynq_native_port_width[\"Ultra96\"] = 128 pynq_native_port_width[\"ZCU102\"]", "build dir. Use this function instead of tempfile.mkdtemp to ensure", "MW) with datatype vec_dt. Returns (acc_min, acc_max). \"\"\" min_weight =", "given shape and with given FINN DataType.\"\"\" if type(tensor_shape) ==", "without # modification, are permitted provided that the following conditions", "n_partitions == 0 ), \"\"\"The outermost dimension is not divisable", "the nearest integer multiple of integer factor. Returns x if", "(x % factor)) def pad_tensor_to_multiple_of(ndarray, pad_to_dims, val=0, distr_pad=False): \"\"\"Pad each", "as a carrier data type to represent integers. Floating point", "platform mappings alveo_part_map = dict() alveo_part_map[\"U50\"] = \"xcu50-fsvh2104-2L-e\" alveo_part_map[\"U200\"] =", "signals \"\"\" try: return int(os.environ[\"RTLSIM_TRACE_DEPTH\"]) except KeyError: return 1 def", ") def get_execution_error_thresh(): \"Return the max error that is allowed", "== list: tensor_shape = tuple(tensor_shape) if finn_dt == DataType.BIPOLAR: tensor_values", "get_remote_vivado(): \"\"\"Return the address of the remote Vivado synthesis server", "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY", "interleave rows between PEs using reshape + transpose matrix_r =", "pad_to_dims. -1 means do not pad that particular dimension. If", "empty self.code_gen_dir = code_gen_dir self.compile_components.append(\"g++ -o \" + str(self.executable_path)) for", ") def get_by_name(container, name, name_field=\"name\"): \"\"\"Return item from container by", "IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR", "THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF", "= [getattr(x, name_field) for x in container] inds = [i", "string.ascii_letters + string.digits return \"\".join(random.choice(lettersAndDigits) for i in range(stringLength)) def", "the number of partitions.\"\"\" # only tested for matrices assert", "divide the outermost dimension assert ( shp[0] % n_partitions ==", ".vcd files. The following depth values are of interest for", "from container by .name field if it exists.\"\"\" item =", "max_input, min_weight * min_input, max_weight * max_input, max_weight * min_input,", "float numpy array (container dtype is float) ndarray = np.asarray(ndarray,", "values; otherwise it will be split evenly between before and", "in self.include_paths: self.compile_components.append(lib) bash_compile = \"\" for component in self.compile_components:", "\"\"\" for tensor in node_tensors: dtype = model.get_tensor_datatype(tensor) # floats", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "max_prod = -(2 ** 30) for a_val in [dt_a.min(), dt_a.max()]:", "return tensor_values.astype(np.float32) def calculate_signed_dot_prod_range(dt_a, dt_b, len): \"\"\"Returns the (min,max) values", "don't match the length of the pad_to_dims value.\"\"\" # compute", "min_weight * max_input, min_weight * min_input, max_weight * max_input, max_weight", "found, since this violates the ONNX standard.\"\"\" names = [getattr(x,", "desired ).all(), \"\"\"The calculated output array doesn't match the desired/expected", "container return tensor_values.astype(np.float32) def calculate_signed_dot_prod_range(dt_a, dt_b, len): \"\"\"Returns the (min,max)", "TODO: vectorize with numpy for value in np.nditer(updated_values): if not", "calculated output array doesn't match the desired/expected one.\"\"\" return ret", "Returns (acc_min, acc_max). \"\"\" min_weight = matrix.min() max_weight = matrix.max()", "datatype ({}) for input {}\"\"\".format( dtype, tensor ) ) return", "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #", "permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "dt_b of len elements can take.\"\"\" assert ( dt_a.signed() and", "# check again if values can now be represented with", "!= np.float32: # try to convert to a float numpy", "level 3 shows per full-layer I/O including FIFO count signals", "temporary folder with given prefix to be used as a", "with caution.\"\"\" try: return int(os.environ[\"SANITIZE_QUANT_TENSORS\"]) except KeyError: # enabled by", "matrix.dtype != np.float32: # try to convert to a float", "outermost dimension assert ( shp[0] % n_partitions == 0 ),", "finn datatype # TODO: vectorize with numpy for value in", "represented with set finn datatype ({}) for input {}\"\"\".format( dtype,", "will be performed on any rounded tensors. Background: FINN uses", "they will be rounded to match the \" \"FINN datatype.\".format(tensor,", "USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED", "IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "top-level signals and yield smaller .vcd files. The following depth", "x < factor: return factor else: if x % factor", "0: return None else: ind = inds[0] return container[ind] def", "np.random.randint( finn_dt.min(), high=finn_dt.max() + 1, size=tensor_shape ) else: raise ValueError(", "= matrix.max() perceptive_field_elems = matrix.shape[0] min_input = vec_dt.min() max_input =", "that FINN is cloned into.\" try: return os.environ[\"FINN_ROOT\"] except KeyError:", "KeyError: return None def get_num_default_workers(): \"\"\"Return the number of workers", "roundup_to_integer_multiple(x[0], x[1]), desired) desired = np.asarray(list(desired), dtype=np.int32) current = np.asarray(ndarray.shape,", "added after the existing values pad_amt = list(map(lambda x: (0,", "too large. Returns the sanitized execution context. If check_values is", "numpy as np import os import random import string import", "int(factor) == factor, \"The input factor is not an integer.\"", "acc_max). \"\"\" min_weight = matrix.min() max_weight = matrix.max() perceptive_field_elems =", "execution context. If check_values is specified, an extra DataType.allowed() check", "min_prod = 2 ** 30 max_prod = -(2 ** 30)", "2)) matrix_r = matrix_r.reshape(n_partitions, -1, shp[1]) return matrix_r def roundup_to_integer_multiple(x,", "array (container dtype is float) ndarray = np.asarray(ndarray, dtype=np.float32) assert", "tensor ) ) execution_context[tensor] = updated_values else: raise Exception( \"\"\"Rounding", "IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numpy", "size=tensor_shape) tensor_values = 2 * tensor_values - 1 elif finn_dt", "rounded tensors. Background: FINN uses floating point tensors as a", "value inserted after if the padding amount is not divisible", "len elements can take.\"\"\" assert ( dt_a.signed() and dt_b.signed() ),", "* min_input, ) return (acc_min, acc_max) def gen_finn_dt_tensor(finn_dt, tensor_shape): \"\"\"Generates", "get_num_default_workers(): \"\"\"Return the number of workers for parallel transformations. Controllable", "# check if rounded values are not too far from", "to the desired shape if distr_pad: pad_before = (pad_amt //", "TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT", "is False, all padding will be inserted after the existing", "execution_context, check_values=False): \"\"\"Sanitize given list of tensors in execution_context by", "<= get_execution_error_thresh(): if check_values is True: # check again if", "full-layer I/O including FIFO count signals \"\"\" try: return int(os.environ[\"RTLSIM_TRACE_DEPTH\"])", "dict() alveo_part_map[\"U50\"] = \"xcu50-fsvh2104-2L-e\" alveo_part_map[\"U200\"] = \"xcu200-fsgd2104-2-e\" alveo_part_map[\"U250\"] = \"xcu250-figd2104-2L-e\"", "and yield smaller .vcd files. The following depth values are", "x is not an integer.\" assert int(factor) == factor, \"The", "and dt_b of len elements can take.\"\"\" assert ( dt_a.signed()", "(pad_amt // 2).astype(np.int32) pad_after = pad_amt - pad_before pad_amt =", "number of partitions.\"\"\" # only tested for matrices assert (", "self.code_gen_dir = code_gen_dir self.compile_components.append(\"g++ -o \" + str(self.executable_path)) for cpp_file", "with given prefix to be used as a build dir.", "if type(tensor_shape) == list: tensor_shape = tuple(tensor_shape) if finn_dt ==", "of this class.\"\"\" def __init__(self): self.include_paths = [] self.cpp_files =", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND", "to be integers are indeed integers. \"\"\" for tensor in", "Will throw an Exception if multiple items are found, since", "to match set FINN datatype ({}) for input {}\"\"\".format( dtype,", "if multiple items are found, since this violates the ONNX", "via the NUM_DEFAULT_WORKERS environment variable. If the env.var. is undefined,", "of the input array don't match the length of the", "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF", "all padding is added after the existing values pad_amt =", "AXI HP port width (in bits) for PYNQ boards pynq_native_port_width", "above copyright notice, # this list of conditions and the", "range of the input datatype acc_min = perceptive_field_elems * min(", "not None: container.remove(item) def random_string(stringLength=6): \"\"\"Randomly generate a string of", "# # Redistribution and use in source and binary forms,", "dimension. If distr_pad is False, all padding will be inserted", "min_input, ) acc_max = perceptive_field_elems * max( min_weight * max_input,", "* float_scale) / float_scale is not always equal to int_num.", "inserted after if the padding amount is not divisible by", "indeed integers. \"\"\" for tensor in node_tensors: dtype = model.get_tensor_datatype(tensor)", "with the distribution. # # * Neither the name of", "add padding to get to the desired shape if distr_pad:", "env.var. is undefined, the default value of 1 is returned.", "into.\" try: return os.environ[\"FINN_ROOT\"] except KeyError: raise Exception( \"\"\"Environment variable", "are <= 0.\" if x < factor: return factor else:", "), \"\"\"The dimensions of the input array don't match the", "be split evenly between before and after the existing values,", "from # this software without specific prior written permission. #", "types dt_a and dt_b of len elements can take.\"\"\" assert", "the g++ compiler command according to entries in include_paths and", "path): \"\"\"Sets member variable \"executable_path\" to given path.\"\"\" self.executable_path =", "matrix.max() perceptive_field_elems = matrix.shape[0] min_input = vec_dt.min() max_input = vec_dt.max()", "names pynq_part_map = dict() pynq_part_map[\"Ultra96\"] = \"xczu3eg-sbva484-1-e\" pynq_part_map[\"Pynq-Z1\"] = \"xc7z020clg400-1\"", "Enabled by default, disabling will yield faster ONNX execution but", "partitions evenly divide the outermost dimension assert ( shp[0] %", "int_num. We use this function to ensure that the values", "if prod < min_prod: min_prod = prod if prod >", "min_prod = prod if prod > max_prod: max_prod = prod", "if not dtype.allowed(value): raise Exception( \"\"\"Values can't be represented with", "by the number of partitions.\"\"\" # only tested for matrices", "source and binary forms, with or without # modification, are", "model.get_tensor_datatype(tensor) # floats don't need sanitization, skip to next #", "PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE", "try: return os.environ[\"FINN_ROOT\"] except KeyError: raise Exception( \"\"\"Environment variable FINN_ROOT", "top-level input/output streams - level 2 shows per-layer input/output streams", "get_by_name(container, name, name_field=\"name\"): \"\"\"Return item from container by .name field", "container by .name field if it exists.\"\"\" item = get_by_name(container,", "ANY WAY OUT OF THE USE # OF THIS SOFTWARE,", "os.environ[\"REMOTE_VIVADO\"] except KeyError: return None def get_num_default_workers(): \"\"\"Return the number", "vector (1, MW) with datatype vec_dt. Returns (acc_min, acc_max). \"\"\"", "FINN DataType.\"\"\" if type(tensor_shape) == list: tensor_shape = tuple(tensor_shape) if", "function instead of tempfile.mkdtemp to ensure any generated files will", "it exists, None otherwise. Will throw an Exception if multiple", "container] inds = [i for i, e in enumerate(names) if", "get_sanitize_quant_tensors(): \"\"\"Return whether tensors with quantization annotations should be sanitized.", "datatype.\".format(tensor, dtype) ) # check if rounded values are not", "values a dot product between two signed vectors of types", "to int_num. We use this function to ensure that the", "input/output streams - level 2 shows per-layer input/output streams -", "supposed to be integers (as indicated by their quantization annotation).", "= inds[0] return container[ind] def remove_by_name(container, name, name_field=\"name\"): \"\"\"Remove item", "OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR", "tempfile import warnings from finn.core.datatype import DataType # mapping from", "SUCH DAMAGE. import numpy as np import os import random", "raise Exception(\"Found multiple get_by_name matches, undefined behavior\") elif len(inds) ==", "ensure any generated files will survive on the host after", "PyVerilator. Controllable via the RTLSIM_TRACE_DEPTH environment variable. If the env.var.", "= \"xilinx_u280_xdma_201920_3\" def get_rtlsim_trace_depth(): \"\"\"Return the trace depth for rtlsim", "tensor ) ) return execution_context class CppBuilder: \"\"\"Builds the g++", "== DataType.TERNARY: tensor_values = np.random.randint( finn_dt.min(), high=finn_dt.max() + 1, size=tensor_shape", "error that is allowed for rounding in FINN execution.\" try:", "None else: ind = inds[0] return container[ind] def remove_by_name(container, name,", "30) for a_val in [dt_a.min(), dt_a.max()]: for b_val in [dt_b.min(),", "yield smaller .vcd files. The following depth values are of", "of 1 is returned. A trace depth of 1 will", "path to include_paths list.\"\"\" self.include_paths.append(library_path) def append_sources(self, cpp_file): \"\"\"Adds given", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE", "min_input, max_weight * max_input, max_weight * min_input, ) return (acc_min,", "2).astype(np.int32) pad_after = pad_amt - pad_before pad_amt = list(zip(pad_before, pad_after))", "is float) ndarray = np.asarray(ndarray, dtype=np.float32) assert ndarray.ndim == len(", "assume inputs span the whole range of the input datatype", "be positive.\"\"\" # ensure integers assert int(x) == x, \"The", "notice, # this list of conditions and the following disclaimer", "in self.cpp_files: self.compile_components.append(cpp_file) for lib in self.include_paths: self.compile_components.append(lib) bash_compile =", "128 pynq_native_port_width[\"ZCU102\"] = 128 pynq_native_port_width[\"ZCU104\"] = 128 # Alveo device", "only tested for matrices assert ( ndim == 2 ),", "1 def get_finn_root(): \"Return the root directory that FINN is", "= \"xczu3eg-sbva484-1-e\" pynq_part_map[\"Pynq-Z1\"] = \"xc7z020clg400-1\" pynq_part_map[\"Pynq-Z2\"] = \"xc7z020clg400-1\" pynq_part_map[\"ZCU102\"] =", "retain the above copyright notice, this # list of conditions", "import DataType # mapping from PYNQ board names to FPGA", "OUT OF THE USE # OF THIS SOFTWARE, EVEN IF", "quantization annotations should be sanitized. Enabled by default, disabling will", "value in np.nditer(current_values): if not dtype.allowed(value): has_to_be_rounded = True break", "= pad_amt - pad_before pad_amt = list(zip(pad_before, pad_after)) else: #", "factor == 0: return x else: return x + (factor", "\"/compile.sh\" with open(self.compile_script, \"w\") as f: f.write(\"#!/bin/bash \\n\") f.write(bash_compile +", "values for a dot product x * A, given matrix", "# use -1 to indicate no padding needed if factor", "g++ compiler command according to entries in include_paths and cpp_files", "in given folder and executes it.\"\"\" # raise error if", "random tensor in given shape and with given FINN DataType.\"\"\"", "import tempfile import warnings from finn.core.datatype import DataType # mapping", "= perceptive_field_elems * max( min_weight * max_input, min_weight * min_input,", "disclaimer in the documentation # and/or other materials provided with", "assert ndarray.ndim == len( pad_to_dims ), \"\"\"The dimensions of the", "Returns the sanitized execution context. If check_values is specified, an", "== x, \"The input x is not an integer.\" assert", "tensor_values = np.random.randint( finn_dt.min(), high=finn_dt.max() + 1, size=tensor_shape ) else:", "max_prod) def sanitize_quant_values(model, node_tensors, execution_context, check_values=False): \"\"\"Sanitize given list of", "in pad_to_dims. -1 means do not pad that particular dimension.", "[] self.executable_path = \"\" self.code_gen_dir = \"\" self.compile_components = []", "disclaimer. # # * Redistributions in binary form must reproduce", "False, all padding will be inserted after the existing values;", "evenly divide the outermost dimension assert ( shp[0] % n_partitions", "# partitions evenly divide the outermost dimension assert ( shp[0]", "a temporary folder with given prefix to be used as", "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF", "set FINN datatype ({}) for input {}\"\"\".format( dtype, tensor )", "DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS", "np.ndarray or ndarray.dtype != np.float32: # try to convert to", "tensor could be generated\".format(finn_dt) ) # always use float type", "+ \"/\" return tempfile.mkdtemp(prefix=inst_prefix + prefix) except KeyError: raise Exception(", "FINN_ROOT must be set correctly. Please ensure you have launched", "self.executable_path = path def build(self, code_gen_dir): \"\"\"Builds the g++ compiler", "\"\"\"Adds given c++ file to cpp_files list.\"\"\" self.cpp_files.append(cpp_file) def set_executable_path(self,", "open(self.compile_script, \"w\") as f: f.write(\"#!/bin/bash \\n\") f.write(bash_compile + \"\\n\") bash_command", "CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)", "def pad_tensor_to_multiple_of(ndarray, pad_to_dims, val=0, distr_pad=False): \"\"\"Pad each dimension of given", "include_paths list.\"\"\" self.include_paths.append(library_path) def append_sources(self, cpp_file): \"\"\"Adds given c++ file", "1 shows top-level input/output streams - level 2 shows per-layer", "given list of tensors in execution_context by rounding values that", "and/or other materials provided with the distribution. # # *", "(min,max) values a dot product between two signed vectors of", "elements can take.\"\"\" assert ( dt_a.signed() and dt_b.signed() ), \"\"\"The", ".name field if it exists, None otherwise. Will throw an", "that the following conditions are met: # # * Redistributions", "of tempfile.mkdtemp to ensure any generated files will survive on", "Redistribution and use in source and binary forms, with or", "code must retain the above copyright notice, this # list", "can now be represented with set finn datatype # TODO:", "environment variable. If the env.var. is undefined, the default value", "factor, \"The input factor is not an integer.\" # use", "ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numpy as", "this # list of conditions and the following disclaimer. #", "x: (0, x), pad_amt)) ret = np.pad(ndarray, pad_amt, mode=\"constant\", constant_values=val)", "a string of letters and digits.\"\"\" lettersAndDigits = string.ascii_letters +", "a dot product x * A, given matrix A of", "of the c++ code in code_gen_dir which is passed to", "a_val * b_val * len if prod < min_prod: min_prod", "[dt_a.min(), dt_a.max()]: for b_val in [dt_b.min(), dt_b.max()]: prod = a_val", "128 pynq_native_port_width[\"ZCU104\"] = 128 # Alveo device and platform mappings", "1 def make_build_dir(prefix=\"\"): \"\"\"Creates a temporary folder with given prefix", "rights reserved. # # Redistribution and use in source and", "# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY", "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING,", "width (in bits) for PYNQ boards pynq_native_port_width = dict() pynq_native_port_width[\"Pynq-Z1\"]", "dtype.allowed(value): has_to_be_rounded = True break if has_to_be_rounded: updated_values = np.round(current_values)", "to ensure that the values that are supposed to be", "on any rounded tensors. Background: FINN uses floating point tensors", "0 and x > 0, \"Factor and x are <=", "from finn.core.datatype import DataType # mapping from PYNQ board names", "alveo_part_map[\"U200\"] = \"xcu200-fsgd2104-2-e\" alveo_part_map[\"U250\"] = \"xcu250-figd2104-2L-e\" alveo_part_map[\"U280\"] = \"xcu280-fsvh2892-2L-e\" alveo_default_platform", "np.nditer(current_values): if not dtype.allowed(value): has_to_be_rounded = True break if has_to_be_rounded:", "level 1 shows top-level input/output streams - level 2 shows", "binary form must reproduce the above copyright notice, # this", "import os import random import string import subprocess import tempfile", "# calculate minimum and maximum values of accumulator # assume", "np.nditer(updated_values): if not dtype.allowed(value): raise Exception( \"\"\"Values can't be represented", "represented with set finn datatype # TODO: vectorize with numpy", "number of workers for parallel transformations. Controllable via the NUM_DEFAULT_WORKERS", "\"\"\" min_weight = matrix.min() max_weight = matrix.max() perceptive_field_elems = matrix.shape[0]", "integers. \"\"\" for tensor in node_tensors: dtype = model.get_tensor_datatype(tensor) #", "# only tested for matrices assert ( ndim == 2", "# TODO: vectorize with numpy for value in np.nditer(updated_values): if", "(accumulator) values for a dot product x * A, given", "possible result (accumulator) values for a dot product x *", "compiler command to produces the executable of the c++ code", "exists.\"\"\" item = get_by_name(container, name, name_field) if item is not", "min_input = vec_dt.min() max_input = vec_dt.max() # calculate minimum and", "be set correctly. Please ensure you have launched the Docker", "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING", "max_weight = matrix.max() perceptive_field_elems = matrix.shape[0] min_input = vec_dt.min() max_input", "integers. Floating point arithmetic can introduce rounding errors, e.g. (int_num", "list of conditions and the following disclaimer. # # *", "be integers are indeed integers. \"\"\" for tensor in node_tensors:", "the desired shape desired = zip(list(ndarray.shape), list(pad_to_dims)) desired = map(lambda", "self.compile_components = [] self.compile_script = \"\" def append_includes(self, library_path): \"\"\"Adds", "of conditions and the following disclaimer in the documentation #", "products derived from # this software without specific prior written", "has_to_be_rounded = False # TODO: vectorize with numpy for value", "is allowed for rounding in FINN execution.\" try: return float(os.environ[\"ERROR_THRESH\"])", "values assert factor > 0 and x > 0, \"Factor", "it.\"\"\" # raise error if includes are empty self.code_gen_dir =", "tempfile.mkdtemp(prefix=inst_prefix + prefix) except KeyError: raise Exception( \"\"\"Environment variable FINN_INST_NAME", "= zip(list(ndarray.shape), list(pad_to_dims)) desired = map(lambda x: roundup_to_integer_multiple(x[0], x[1]), desired)", "\"\"\"Builds the g++ compiler command to produces the executable of", "EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import", "file to cpp_files list.\"\"\" self.cpp_files.append(cpp_file) def set_executable_path(self, path): \"\"\"Sets member", "values, with one extra value inserted after if the padding", "assertion if the amount of rounding is too large. Returns", "distribution. # # * Neither the name of Xilinx nor", "in range(stringLength)) def interleave_matrix_outer_dim_from_partitions(matrix, n_partitions): \"\"\"Interleave the outermost dimension of", "<= 0.\" if x < factor: return factor else: if", "= max(np.abs(current_values - updated_values).flatten()) if max_error <= get_execution_error_thresh(): if check_values", "the function build() of this class.\"\"\" def __init__(self): self.include_paths =", "Inc. # All rights reserved. # # Redistribution and use", "rounding is too large. Returns the sanitized execution context. If", "A, given matrix A of dims (MW, MH), and vector", "n_partitions): \"\"\"Interleave the outermost dimension of a matrix from given", "type(tensor_shape) == list: tensor_shape = tuple(tensor_shape) if finn_dt == DataType.BIPOLAR:", "= np.random.randint( finn_dt.min(), high=finn_dt.max() + 1, size=tensor_shape ) else: raise", "return os.environ[\"FINN_ROOT\"] except KeyError: raise Exception( \"\"\"Environment variable FINN_ROOT must", "values are not both signed vectors.\"\"\" min_prod = 2 **", "self.compile_script = \"\" def append_includes(self, library_path): \"\"\"Adds given library path", "divisible by two.\"\"\" if type(ndarray) != np.ndarray or ndarray.dtype !=", "b_val in [dt_b.min(), dt_b.max()]: prod = a_val * b_val *", "The following depth values are of interest for whole-network stitched", "dtype=np.float32) assert ndarray.ndim == len( pad_to_dims ), \"\"\"The dimensions of", "roundup_to_integer_multiple(x, factor): \"\"\"Round up integer x to the nearest integer", "for matrices assert ( ndim == 2 ), \"\"\"The dimension", "# all padding is added after the existing values pad_amt", "self.cpp_files: self.compile_components.append(cpp_file) for lib in self.include_paths: self.compile_components.append(lib) bash_compile = \"\"", "min_input, max_weight * max_input, max_weight * min_input, ) acc_max =", "input/output streams - level 3 shows per full-layer I/O including", "\"\"\"Adds given library path to include_paths list.\"\"\" self.include_paths.append(library_path) def append_sources(self,", "def get_sanitize_quant_tensors(): \"\"\"Return whether tensors with quantization annotations should be", "the number of workers for parallel transformations. Controllable via the", "item is not None: container.remove(item) def random_string(stringLength=6): \"\"\"Randomly generate a", "in code_gen_dir which is passed to the function build() of", "FINN is cloned into.\" try: return os.environ[\"FINN_ROOT\"] except KeyError: raise", "self.cpp_files.append(cpp_file) def set_executable_path(self, path): \"\"\"Sets member variable \"executable_path\" to given", "IN ANY WAY OUT OF THE USE # OF THIS", "disabling will yield faster ONNX execution but may give incorrect", "c++ file to cpp_files list.\"\"\" self.cpp_files.append(cpp_file) def set_executable_path(self, path): \"\"\"Sets", "\"\"\" try: return int(os.environ[\"NUM_DEFAULT_WORKERS\"]) except KeyError: return 1 def get_finn_root():", "(c) 2020 Xilinx, Inc. # All rights reserved. # #", "use -1 to indicate no padding needed if factor ==", "board names to FPGA part names pynq_part_map = dict() pynq_part_map[\"Ultra96\"]", "and use in source and binary forms, with or without", "throw an Exception if multiple items are found, since this", "the input array don't match the length of the pad_to_dims", "can introduce rounding errors, e.g. (int_num * float_scale) / float_scale", "tensor_shape): \"\"\"Generates random tensor in given shape and with given", "transformations. Controllable via the NUM_DEFAULT_WORKERS environment variable. If the env.var.", "component in self.compile_components: bash_compile += str(component) + \" \" self.compile_script", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE", "SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR", "Use this function instead of tempfile.mkdtemp to ensure any generated", "\"Return the root directory that FINN is cloned into.\" try:", "context. If check_values is specified, an extra DataType.allowed() check will", "len(inds) == 0: return None else: ind = inds[0] return", "is too large. Returns the sanitized execution context. If check_values", "after the existing values, with one extra value inserted after", "the existing values pad_amt = list(map(lambda x: (0, x), pad_amt))", "mode=\"constant\", constant_values=val) assert ( np.asarray(ret.shape, dtype=np.int32) == desired ).all(), \"\"\"The", "function to ensure that the values that are supposed to", "transpose matrix_r = matrix.reshape(-1, n_partitions, shp[1]).transpose((1, 0, 2)) matrix_r =", "# always use float type as container return tensor_values.astype(np.float32) def", "conditions and the following disclaimer in the documentation # and/or", "of partitions.\"\"\" # only tested for matrices assert ( ndim", "or finn_dt == DataType.TERNARY: tensor_values = np.random.randint( finn_dt.min(), high=finn_dt.max() +", "the env.var. is undefined, the default value of 1 is", "( ndim == 2 ), \"\"\"The dimension of the matrix", "reproduce the above copyright notice, # this list of conditions", "Use with caution.\"\"\" try: return int(os.environ[\"SANITIZE_QUANT_TENSORS\"]) except KeyError: # enabled", "dimension of a matrix from given partitions (n_partitions).\"\"\" if type(matrix)", "= matrix.shape[0] min_input = vec_dt.min() max_input = vec_dt.max() # calculate", "given FINN DataType.\"\"\" if type(tensor_shape) == list: tensor_shape = tuple(tensor_shape)", "FPGA part names pynq_part_map = dict() pynq_part_map[\"Ultra96\"] = \"xczu3eg-sbva484-1-e\" pynq_part_map[\"Pynq-Z1\"]", "= \"xczu7ev-ffvc1156-2-e\" # native AXI HP port width (in bits)", "to FPGA part names pynq_part_map = dict() pynq_part_map[\"Ultra96\"] = \"xczu3eg-sbva484-1-e\"", "quantization annotation). Will raise an assertion if the amount of", "be used to endorse or promote products derived from #", "forms, with or without # modification, are permitted provided that", "DAMAGE. import numpy as np import os import random import", "\"FINN datatype.\".format(tensor, dtype) ) # check if rounded values are", "dt_a.signed() and dt_b.signed() ), \"\"\"The input values are not both", "since this violates the ONNX standard.\"\"\" names = [getattr(x, name_field)", "DataType.BINARY: tensor_values = np.random.randint(2, size=tensor_shape) elif \"INT\" in finn_dt.name or", "in np.nditer(current_values): if not dtype.allowed(value): has_to_be_rounded = True break if", "* min( min_weight * max_input, min_weight * min_input, max_weight *", "# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR", "introduce rounding errors, e.g. (int_num * float_scale) / float_scale is", "x are <= 0.\" if x < factor: return factor", "\"\"\"Sets member variable \"executable_path\" to given path.\"\"\" self.executable_path = path", "LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN", "faster ONNX execution but may give incorrect results. Use with", "# add padding to get to the desired shape if", "current_values = execution_context[tensor] updated_values = current_values has_to_be_rounded = False #", "str(component) + \" \" self.compile_script = str(self.code_gen_dir) + \"/compile.sh\" with", "given matrix A of dims (MW, MH), and vector (1,", "the documentation # and/or other materials provided with the distribution.", "os.environ[\"FINN_ROOT\"] except KeyError: raise Exception( \"\"\"Environment variable FINN_ROOT must be", "max_weight * min_input, ) return (acc_min, acc_max) def gen_finn_dt_tensor(finn_dt, tensor_shape):", "be generated\".format(finn_dt) ) # always use float type as container", "= \"xczu9eg-ffvb1156-2-e\" pynq_part_map[\"ZCU104\"] = \"xczu7ev-ffvc1156-2-e\" # native AXI HP port", "if it exists.\"\"\" item = get_by_name(container, name, name_field) if item", "have launched the Docker contaier correctly. \"\"\" ) def get_execution_error_thresh():", "are permitted provided that the following conditions are met: #", "- level 2 shows per-layer input/output streams - level 3", "to get to the desired shape if distr_pad: pad_before =", "in node_tensors: dtype = model.get_tensor_datatype(tensor) # floats don't need sanitization,", "== desired ).all(), \"\"\"The calculated output array doesn't match the", "30 max_prod = -(2 ** 30) for a_val in [dt_a.min(),", "execution_context[tensor] = updated_values else: raise Exception( \"\"\"Rounding error is too", "* max( min_weight * max_input, min_weight * min_input, max_weight *", "float) ndarray = np.asarray(ndarray, dtype=np.float32) assert ndarray.ndim == len( pad_to_dims", "is set to -1. Both x and factor must otherwise", "= matrix.shape ndim = matrix.ndim # ensure # partitions evenly", "e.g. (int_num * float_scale) / float_scale is not always equal", "OF SUCH DAMAGE. import numpy as np import os import", "raise Exception( \"\"\"Environment variable FINN_INST_NAME must be set correctly. Please", "max_weight * min_input, ) acc_max = perceptive_field_elems * max( min_weight", "to convert to a float numpy array (container dtype is", "( shp[0] % n_partitions == 0 ), \"\"\"The outermost dimension", "# Redistribution and use in source and binary forms, with", "vectorize with numpy for value in np.nditer(current_values): if not dtype.allowed(value):", "assert ( np.asarray(ret.shape, dtype=np.int32) == desired ).all(), \"\"\"The calculated output", "the above copyright notice, # this list of conditions and", "the following conditions are met: # # * Redistributions of", "per full-layer I/O including FIFO count signals \"\"\" try: return", "ret = np.pad(ndarray, pad_amt, mode=\"constant\", constant_values=val) assert ( np.asarray(ret.shape, dtype=np.int32)", "* tensor_values - 1 elif finn_dt == DataType.BINARY: tensor_values =", "match the desired/expected one.\"\"\" return ret def calculate_matvec_accumulator_range(matrix, vec_dt): \"\"\"Calculate", "accumulator # assume inputs span the whole range of the", "the existing values; otherwise it will be split evenly between", "path.\"\"\" self.executable_path = path def build(self, code_gen_dir): \"\"\"Builds the g++", "with numpy for value in np.nditer(current_values): if not dtype.allowed(value): has_to_be_rounded", "the ONNX standard.\"\"\" names = [getattr(x, name_field) for x in", "\"\"\"Round up integer x to the nearest integer multiple of", "maximum possible result (accumulator) values for a dot product x", "== name] if len(inds) > 1: raise Exception(\"Found multiple get_by_name", "the remote Vivado synthesis server as set by the, REMOTE_VIVADO", "matches, undefined behavior\") elif len(inds) == 0: return None else:", "is specified, an extra DataType.allowed() check will be performed on", "introduces less quicker runtime if dtype == DataType.FLOAT32: continue current_values", "and after the existing values, with one extra value inserted", "the following disclaimer. # # * Redistributions in binary form", "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS", "path def build(self, code_gen_dir): \"\"\"Builds the g++ compiler command according", "the, REMOTE_VIVADO environment variable, otherwise return None\"\"\" try: return os.environ[\"REMOTE_VIVADO\"]", "and dt_b.signed() ), \"\"\"The input values are not both signed", "\"xilinx_u250_xdma_201830_2\" alveo_default_platform[\"U280\"] = \"xilinx_u280_xdma_201920_3\" def get_rtlsim_trace_depth(): \"\"\"Return the trace depth", "prefix) except KeyError: raise Exception( \"\"\"Environment variable FINN_INST_NAME must be", "= current_values has_to_be_rounded = False # TODO: vectorize with numpy", "\"\"\"Sanitize given list of tensors in execution_context by rounding values", "skip to next # introduces less quicker runtime if dtype", "def get_finn_root(): \"Return the root directory that FINN is cloned", "the \" \"FINN datatype.\".format(tensor, dtype) ) # check if rounded", "less quicker runtime if dtype == DataType.FLOAT32: continue current_values =", "between two signed vectors of types dt_a and dt_b of", "from given partitions (n_partitions).\"\"\" if type(matrix) != np.ndarray or matrix.dtype", "+= str(component) + \" \" self.compile_script = str(self.code_gen_dir) + \"/compile.sh\"", "# # * Redistributions in binary form must reproduce the", "current # add padding to get to the desired shape", "incorrect results. Use with caution.\"\"\" try: return int(os.environ[\"SANITIZE_QUANT_TENSORS\"]) except KeyError:", "exists, None otherwise. Will throw an Exception if multiple items", "False # TODO: vectorize with numpy for value in np.nditer(current_values):", "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED", "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE", "continue current_values = execution_context[tensor] updated_values = current_values has_to_be_rounded = False", "OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE", "+ string.digits return \"\".join(random.choice(lettersAndDigits) for i in range(stringLength)) def interleave_matrix_outer_dim_from_partitions(matrix,", "no padding needed if factor == -1: return x #", "def make_build_dir(prefix=\"\"): \"\"\"Creates a temporary folder with given prefix to", "(n_partitions).\"\"\" if type(matrix) != np.ndarray or matrix.dtype != np.float32: #", "and x are <= 0.\" if x < factor: return", "distr_pad: pad_before = (pad_amt // 2).astype(np.int32) pad_after = pad_amt -", "the names of its # contributors may be used to", "for matrices.\"\"\" # interleave rows between PEs using reshape +", "inst_prefix = os.environ[\"FINN_INST_NAME\"] + \"/\" return tempfile.mkdtemp(prefix=inst_prefix + prefix) except", "digits.\"\"\" lettersAndDigits = string.ascii_letters + string.digits return \"\".join(random.choice(lettersAndDigits) for i", "the above copyright notice, this # list of conditions and", "and the following disclaimer in the documentation # and/or other", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "by two.\"\"\" if type(ndarray) != np.ndarray or ndarray.dtype != np.float32:", "= [] self.executable_path = \"\" self.code_gen_dir = \"\" self.compile_components =", "If check_values is specified, an extra DataType.allowed() check will be", "Please ensure you have launched the Docker contaier correctly. \"\"\"", "is not always equal to int_num. We use this function", "trace depth for rtlsim via PyVerilator. Controllable via the RTLSIM_TRACE_DEPTH", "integers assert int(x) == x, \"The input x is not", "check_values=False): \"\"\"Sanitize given list of tensors in execution_context by rounding", "the values that are supposed to be integers are indeed", "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS", "return int(os.environ[\"NUM_DEFAULT_WORKERS\"]) except KeyError: return 1 def get_finn_root(): \"Return the", "quicker runtime if dtype == DataType.FLOAT32: continue current_values = execution_context[tensor]", "item from container by .name field if it exists, None", "files. The following depth values are of interest for whole-network", "a dot product between two signed vectors of types dt_a", "numpy array (container dtype is float) matrix = np.asarray(matrix, dtype=np.float32)", "\"xczu7ev-ffvc1156-2-e\" # native AXI HP port width (in bits) for", "matrix.min() max_weight = matrix.max() perceptive_field_elems = matrix.shape[0] min_input = vec_dt.min()", "Saves it in bash script in given folder and executes", "field if it exists.\"\"\" item = get_by_name(container, name, name_field) if", "maximum values of accumulator # assume inputs span the whole", "\"The values of tensor {} can't be represented \" \"with", "multiple items are found, since this violates the ONNX standard.\"\"\"", "only show top-level signals and yield smaller .vcd files. The", "\"/\" return tempfile.mkdtemp(prefix=inst_prefix + prefix) except KeyError: raise Exception( \"\"\"Environment", "== 0 ), \"\"\"The outermost dimension is not divisable by", "= np.asarray(matrix, dtype=np.float32) shp = matrix.shape ndim = matrix.ndim #", "any rounded tensors. Background: FINN uses floating point tensors as", "type(matrix) != np.ndarray or matrix.dtype != np.float32: # try to", "modification, are permitted provided that the following conditions are met:", "to -1. Both x and factor must otherwise be positive.\"\"\"", "be performed on any rounded tensors. Background: FINN uses floating", "for rounding in FINN execution.\" try: return float(os.environ[\"ERROR_THRESH\"]) except KeyError:", "to entries in include_paths and cpp_files lists. Saves it in", "matrices.\"\"\" # interleave rows between PEs using reshape + transpose", "the c++ code in code_gen_dir which is passed to the", "node_tensors, execution_context, check_values=False): \"\"\"Sanitize given list of tensors in execution_context", "the Docker contaier correctly. \"\"\" ) def get_by_name(container, name, name_field=\"name\"):", "up integer x to the nearest integer multiple of integer", "a matrix from given partitions (n_partitions).\"\"\" if type(matrix) != np.ndarray", "performed on any rounded tensors. Background: FINN uses floating point", "updated_values = np.round(current_values) warnings.warn( \"The values of tensor {} can't", "cpp_file): \"\"\"Adds given c++ file to cpp_files list.\"\"\" self.cpp_files.append(cpp_file) def", "None def get_num_default_workers(): \"\"\"Return the number of workers for parallel", "reserved. # # Redistribution and use in source and binary", "is undefined, the default value of 1 is returned. \"\"\"", "(factor - (x % factor)) def pad_tensor_to_multiple_of(ndarray, pad_to_dims, val=0, distr_pad=False):", "\" \" self.compile_script = str(self.code_gen_dir) + \"/compile.sh\" with open(self.compile_script, \"w\")", "set correctly. Please ensure you have launched the Docker contaier", "shp[1]).transpose((1, 0, 2)) matrix_r = matrix_r.reshape(n_partitions, -1, shp[1]) return matrix_r", "raise an assertion if the amount of rounding is too", "ensure you have launched the Docker contaier correctly. \"\"\" )", "integers are indeed integers. \"\"\" for tensor in node_tensors: dtype", "numpy array (container dtype is float) ndarray = np.asarray(ndarray, dtype=np.float32)", "pad_amt)) ret = np.pad(ndarray, pad_amt, mode=\"constant\", constant_values=val) assert ( np.asarray(ret.shape,", "to cpp_files list.\"\"\" self.cpp_files.append(cpp_file) def set_executable_path(self, path): \"\"\"Sets member variable", "smaller .vcd files. The following depth values are of interest", "is a multiple of the respective value in pad_to_dims. -1", "dims (MW, MH), and vector (1, MW) with datatype vec_dt.", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #", "= np.random.randint(2, size=tensor_shape) elif \"INT\" in finn_dt.name or finn_dt ==", "str(self.executable_path)) for cpp_file in self.cpp_files: self.compile_components.append(cpp_file) for lib in self.include_paths:", "datatype acc_min = perceptive_field_elems * min( min_weight * max_input, min_weight", "dimension is a multiple of the respective value in pad_to_dims.", "vec_dt.max() # calculate minimum and maximum values of accumulator #", "integer.\" assert int(factor) == factor, \"The input factor is not", "dict() alveo_default_platform[\"U50\"] = \"xilinx_u50_gen3x16_xdma_201920_3\" alveo_default_platform[\"U200\"] = \"xilinx_u200_xdma_201830_2\" alveo_default_platform[\"U250\"] = \"xilinx_u250_xdma_201830_2\"", "vectorize with numpy for value in np.nditer(updated_values): if not dtype.allowed(value):", "pynq_part_map[\"Ultra96\"] = \"xczu3eg-sbva484-1-e\" pynq_part_map[\"Pynq-Z1\"] = \"xc7z020clg400-1\" pynq_part_map[\"Pynq-Z2\"] = \"xc7z020clg400-1\" pynq_part_map[\"ZCU102\"]", "= \"xcu250-figd2104-2L-e\" alveo_part_map[\"U280\"] = \"xcu280-fsvh2892-2L-e\" alveo_default_platform = dict() alveo_default_platform[\"U50\"] =", "vec_dt.min() max_input = vec_dt.max() # calculate minimum and maximum values", "positive values assert factor > 0 and x > 0,", "max_prod = prod return (min_prod, max_prod) def sanitize_quant_values(model, node_tensors, execution_context,", "TODO: vectorize with numpy for value in np.nditer(current_values): if not", "0: return x else: return x + (factor - (x", "<reponame>quetric/finn-base-1 # Copyright (c) 2020 Xilinx, Inc. # All rights", "values that are supposed to be integers are indeed integers.", "includes are empty self.code_gen_dir = code_gen_dir self.compile_components.append(\"g++ -o \" +", "not an integer.\" assert int(factor) == factor, \"The input factor", "\"xczu9eg-ffvb1156-2-e\" pynq_part_map[\"ZCU104\"] = \"xczu7ev-ffvc1156-2-e\" # native AXI HP port width", "OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #", "container[ind] def remove_by_name(container, name, name_field=\"name\"): \"\"\"Remove item from container by", "- level 1 shows top-level input/output streams - level 2", "contaier correctly. \"\"\" ) def get_by_name(container, name, name_field=\"name\"): \"\"\"Return item", "self.include_paths: self.compile_components.append(lib) bash_compile = \"\" for component in self.compile_components: bash_compile", "this class.\"\"\" def __init__(self): self.include_paths = [] self.cpp_files = []", "A of dims (MW, MH), and vector (1, MW) with", "to a float numpy array (container dtype is float) matrix", "size=tensor_shape) elif \"INT\" in finn_dt.name or finn_dt == DataType.TERNARY: tensor_values", "COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS", "max_error <= get_execution_error_thresh(): if check_values is True: # check again", "float_scale) / float_scale is not always equal to int_num. We", "set_executable_path(self, path): \"\"\"Sets member variable \"executable_path\" to given path.\"\"\" self.executable_path", "after the existing values; otherwise it will be split evenly", "Will raise an assertion if the amount of rounding is", "alveo_default_platform[\"U50\"] = \"xilinx_u50_gen3x16_xdma_201920_3\" alveo_default_platform[\"U200\"] = \"xilinx_u200_xdma_201830_2\" alveo_default_platform[\"U250\"] = \"xilinx_u250_xdma_201830_2\" alveo_default_platform[\"U280\"]", "max_error = max(np.abs(current_values - updated_values).flatten()) if max_error <= get_execution_error_thresh(): if", "def get_rtlsim_trace_depth(): \"\"\"Return the trace depth for rtlsim via PyVerilator.", "distr_pad=False): \"\"\"Pad each dimension of given NumPy ndarray using val,", "= model.get_tensor_datatype(tensor) # floats don't need sanitization, skip to next", "get_execution_error_thresh(): if check_values is True: # check again if values", "= [] self.compile_script = \"\" def append_includes(self, library_path): \"\"\"Adds given", "is passed to the function build() of this class.\"\"\" def", "return 1 def make_build_dir(prefix=\"\"): \"\"\"Creates a temporary folder with given", "multiple get_by_name matches, undefined behavior\") elif len(inds) == 0: return", "values of accumulator # assume inputs span the whole range", "in include_paths and cpp_files lists. Saves it in bash script", "conditions are met: # # * Redistributions of source code", "PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT", "THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY", "each dimension is a multiple of the respective value in", "= np.random.randint(2, size=tensor_shape) tensor_values = 2 * tensor_values - 1", "tensor_values = np.random.randint(2, size=tensor_shape) elif \"INT\" in finn_dt.name or finn_dt", "({}), they will be rounded to match the \" \"FINN", "( np.asarray(ret.shape, dtype=np.int32) == desired ).all(), \"\"\"The calculated output array", "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED", "high=finn_dt.max() + 1, size=tensor_shape ) else: raise ValueError( \"Datatype {}", "after if the padding amount is not divisible by two.\"\"\"", "OF THE POSSIBILITY OF SUCH DAMAGE. import numpy as np", "in execution_context by rounding values that are supposed to be", "(container dtype is float) matrix = np.asarray(matrix, dtype=np.float32) shp =", "def random_string(stringLength=6): \"\"\"Randomly generate a string of letters and digits.\"\"\"", "survive on the host after the FINN Docker container exits.\"\"\"", "int(x) == x, \"The input x is not an integer.\"", "+ \"/compile.sh\" with open(self.compile_script, \"w\") as f: f.write(\"#!/bin/bash \\n\") f.write(bash_compile", "default value of 1 is returned. \"\"\" try: return int(os.environ[\"NUM_DEFAULT_WORKERS\"])", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY", "pad_tensor_to_multiple_of(ndarray, pad_to_dims, val=0, distr_pad=False): \"\"\"Pad each dimension of given NumPy", "integer factor. Returns x if factor is set to -1.", "Neither the name of Xilinx nor the names of its", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,", "signed vectors of types dt_a and dt_b of len elements", "evenly between before and after the existing values, with one", "to be integers (as indicated by their quantization annotation). Will", "multiple of the respective value in pad_to_dims. -1 means do", "convert to a float numpy array (container dtype is float)", "perceptive_field_elems * max( min_weight * max_input, min_weight * min_input, max_weight", "distr_pad is False, all padding will be inserted after the", "item = get_by_name(container, name, name_field) if item is not None:", "given NumPy ndarray using val, so that each dimension is", "import subprocess import tempfile import warnings from finn.core.datatype import DataType", "to indicate no padding needed if factor == -1: return", "this function only works for matrices.\"\"\" # interleave rows between", "\"xilinx_u200_xdma_201830_2\" alveo_default_platform[\"U250\"] = \"xilinx_u250_xdma_201830_2\" alveo_default_platform[\"U280\"] = \"xilinx_u280_xdma_201920_3\" def get_rtlsim_trace_depth(): \"\"\"Return", "an integer.\" # use -1 to indicate no padding needed", "data type to represent integers. Floating point arithmetic can introduce", "padding amount is not divisible by two.\"\"\" if type(ndarray) !=", "for i in range(stringLength)) def interleave_matrix_outer_dim_from_partitions(matrix, n_partitions): \"\"\"Interleave the outermost", "return factor else: if x % factor == 0: return", "is not supported, no tensor could be generated\".format(finn_dt) ) #", "== len( pad_to_dims ), \"\"\"The dimensions of the input array", "inds = [i for i, e in enumerate(names) if e", "per-layer input/output streams - level 3 shows per full-layer I/O", "endorse or promote products derived from # this software without", "copyright notice, this # list of conditions and the following", "max_prod: max_prod = prod return (min_prod, max_prod) def sanitize_quant_values(model, node_tensors,", "DataType.allowed() check will be performed on any rounded tensors. Background:", "\\n\") f.write(bash_compile + \"\\n\") bash_command = [\"bash\", self.compile_script] process_compile =", "set finn datatype ({}) for input {}\"\"\".format( dtype, tensor )", "library path to include_paths list.\"\"\" self.include_paths.append(library_path) def append_sources(self, cpp_file): \"\"\"Adds", "match the \" \"FINN datatype.\".format(tensor, dtype) ) # check if", "with set finn datatype # TODO: vectorize with numpy for", "self.code_gen_dir = \"\" self.compile_components = [] self.compile_script = \"\" def", "product between two signed vectors of types dt_a and dt_b", "if values can now be represented with set finn datatype", "in np.nditer(updated_values): if not dtype.allowed(value): raise Exception( \"\"\"Values can't be", "= 2 * tensor_values - 1 elif finn_dt == DataType.BINARY:", "(container dtype is float) ndarray = np.asarray(ndarray, dtype=np.float32) assert ndarray.ndim", "try: return float(os.environ[\"ERROR_THRESH\"]) except KeyError: return 1e-2 def get_sanitize_quant_tensors(): \"\"\"Return", "({}) for input {}\"\"\".format( dtype, tensor ) ) return execution_context", "command according to entries in include_paths and cpp_files lists. Saves", "factor is set to -1. Both x and factor must", "tensor_shape = tuple(tensor_shape) if finn_dt == DataType.BIPOLAR: tensor_values = np.random.randint(2,", "of the input datatype acc_min = perceptive_field_elems * min( min_weight", "next # introduces less quicker runtime if dtype == DataType.FLOAT32:", "directory that FINN is cloned into.\" try: return os.environ[\"FINN_ROOT\"] except", "return ret def calculate_matvec_accumulator_range(matrix, vec_dt): \"\"\"Calculate the minimum and maximum", "> 0, \"Factor and x are <= 0.\" if x", "= get_by_name(container, name, name_field) if item is not None: container.remove(item)", "\"\"\"Pad each dimension of given NumPy ndarray using val, so", "desired - current # add padding to get to the", "float) matrix = np.asarray(matrix, dtype=np.float32) shp = matrix.shape ndim =", "dtype, tensor ) ) return execution_context class CppBuilder: \"\"\"Builds the", "tensors in execution_context by rounding values that are supposed to", "% n_partitions == 0 ), \"\"\"The outermost dimension is not", "their quantization annotation). Will raise an assertion if the amount", "matrix from given partitions (n_partitions).\"\"\" if type(matrix) != np.ndarray or", "if distr_pad: pad_before = (pad_amt // 2).astype(np.int32) pad_after = pad_amt", "two.\"\"\" if type(ndarray) != np.ndarray or ndarray.dtype != np.float32: #", "3 shows per full-layer I/O including FIFO count signals \"\"\"", "specified, an extra DataType.allowed() check will be performed on any", "def __init__(self): self.include_paths = [] self.cpp_files = [] self.executable_path =", "list.\"\"\" self.cpp_files.append(cpp_file) def set_executable_path(self, path): \"\"\"Sets member variable \"executable_path\" to", "Copyright (c) 2020 Xilinx, Inc. # All rights reserved. #", "b_val * len if prod < min_prod: min_prod = prod", "BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,", "return os.environ[\"REMOTE_VIVADO\"] except KeyError: return None def get_num_default_workers(): \"\"\"Return the", "\"Datatype {} is not supported, no tensor could be generated\".format(finn_dt)", "def get_by_name(container, name, name_field=\"name\"): \"\"\"Return item from container by .name", "for rtlsim via PyVerilator. Controllable via the RTLSIM_TRACE_DEPTH environment variable.", "contaier correctly. \"\"\" ) def get_execution_error_thresh(): \"Return the max error", "pynq_native_port_width = dict() pynq_native_port_width[\"Pynq-Z1\"] = 64 pynq_native_port_width[\"Pynq-Z2\"] = 64 pynq_native_port_width[\"Ultra96\"]", "of tensors in execution_context by rounding values that are supposed", "is not 2. Currently this function only works for matrices.\"\"\"", "and factor must otherwise be positive.\"\"\" # ensure integers assert", "try: inst_prefix = os.environ[\"FINN_INST_NAME\"] + \"/\" return tempfile.mkdtemp(prefix=inst_prefix + prefix)", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE", "x + (factor - (x % factor)) def pad_tensor_to_multiple_of(ndarray, pad_to_dims,", "= dict() pynq_part_map[\"Ultra96\"] = \"xczu3eg-sbva484-1-e\" pynq_part_map[\"Pynq-Z1\"] = \"xc7z020clg400-1\" pynq_part_map[\"Pynq-Z2\"] =", "pad_amt = desired - current # add padding to get", "\"\"\"Creates a temporary folder with given prefix to be used", "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES;", "HP port width (in bits) for PYNQ boards pynq_native_port_width =", "def get_remote_vivado(): \"\"\"Return the address of the remote Vivado synthesis", "will survive on the host after the FINN Docker container", "-(2 ** 30) for a_val in [dt_a.min(), dt_a.max()]: for b_val", "device and platform mappings alveo_part_map = dict() alveo_part_map[\"U50\"] = \"xcu50-fsvh2104-2L-e\"", "after the FINN Docker container exits.\"\"\" try: inst_prefix = os.environ[\"FINN_INST_NAME\"]", "show top-level signals and yield smaller .vcd files. The following", "vec_dt): \"\"\"Calculate the minimum and maximum possible result (accumulator) values", "is returned. A trace depth of 1 will only show", "has_to_be_rounded = True break if has_to_be_rounded: updated_values = np.round(current_values) warnings.warn(", "list(pad_to_dims)) desired = map(lambda x: roundup_to_integer_multiple(x[0], x[1]), desired) desired =", "name, name_field=\"name\"): \"\"\"Return item from container by .name field if", "+ (factor - (x % factor)) def pad_tensor_to_multiple_of(ndarray, pad_to_dims, val=0,", "= prod if prod > max_prod: max_prod = prod return", "factor is not an integer.\" # use -1 to indicate", "= tuple(tensor_shape) if finn_dt == DataType.BIPOLAR: tensor_values = np.random.randint(2, size=tensor_shape)", "(MW, MH), and vector (1, MW) with datatype vec_dt. Returns", "are met: # # * Redistributions of source code must", "container.remove(item) def random_string(stringLength=6): \"\"\"Randomly generate a string of letters and", "x, \"The input x is not an integer.\" assert int(factor)", "returned. \"\"\" try: return int(os.environ[\"NUM_DEFAULT_WORKERS\"]) except KeyError: return 1 def", "return x else: return x + (factor - (x %", "that is allowed for rounding in FINN execution.\" try: return", "- pad_before pad_amt = list(zip(pad_before, pad_after)) else: # all padding", "existing values pad_amt = list(map(lambda x: (0, x), pad_amt)) ret", "np.asarray(matrix, dtype=np.float32) shp = matrix.shape ndim = matrix.ndim # ensure", "self.compile_components.append(\"g++ -o \" + str(self.executable_path)) for cpp_file in self.cpp_files: self.compile_components.append(cpp_file)", "1 will only show top-level signals and yield smaller .vcd", "= \"xc7z020clg400-1\" pynq_part_map[\"ZCU102\"] = \"xczu9eg-ffvb1156-2-e\" pynq_part_map[\"ZCU104\"] = \"xczu7ev-ffvc1156-2-e\" # native", "desired shape desired = zip(list(ndarray.shape), list(pad_to_dims)) desired = map(lambda x:", "min_weight = matrix.min() max_weight = matrix.max() perceptive_field_elems = matrix.shape[0] min_input", ") execution_context[tensor] = updated_values else: raise Exception( \"\"\"Rounding error is", "* len if prod < min_prod: min_prod = prod if", "value.\"\"\" # compute the desired shape desired = zip(list(ndarray.shape), list(pad_to_dims))", "get to the desired shape if distr_pad: pad_before = (pad_amt", "provided with the distribution. # # * Neither the name", "KeyError: return 1e-2 def get_sanitize_quant_tensors(): \"\"\"Return whether tensors with quantization", "\"\"\"The outermost dimension is not divisable by the number of", "\" \"with the set FINN datatype ({}), they will be", "environment variable, otherwise return None\"\"\" try: return os.environ[\"REMOTE_VIVADO\"] except KeyError:", "* min_input, max_weight * max_input, max_weight * min_input, ) acc_max", "folder and executes it.\"\"\" # raise error if includes are", "raise Exception( \"\"\"Rounding error is too high to match set", "are not too far from original values max_error = max(np.abs(current_values", "elif finn_dt == DataType.BINARY: tensor_values = np.random.randint(2, size=tensor_shape) elif \"INT\"", "minimum and maximum values of accumulator # assume inputs span", "is too high to match set FINN datatype ({}) for", "np.float32: # try to convert to a float numpy array", "materials provided with the distribution. # # * Neither the", "alveo_default_platform[\"U280\"] = \"xilinx_u280_xdma_201920_3\" def get_rtlsim_trace_depth(): \"\"\"Return the trace depth for", "= desired - current # add padding to get to", "documentation # and/or other materials provided with the distribution. #", "% factor == 0: return x else: return x +", "OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT", "the padding amount is not divisible by two.\"\"\" if type(ndarray)", "== DataType.FLOAT32: continue current_values = execution_context[tensor] updated_values = current_values has_to_be_rounded", "if rounded values are not too far from original values", "yield faster ONNX execution but may give incorrect results. Use", "Docker contaier correctly. \"\"\" ) def get_by_name(container, name, name_field=\"name\"): \"\"\"Return", "\"\"\"Randomly generate a string of letters and digits.\"\"\" lettersAndDigits =", "two signed vectors of types dt_a and dt_b of len", "[] self.cpp_files = [] self.executable_path = \"\" self.code_gen_dir = \"\"", "\"\" self.compile_components = [] self.compile_script = \"\" def append_includes(self, library_path):", "dt_b, len): \"\"\"Returns the (min,max) values a dot product between", "whether tensors with quantization annotations should be sanitized. Enabled by", "float numpy array (container dtype is float) matrix = np.asarray(matrix,", "match set FINN datatype ({}) for input {}\"\"\".format( dtype, tensor", "tempfile.mkdtemp to ensure any generated files will survive on the", "0, 2)) matrix_r = matrix_r.reshape(n_partitions, -1, shp[1]) return matrix_r def", "Background: FINN uses floating point tensors as a carrier data", "prod return (min_prod, max_prod) def sanitize_quant_values(model, node_tensors, execution_context, check_values=False): \"\"\"Sanitize", "), \"\"\"The input values are not both signed vectors.\"\"\" min_prod", "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "= vec_dt.max() # calculate minimum and maximum values of accumulator", "numpy for value in np.nditer(updated_values): if not dtype.allowed(value): raise Exception(", "variable FINN_ROOT must be set correctly. Please ensure you have", "ensure that the values that are supposed to be integers", "max(np.abs(current_values - updated_values).flatten()) if max_error <= get_execution_error_thresh(): if check_values is", "member variable \"executable_path\" to given path.\"\"\" self.executable_path = path def", "get_by_name matches, undefined behavior\") elif len(inds) == 0: return None", "max error that is allowed for rounding in FINN execution.\"", "-1 means do not pad that particular dimension. If distr_pad", "host after the FINN Docker container exits.\"\"\" try: inst_prefix =", "of workers for parallel transformations. Controllable via the NUM_DEFAULT_WORKERS environment", "-1, shp[1]) return matrix_r def roundup_to_integer_multiple(x, factor): \"\"\"Round up integer", "= np.asarray(ndarray.shape, dtype=np.int32) pad_amt = desired - current # add", "dt_b.max()]: prod = a_val * b_val * len if prod", "this function to ensure that the values that are supposed", ") # always use float type as container return tensor_values.astype(np.float32)", "x else: return x + (factor - (x % factor))", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" #", "not pad that particular dimension. If distr_pad is False, all", "( dt_a.signed() and dt_b.signed() ), \"\"\"The input values are not", "but may give incorrect results. Use with caution.\"\"\" try: return", "Both x and factor must otherwise be positive.\"\"\" # ensure", "input {}\"\"\".format( dtype, tensor ) ) execution_context[tensor] = updated_values else:", "def interleave_matrix_outer_dim_from_partitions(matrix, n_partitions): \"\"\"Interleave the outermost dimension of a matrix", "rounding errors, e.g. (int_num * float_scale) / float_scale is not", "FINN Docker container exits.\"\"\" try: inst_prefix = os.environ[\"FINN_INST_NAME\"] + \"/\"", "desired/expected one.\"\"\" return ret def calculate_matvec_accumulator_range(matrix, vec_dt): \"\"\"Calculate the minimum", "is not an integer.\" assert int(factor) == factor, \"The input", "in source and binary forms, with or without # modification,", "in FINN execution.\" try: return float(os.environ[\"ERROR_THRESH\"]) except KeyError: return 1e-2", "# ensure positive values assert factor > 0 and x", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED", "permitted provided that the following conditions are met: # #", "except KeyError: return None def get_num_default_workers(): \"\"\"Return the number of", "EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE #", "# floats don't need sanitization, skip to next # introduces", "in the documentation # and/or other materials provided with the", "are not both signed vectors.\"\"\" min_prod = 2 ** 30", "assert int(factor) == factor, \"The input factor is not an", "given folder and executes it.\"\"\" # raise error if includes", "try: return int(os.environ[\"NUM_DEFAULT_WORKERS\"]) except KeyError: return 1 def get_finn_root(): \"Return", "point arithmetic can introduce rounding errors, e.g. (int_num * float_scale)", "= list(map(lambda x: (0, x), pad_amt)) ret = np.pad(ndarray, pad_amt,", "self.compile_components.append(lib) bash_compile = \"\" for component in self.compile_components: bash_compile +=", "before and after the existing values, with one extra value", "# interleave rows between PEs using reshape + transpose matrix_r", "LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR", "if not dtype.allowed(value): has_to_be_rounded = True break if has_to_be_rounded: updated_values", "# raise error if includes are empty self.code_gen_dir = code_gen_dir", "f: f.write(\"#!/bin/bash \\n\") f.write(bash_compile + \"\\n\") bash_command = [\"bash\", self.compile_script]", "minimum and maximum possible result (accumulator) values for a dot", "assert ( shp[0] % n_partitions == 0 ), \"\"\"The outermost", "not dtype.allowed(value): has_to_be_rounded = True break if has_to_be_rounded: updated_values =", "the whole range of the input datatype acc_min = perceptive_field_elems", "WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN", "def calculate_matvec_accumulator_range(matrix, vec_dt): \"\"\"Calculate the minimum and maximum possible result", "rows between PEs using reshape + transpose matrix_r = matrix.reshape(-1,", "returned. A trace depth of 1 will only show top-level", "# * Neither the name of Xilinx nor the names", "# TODO: vectorize with numpy for value in np.nditer(current_values): if", "represented \" \"with the set FINN datatype ({}), they will", "pad_to_dims ), \"\"\"The dimensions of the input array don't match", "matrix_r.reshape(n_partitions, -1, shp[1]) return matrix_r def roundup_to_integer_multiple(x, factor): \"\"\"Round up", "this function instead of tempfile.mkdtemp to ensure any generated files", "generated\".format(finn_dt) ) # always use float type as container return", "if item is not None: container.remove(item) def random_string(stringLength=6): \"\"\"Randomly generate", "by their quantization annotation). Will raise an assertion if the", "span the whole range of the input datatype acc_min =", "pynq_native_port_width[\"Pynq-Z2\"] = 64 pynq_native_port_width[\"Ultra96\"] = 128 pynq_native_port_width[\"ZCU102\"] = 128 pynq_native_port_width[\"ZCU104\"]", "the Docker contaier correctly. \"\"\" ) def get_execution_error_thresh(): \"Return the", "datatype ({}), they will be rounded to match the \"", "OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED", "x), pad_amt)) ret = np.pad(ndarray, pad_amt, mode=\"constant\", constant_values=val) assert (", "np import os import random import string import subprocess import", "CppBuilder: \"\"\"Builds the g++ compiler command to produces the executable", "function only works for matrices.\"\"\" # interleave rows between PEs", "dot product x * A, given matrix A of dims", "with or without # modification, are permitted provided that the", "for PYNQ boards pynq_native_port_width = dict() pynq_native_port_width[\"Pynq-Z1\"] = 64 pynq_native_port_width[\"Pynq-Z2\"]", "to produces the executable of the c++ code in code_gen_dir", "code in code_gen_dir which is passed to the function build()", "following disclaimer. # # * Redistributions in binary form must", "the g++ compiler command to produces the executable of the", "pynq_part_map[\"ZCU104\"] = \"xczu7ev-ffvc1156-2-e\" # native AXI HP port width (in", "ndim == 2 ), \"\"\"The dimension of the matrix is", "= np.asarray(ndarray, dtype=np.float32) assert ndarray.ndim == len( pad_to_dims ), \"\"\"The", "rounding values that are supposed to be integers (as indicated", "= \"\" def append_includes(self, library_path): \"\"\"Adds given library path to", "# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY", "x in container] inds = [i for i, e in", "value in pad_to_dims. -1 means do not pad that particular", "is not divisable by the number of partitions.\"\"\" # only", "+ transpose matrix_r = matrix.reshape(-1, n_partitions, shp[1]).transpose((1, 0, 2)) matrix_r", "if prod > max_prod: max_prod = prod return (min_prod, max_prod)", "# this list of conditions and the following disclaimer in", "values that are supposed to be integers (as indicated by", "met: # # * Redistributions of source code must retain", "by .name field if it exists.\"\"\" item = get_by_name(container, name,", "\"\\n\") bash_command = [\"bash\", self.compile_script] process_compile = subprocess.Popen(bash_command, stdout=subprocess.PIPE) process_compile.communicate()", "standard.\"\"\" names = [getattr(x, name_field) for x in container] inds", "of conditions and the following disclaimer. # # * Redistributions", "results. Use with caution.\"\"\" try: return int(os.environ[\"SANITIZE_QUANT_TENSORS\"]) except KeyError: #", "shp[1]) return matrix_r def roundup_to_integer_multiple(x, factor): \"\"\"Round up integer x", "using val, so that each dimension is a multiple of", "rtlsim: - level 1 shows top-level input/output streams - level", "runtime if dtype == DataType.FLOAT32: continue current_values = execution_context[tensor] updated_values", "# assume inputs span the whole range of the input", "name_field) for x in container] inds = [i for i,", "shp[0] % n_partitions == 0 ), \"\"\"The outermost dimension is", "pynq_part_map[\"Pynq-Z1\"] = \"xc7z020clg400-1\" pynq_part_map[\"Pynq-Z2\"] = \"xc7z020clg400-1\" pynq_part_map[\"ZCU102\"] = \"xczu9eg-ffvb1156-2-e\" pynq_part_map[\"ZCU104\"]", "level 2 shows per-layer input/output streams - level 3 shows", "PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE,", "factor: return factor else: if x % factor == 0:", "ONNX standard.\"\"\" names = [getattr(x, name_field) for x in container]", "(acc_min, acc_max) def gen_finn_dt_tensor(finn_dt, tensor_shape): \"\"\"Generates random tensor in given", "range(stringLength)) def interleave_matrix_outer_dim_from_partitions(matrix, n_partitions): \"\"\"Interleave the outermost dimension of a", "= \"xc7z020clg400-1\" pynq_part_map[\"Pynq-Z2\"] = \"xc7z020clg400-1\" pynq_part_map[\"ZCU102\"] = \"xczu9eg-ffvb1156-2-e\" pynq_part_map[\"ZCU104\"] =", "in binary form must reproduce the above copyright notice, #", "ARISING IN ANY WAY OUT OF THE USE # OF", "binary forms, with or without # modification, are permitted provided", "# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN", "signed vectors.\"\"\" min_prod = 2 ** 30 max_prod = -(2", "\"with the set FINN datatype ({}), they will be rounded", "min_weight * min_input, max_weight * max_input, max_weight * min_input, )", "contributors may be used to endorse or promote products derived", "list(zip(pad_before, pad_after)) else: # all padding is added after the", "def set_executable_path(self, path): \"\"\"Sets member variable \"executable_path\" to given path.\"\"\"", "2 shows per-layer input/output streams - level 3 shows per", "if includes are empty self.code_gen_dir = code_gen_dir self.compile_components.append(\"g++ -o \"", "divisable by the number of partitions.\"\"\" # only tested for", "# ensure integers assert int(x) == x, \"The input x", "{}\"\"\".format( dtype, tensor ) ) return execution_context class CppBuilder: \"\"\"Builds", "TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF", "True: # check again if values can now be represented", "\"\"\"Environment variable FINN_INST_NAME must be set correctly. Please ensure you", "dt_a and dt_b of len elements can take.\"\"\" assert (", "= [] self.cpp_files = [] self.executable_path = \"\" self.code_gen_dir =", ") ) execution_context[tensor] = updated_values else: raise Exception( \"\"\"Rounding error", "tensor in node_tensors: dtype = model.get_tensor_datatype(tensor) # floats don't need", "not divisible by two.\"\"\" if type(ndarray) != np.ndarray or ndarray.dtype", "= \"\" self.code_gen_dir = \"\" self.compile_components = [] self.compile_script =", "= \"\" self.compile_components = [] self.compile_script = \"\" def append_includes(self,", "to a float numpy array (container dtype is float) ndarray", "dimension of given NumPy ndarray using val, so that each", "alveo_part_map = dict() alveo_part_map[\"U50\"] = \"xcu50-fsvh2104-2L-e\" alveo_part_map[\"U200\"] = \"xcu200-fsgd2104-2-e\" alveo_part_map[\"U250\"]", "> 1: raise Exception(\"Found multiple get_by_name matches, undefined behavior\") elif", "produces the executable of the c++ code in code_gen_dir which", "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER", "factor else: if x % factor == 0: return x", "# All rights reserved. # # Redistribution and use in", "for x in container] inds = [i for i, e", "dt_a.max()]: for b_val in [dt_b.min(), dt_b.max()]: prod = a_val *", "interest for whole-network stitched IP rtlsim: - level 1 shows", "the max error that is allowed for rounding in FINN", "depth of 1 will only show top-level signals and yield", "np.asarray(ret.shape, dtype=np.int32) == desired ).all(), \"\"\"The calculated output array doesn't", "in given shape and with given FINN DataType.\"\"\" if type(tensor_shape)", "amount of rounding is too large. Returns the sanitized execution", "set FINN datatype ({}), they will be rounded to match", "length of the pad_to_dims value.\"\"\" # compute the desired shape", "ret def calculate_matvec_accumulator_range(matrix, vec_dt): \"\"\"Calculate the minimum and maximum possible", "except KeyError: return 1 def get_finn_root(): \"Return the root directory", "\"\"\"Returns the (min,max) values a dot product between two signed", "Exception(\"Found multiple get_by_name matches, undefined behavior\") elif len(inds) == 0:", "enumerate(names) if e == name] if len(inds) > 1: raise", "list of conditions and the following disclaimer in the documentation", "dimension is not divisable by the number of partitions.\"\"\" #", "= matrix.ndim # ensure # partitions evenly divide the outermost", "self.compile_components.append(cpp_file) for lib in self.include_paths: self.compile_components.append(lib) bash_compile = \"\" for", "dtype, tensor ) ) execution_context[tensor] = updated_values else: raise Exception(", "not too far from original values max_error = max(np.abs(current_values -", "% factor)) def pad_tensor_to_multiple_of(ndarray, pad_to_dims, val=0, distr_pad=False): \"\"\"Pad each dimension", "and executes it.\"\"\" # raise error if includes are empty", "# modification, are permitted provided that the following conditions are", "assert factor > 0 and x > 0, \"Factor and", "do not pad that particular dimension. If distr_pad is False,", "try: return int(os.environ[\"SANITIZE_QUANT_TENSORS\"]) except KeyError: # enabled by default return", "if the padding amount is not divisible by two.\"\"\" if", "following disclaimer in the documentation # and/or other materials provided", "build() of this class.\"\"\" def __init__(self): self.include_paths = [] self.cpp_files", "may be used to endorse or promote products derived from", "= perceptive_field_elems * min( min_weight * max_input, min_weight * min_input,", "it will be split evenly between before and after the", "with given FINN DataType.\"\"\" if type(tensor_shape) == list: tensor_shape =", "\"\"\"The dimensions of the input array don't match the length", "list of tensors in execution_context by rounding values that are", "updated_values).flatten()) if max_error <= get_execution_error_thresh(): if check_values is True: #", "by default return 1 def make_build_dir(prefix=\"\"): \"\"\"Creates a temporary folder", "of given NumPy ndarray using val, so that each dimension", "be rounded to match the \" \"FINN datatype.\".format(tensor, dtype) )", "values pad_amt = list(map(lambda x: (0, x), pad_amt)) ret =", "rounding in FINN execution.\" try: return float(os.environ[\"ERROR_THRESH\"]) except KeyError: return", "< min_prod: min_prod = prod if prod > max_prod: max_prod", "** 30) for a_val in [dt_a.min(), dt_a.max()]: for b_val in", "following conditions are met: # # * Redistributions of source", "launched the Docker contaier correctly. \"\"\" ) def get_by_name(container, name,", "not always equal to int_num. We use this function to", "else: raise Exception( \"\"\"Rounding error is too high to match", "if it exists, None otherwise. Will throw an Exception if", "OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "to represent integers. Floating point arithmetic can introduce rounding errors,", "ndarray.dtype != np.float32: # try to convert to a float", "* max_input, max_weight * min_input, ) acc_max = perceptive_field_elems *", "should be sanitized. Enabled by default, disabling will yield faster", "DataType.BIPOLAR: tensor_values = np.random.randint(2, size=tensor_shape) tensor_values = 2 * tensor_values", "conditions and the following disclaimer. # # * Redistributions in", "Floating point arithmetic can introduce rounding errors, e.g. (int_num *", "\"INT\" in finn_dt.name or finn_dt == DataType.TERNARY: tensor_values = np.random.randint(", "assert int(x) == x, \"The input x is not an", "elif len(inds) == 0: return None else: ind = inds[0]", "= updated_values else: raise Exception( \"\"\"Rounding error is too high", "lib in self.include_paths: self.compile_components.append(lib) bash_compile = \"\" for component in", "{} is not supported, no tensor could be generated\".format(finn_dt) )", "Currently this function only works for matrices.\"\"\" # interleave rows", "check if rounded values are not too far from original", "for value in np.nditer(current_values): if not dtype.allowed(value): has_to_be_rounded = True", "for parallel transformations. Controllable via the NUM_DEFAULT_WORKERS environment variable. If", "vectors of types dt_a and dt_b of len elements can", "\"\"\"The input values are not both signed vectors.\"\"\" min_prod =", "1 elif finn_dt == DataType.BINARY: tensor_values = np.random.randint(2, size=tensor_shape) elif", "finn.core.datatype import DataType # mapping from PYNQ board names to", ") return (acc_min, acc_max) def gen_finn_dt_tensor(finn_dt, tensor_shape): \"\"\"Generates random tensor", "DataType.TERNARY: tensor_values = np.random.randint( finn_dt.min(), high=finn_dt.max() + 1, size=tensor_shape )", "this list of conditions and the following disclaimer in the", "with set finn datatype ({}) for input {}\"\"\".format( dtype, tensor", "execution_context by rounding values that are supposed to be integers", "matrix.ndim # ensure # partitions evenly divide the outermost dimension", "= True break if has_to_be_rounded: updated_values = np.round(current_values) warnings.warn( \"The", "vectors.\"\"\" min_prod = 2 ** 30 max_prod = -(2 **", "server as set by the, REMOTE_VIVADO environment variable, otherwise return", "if type(matrix) != np.ndarray or matrix.dtype != np.float32: # try", "ensure # partitions evenly divide the outermost dimension assert (", "max_input = vec_dt.max() # calculate minimum and maximum values of", "1 is returned. \"\"\" try: return int(os.environ[\"NUM_DEFAULT_WORKERS\"]) except KeyError: return", "cpp_files lists. Saves it in bash script in given folder", "raise ValueError( \"Datatype {} is not supported, no tensor could", "streams - level 2 shows per-layer input/output streams - level", "partitions.\"\"\" # only tested for matrices assert ( ndim ==", "workers for parallel transformations. Controllable via the NUM_DEFAULT_WORKERS environment variable.", "not both signed vectors.\"\"\" min_prod = 2 ** 30 max_prod", "used as a build dir. Use this function instead of", "no tensor could be generated\".format(finn_dt) ) # always use float", "matrix A of dims (MW, MH), and vector (1, MW)", "def calculate_signed_dot_prod_range(dt_a, dt_b, len): \"\"\"Returns the (min,max) values a dot", "the executable of the c++ code in code_gen_dir which is", "can't be represented \" \"with the set FINN datatype ({}),", "default value of 1 is returned. A trace depth of", "get_by_name(container, name, name_field) if item is not None: container.remove(item) def", "for component in self.compile_components: bash_compile += str(component) + \" \"", "2 ** 30 max_prod = -(2 ** 30) for a_val", "max_weight * max_input, max_weight * min_input, ) acc_max = perceptive_field_elems", "\"\"\"Return item from container by .name field if it exists,", "too high to match set FINN datatype ({}) for input", "indicated by their quantization annotation). Will raise an assertion if", "0, \"Factor and x are <= 0.\" if x <", "class.\"\"\" def __init__(self): self.include_paths = [] self.cpp_files = [] self.executable_path", "perceptive_field_elems = matrix.shape[0] min_input = vec_dt.min() max_input = vec_dt.max() #", "tensor_values - 1 elif finn_dt == DataType.BINARY: tensor_values = np.random.randint(2,", "error is too high to match set FINN datatype ({})", "from container by .name field if it exists, None otherwise.", "for input {}\"\"\".format( dtype, tensor ) ) return execution_context class", "container exits.\"\"\" try: inst_prefix = os.environ[\"FINN_INST_NAME\"] + \"/\" return tempfile.mkdtemp(prefix=inst_prefix", "\"\"\"Values can't be represented with set finn datatype ({}) for", "acc_max = perceptive_field_elems * max( min_weight * max_input, min_weight *", "is returned. \"\"\" try: return int(os.environ[\"NUM_DEFAULT_WORKERS\"]) except KeyError: return 1", "# Alveo device and platform mappings alveo_part_map = dict() alveo_part_map[\"U50\"]", "be represented with set finn datatype ({}) for input {}\"\"\".format(", "x > 0, \"Factor and x are <= 0.\" if", "NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND", "that particular dimension. If distr_pad is False, all padding will", "= vec_dt.min() max_input = vec_dt.max() # calculate minimum and maximum", "nearest integer multiple of integer factor. Returns x if factor", "= string.ascii_letters + string.digits return \"\".join(random.choice(lettersAndDigits) for i in range(stringLength))", "a build dir. Use this function instead of tempfile.mkdtemp to", "get_rtlsim_trace_depth(): \"\"\"Return the trace depth for rtlsim via PyVerilator. Controllable", "raise error if includes are empty self.code_gen_dir = code_gen_dir self.compile_components.append(\"g++", "integers (as indicated by their quantization annotation). Will raise an", "or matrix.dtype != np.float32: # try to convert to a", "bits) for PYNQ boards pynq_native_port_width = dict() pynq_native_port_width[\"Pynq-Z1\"] = 64", "max_input, max_weight * min_input, ) acc_max = perceptive_field_elems * max(", "that the values that are supposed to be integers are", "tuple(tensor_shape) if finn_dt == DataType.BIPOLAR: tensor_values = np.random.randint(2, size=tensor_shape) tensor_values", "point tensors as a carrier data type to represent integers.", "vec_dt. Returns (acc_min, acc_max). \"\"\" min_weight = matrix.min() max_weight =", "enabled by default return 1 def make_build_dir(prefix=\"\"): \"\"\"Creates a temporary", "{} can't be represented \" \"with the set FINN datatype", "os import random import string import subprocess import tempfile import", "pad_amt, mode=\"constant\", constant_values=val) assert ( np.asarray(ret.shape, dtype=np.int32) == desired ).all(),", "type to represent integers. Floating point arithmetic can introduce rounding", "in [dt_b.min(), dt_b.max()]: prod = a_val * b_val * len", "KeyError: raise Exception( \"\"\"Environment variable FINN_ROOT must be set correctly.", "trace depth of 1 will only show top-level signals and", "MH), and vector (1, MW) with datatype vec_dt. Returns (acc_min,", "dt_b.signed() ), \"\"\"The input values are not both signed vectors.\"\"\"", "== -1: return x # ensure positive values assert factor", "derived from # this software without specific prior written permission.", "else: # all padding is added after the existing values", "otherwise return None\"\"\" try: return os.environ[\"REMOTE_VIVADO\"] except KeyError: return None", "[] self.compile_script = \"\" def append_includes(self, library_path): \"\"\"Adds given library", "values are of interest for whole-network stitched IP rtlsim: -", "np.asarray(ndarray.shape, dtype=np.int32) pad_amt = desired - current # add padding", "and with given FINN DataType.\"\"\" if type(tensor_shape) == list: tensor_shape", "parallel transformations. Controllable via the NUM_DEFAULT_WORKERS environment variable. If the", "with quantization annotations should be sanitized. Enabled by default, disabling", "ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,", "KeyError: return 1 def get_remote_vivado(): \"\"\"Return the address of the", "get_finn_root(): \"Return the root directory that FINN is cloned into.\"", "far from original values max_error = max(np.abs(current_values - updated_values).flatten()) if", "FIFO count signals \"\"\" try: return int(os.environ[\"RTLSIM_TRACE_DEPTH\"]) except KeyError: return", "OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER #", "= 128 pynq_native_port_width[\"ZCU104\"] = 128 # Alveo device and platform", "128 # Alveo device and platform mappings alveo_part_map = dict()", "correctly. \"\"\" ) def get_by_name(container, name, name_field=\"name\"): \"\"\"Return item from", "-1 to indicate no padding needed if factor == -1:", "BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #", "RTLSIM_TRACE_DEPTH environment variable. If the env.var. is undefined, the default", "value of 1 is returned. A trace depth of 1", "if factor == -1: return x # ensure positive values", "(min_prod, max_prod) def sanitize_quant_values(model, node_tensors, execution_context, check_values=False): \"\"\"Sanitize given list", "DataType.\"\"\" if type(tensor_shape) == list: tensor_shape = tuple(tensor_shape) if finn_dt", "\"\"\"Calculate the minimum and maximum possible result (accumulator) values for", "exits.\"\"\" try: inst_prefix = os.environ[\"FINN_INST_NAME\"] + \"/\" return tempfile.mkdtemp(prefix=inst_prefix +", "\"\"\"Return the number of workers for parallel transformations. Controllable via", "random_string(stringLength=6): \"\"\"Randomly generate a string of letters and digits.\"\"\" lettersAndDigits", "!= np.ndarray or matrix.dtype != np.float32: # try to convert", "def roundup_to_integer_multiple(x, factor): \"\"\"Round up integer x to the nearest", "and platform mappings alveo_part_map = dict() alveo_part_map[\"U50\"] = \"xcu50-fsvh2104-2L-e\" alveo_part_map[\"U200\"]" ]
[ "height=2, bg='steelblue', command=self.read) self.submit.place(x=600, y=300) self.submit = Button(self.left, text=\"Exit\", width=20,", "or self.val4 == '' or self.val5 == '' or self.val6==''", "= Tk() root.title(\"Shalom Clinic\") #root.geometry(\"1200x720+0+0\") root.attributes('-fullscreen', True) root.resizable(0, 0) Top", "= \"INSERT INTO 'appointments' (name, age, gender, location, scheduled_time, phone,date,Allergies,Chronic_Conditions,Blood_Group)", "self.box.insert(END, '\\n Appointment fixed for ' + str(self.val1) + '\\n", "\"INVALID Phone Number\") else: sql = \"INSERT INTO 'appointments' (name,", "self.bg.place(x=0, y=460) self.clicked3=StringVar() self.clicked3.set(\"Select Blood Group\") self.bg_ent = OptionMenu(self.left,self.clicked3,*options3) self.bg_ent.pack()", "from datetime import datetime from datetime import date import tkinter", "self.all_ent.insert(0, 'NONE') self.chronic = Label(self.left, text=\"Chronic Conditions\", font=('arial 18 bold'),", "Group' or self.val5=='Select Date' or self.val6=='Select Time': print(\"ty\",self.val3) tkinter.messagebox.showinfo(\"Warning\", \"Please", "relief=RIDGE) Top.pack(side=TOP, fill=X) Form = Frame(root, height=1) Form.pack(side=TOP, pady=1) lbl_title", "green') self.bg.place(x=0, y=460) self.clicked3=StringVar() self.clicked3.set(\"Select Blood Group\") self.bg_ent = OptionMenu(self.left,self.clicked3,*options3)", "self.val6, self.val7,self.val5,self.val8,self.val9,self.val10)) conn.commit() tkinter.messagebox.showinfo(\"Success\", \"Appointment for \" + str(self.val1) +", "pd import pandas as pd import datetime from dateutil import", "= [] class Application: def __init__(self, master): self.master = master", "as pd import pandas as pd import datetime from dateutil", "pandas as pd import datetime from dateutil import rrule, parser", "self.clicked2.set(\"Select Time\") self.clicked3.set(\"Select Blood Group\") self.chr_ent.delete(0,END) self.all_ent.delete(0,END) self.all_ent.insert(0, 'NONE') self.chr_ent.insert(0,", "self.submit.place(x=600, y=100) self.submit = Button(self.left, text=\"View/Update Patient Details\", width=20, height=2,", "import tkinter as tk from tkinter import ttk from tkinter.messagebox", "tkcalendar import Calendar from datetime import datetime from datetime import", "width=30) self.name_ent.place(x=250, y=100) self.age_ent = Entry(self.left, width=30) self.age_ent.place(x=250, y=140) self.clicked=StringVar()", "Frame(root, height=1) Form.pack(side=TOP, pady=1) lbl_title = Label(Top, text = \"Shalom", "Group\") self.bg_ent = OptionMenu(self.left,self.clicked3,*options3) self.bg_ent.pack() self.bg_ent.place(x=250, y=460) self.name_ent = Entry(self.left,", ") self.box.insert(END, '\\n Appointment fixed for ' + str(self.val1) +", "text=\"Logs\", font=('arial 28 bold'), fg='white', bg='steelblue') self.logs.place(x=0, y=0) self.box =", "= Entry(self.left, width=30) self.all_ent.place(x=250, y=380) self.all_ent.insert(0, 'NONE') self.chronic = Label(self.left,", "text=\"Gender\", font=('arial 18 bold'), fg='black', bg='sea green') self.gender.place(x=0, y=180) self.location", "self.submit = Button(self.left, text=\"Add Appointment\", width=20, height=2, bg='steelblue', command=self.add_appointment) self.submit.place(x=270,", "Label(self.left, text=\"Age\", font=('arial 18 bold'), fg='black', bg='sea green') self.age.place(x=0, y=140)", "self.clicked1.get() self.val6 = self.clicked2.get() self.val7 = self.phone_ent.get() self.val8 = self.all_ent.get()", "self.heading = Label(self.left, text=\"Appointments\", font=('arial 40 bold'), fg='black', bg='sea green')", "height=2, bg='steelblue', command=self.update) self.submit.place(x=600, y=200) self.submit = Button(self.left, text=\"Read Names\",", "self.logs.place(x=0, y=0) self.box = Text(self.right, width=62, height=45) self.box.place(x=20, y=60) def", "str(self.val5)+','+str(self.val6)) self.name_ent.delete(0,END) self.age_ent.delete(0,END) self.location_ent.delete(0,END) self.phone_ent.delete(0,END) self.clicked1.set(\"Select Date\") self.clicked2.set(\"Select Time\") self.clicked3.set(\"Select", "self.gender.place(x=0, y=180) self.location = Label(self.left, text=\"Location\", font=('arial 18 bold'), fg='black',", "Up All Boxes\") print(self.val3) elif not(pattern1.match(self.val1)) or len(self.val1)<2: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Name\")", "bg='steelblue', command=self.add_appointment) self.submit.place(x=270, y=500) self.submit = Button(self.left, text=\"View Appointments\", width=20,", "c = conn.cursor() ids = [] class Application: def __init__(self,", "gender, location, scheduled_time, phone,date,Allergies,Chronic_Conditions,Blood_Group) VALUES(?, ?, ?, ?, ?, ?,?,?,?,?)\"", "VALUES(?, ?, ?, ?, ?, ?,?,?,?,?)\" c.execute(sql, (self.val1, self.val2, self.val3,", "self.clicked.set(\"Male\") self.gender_ent = OptionMenu(self.left,self.clicked,*options) self.gender_ent.pack() self.gender_ent.place(x=250, y=180) self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250, y=220)", "= '05-10-2021' date2 = '12-31-2050' datesx = pd.date_range(today, date2).tolist() conn", "self.val5 == '' or self.val6=='' or self.val7=='' or self.val10=='Select Blood", "for self.row in self.result: self.id = self.row[0] ids.append(self.id) self.new =", "datetime from datetime import date import tkinter as tk from", "self.val9 = self.chr_ent.get() self.val10 = self.clicked3.get() pattern=re.compile(\"[7-9][0-9]{9}\") pattern=re.compile(\"[7-9][0-9]{9}\") pattern2=re.compile(\"[1-9]([0-9])*\") pattern1=re.compile(r'([A-Z])(\\s*[A-Z])*$')", "= Button(self.left, text=\"Read Names\", width=20, height=2, bg='steelblue', command=self.read) self.submit.place(x=600, y=300)", "text=\"Patient's Name\", font=('arial 18 bold'), fg='black', bg='sea green') self.name.place(x=0, y=100)", "pd.date_range(today, date2).tolist() conn = sqlite3.connect('database copy.db') c = conn.cursor() ids", "width=30) self.all_ent.place(x=250, y=380) self.all_ent.insert(0, 'NONE') self.chronic = Label(self.left, text=\"Chronic Conditions\",", "Entry(self.left, width=30) self.all_ent.place(x=250, y=380) self.all_ent.insert(0, 'NONE') self.chronic = Label(self.left, text=\"Chronic", "bg='sea green') self.chronic.place(x=0, y=420) self.chr_ent = Entry(self.left, width=30) self.chr_ent.place(x=250, y=420)", "self.name_ent.place(x=250, y=100) self.age_ent = Entry(self.left, width=30) self.age_ent.place(x=250, y=140) self.clicked=StringVar() self.clicked.set(\"Male\")", "y=460) self.name_ent = Entry(self.left, width=30) self.name_ent.place(x=250, y=100) self.age_ent = Entry(self.left,", "pattern2=re.compile(\"[1-9]([0-9])*\") pattern1=re.compile(r'([A-Z])(\\s*[A-Z])*$') pattern.match(self.val7) if self.val1 == '' or self.val2 ==", "self.time_ent.pack() self.time_ent.place(x=250, y=300) self.phone_ent = Entry(self.left, width=30) self.phone_ent.place(x=250, y=340) self.submit", "?, ?, ?, ?, ?,?,?,?,?)\" c.execute(sql, (self.val1, self.val2, self.val3, self.val4,", "width=20, height=2, bg='steelblue', command=self.view) self.submit.place(x=600, y=100) self.submit = Button(self.left, text=\"View/Update", "= self.location_ent.get() self.val5 = self.clicked1.get() self.val6 = self.clicked2.get() self.val7 =", "== '' or self.val3 == '' or self.val4 == ''", "len(self.val1)<2: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Name\") elif not(pattern2.match(self.val2)) or len(self.val2)>=3: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Age\") elif", "not(pattern.match(self.val7)) or len(self.val7)>10: tkinter.messagebox.showinfo(\"Warning\", \"INVALID Phone Number\") else: sql =", "read(self): import read read.buildread() def quit(self): answer = askyesno(title='Confirm Exit',", "self.all_ent.place(x=250, y=380) self.all_ent.insert(0, 'NONE') self.chronic = Label(self.left, text=\"Chronic Conditions\", font=('arial", "self.heading.place(x=0, y=0) self.name = Label(self.left, text=\"Patient's Name\", font=('arial 18 bold'),", "y=300) self.submit = Button(self.left, text=\"Exit\", width=20, height=2, bg='steelblue', command=self.quit) self.submit.place(x=600,", "bg='sea green') self.gender.place(x=0, y=180) self.location = Label(self.left, text=\"Location\", font=('arial 18", "== '' or self.val6=='' or self.val7=='' or self.val10=='Select Blood Group'", "width=20, height=2, bg='steelblue', command=self.add_appointment) self.submit.place(x=270, y=500) self.submit = Button(self.left, text=\"View", "= Entry(self.left, width=30) self.name_ent.place(x=250, y=100) self.age_ent = Entry(self.left, width=30) self.age_ent.place(x=250,", "date1 = '05-10-2021' date2 = '12-31-2050' datesx = pd.date_range(today, date2).tolist()", "ID FROM appointments\" self.result = c.execute(sql2) for self.row in self.result:", "str(self.val1) + \" has been created\" ) self.box.insert(END, '\\n Appointment", "+ str(self.val1) + \" has been created\" ) self.box.insert(END, '\\n", "Blood Group' or self.val5=='Select Date' or self.val6=='Select Time': print(\"ty\",self.val3) tkinter.messagebox.showinfo(\"Warning\",", "as pd import datetime from dateutil import rrule, parser today", "fg='black', bg='sea green') self.date.place(x=0, y=260) self.time = Label(self.left, text=\"Appointment Time\",", "sorted(ids) self.final_id = self.new[len(ids)-1] self.logs = Label(self.right, text=\"Logs\", font=('arial 28", "you sure you want to exit?') if answer: root.destroy() root", "= Button(self.left, text=\"View/Update Patient Details\", width=20, height=2, bg='steelblue', command=self.update) self.submit.place(x=600,", "width=20, height=2, bg='steelblue', command=self.read) self.submit.place(x=600, y=300) self.submit = Button(self.left, text=\"Exit\",", "self.val5 = self.clicked1.get() self.val6 = self.clicked2.get() self.val7 = self.phone_ent.get() self.val8", "Blood Group\") self.bg_ent = OptionMenu(self.left,self.clicked3,*options3) self.bg_ent.pack() self.bg_ent.place(x=250, y=460) self.name_ent =", "def update(self): import update update.buildupdate() def read(self): import read read.buildread()", "font=('arial 18 bold'), fg='black', bg='sea green') self.location.place(x=0, y=220) self.date =", "or self.val10=='Select Blood Group' or self.val5=='Select Date' or self.val6=='Select Time':", "or self.val7=='' or self.val10=='Select Blood Group' or self.val5=='Select Date' or", "not(pattern1.match(self.val1)) or len(self.val1)<2: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Name\") elif not(pattern2.match(self.val2)) or len(self.val2)>=3: tkinter.messagebox.showinfo(\"Warning\",\"INVALID", "self.clicked1.set(\"Select Date\") self.clicked2.set(\"Select Time\") self.clicked3.set(\"Select Blood Group\") self.chr_ent.delete(0,END) self.all_ent.delete(0,END) self.all_ent.insert(0,", "dateutil import rrule, parser today = date.today() date1 = '05-10-2021'", "conn.commit() tkinter.messagebox.showinfo(\"Success\", \"Appointment for \" + str(self.val1) + \" has", "18 bold'), fg='black', bg='sea green') self.location.place(x=0, y=220) self.date = Label(self.left,", "y=260) self.clicked2=StringVar() self.clicked2.set(\"Select Time\") self.time_ent = OptionMenu(self.left,self.clicked2,*options2) self.time_ent.pack() self.time_ent.place(x=250, y=300)", "command=self.add_appointment) self.submit.place(x=270, y=500) self.submit = Button(self.left, text=\"View Appointments\", width=20, height=2,", "self.submit = Button(self.left, text=\"Exit\", width=20, height=2, bg='steelblue', command=self.quit) self.submit.place(x=600, y=400)", "font=('arial 18 bold'), fg='black', bg='sea green') self.chronic.place(x=0, y=420) self.chr_ent =", "bd=1, relief=RIDGE) Top.pack(side=TOP, fill=X) Form = Frame(root, height=1) Form.pack(side=TOP, pady=1)", "\" + str(self.val1) + \" has been created\" ) self.box.insert(END,", "import update update.buildupdate() def read(self): import read read.buildread() def quit(self):", "import re import sqlite3 import tkinter.messagebox import pandas as pd", "tkinter.messagebox import pandas as pd import pandas as pd import", "bg='steelblue', command=self.quit) self.submit.place(x=600, y=400) sql2 = \"SELECT ID FROM appointments\"", "= self.name_ent.get() self.val2 = self.age_ent.get() self.val3 = self.clicked.get() self.val4 =", "OptionMenu(self.left,self.clicked,*options) self.gender_ent.pack() self.gender_ent.place(x=250, y=180) self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250, y=220) self.clicked1=StringVar() self.clicked1.set(\"Select Date\")", "bg='sea green') self.left.pack(side=LEFT) self.right = Frame(master, width=1000, height=800, bg='steelblue') self.right.pack(side=RIGHT)", "fg='black', bg='sea green') self.age.place(x=0, y=140) self.gender = Label(self.left, text=\"Gender\", font=('arial", "self.val4 == '' or self.val5 == '' or self.val6=='' or", "y=100) self.submit = Button(self.left, text=\"View/Update Patient Details\", width=20, height=2, bg='steelblue',", "self.clicked3.set(\"Select Blood Group\") self.bg_ent = OptionMenu(self.left,self.clicked3,*options3) self.bg_ent.pack() self.bg_ent.place(x=250, y=460) self.name_ent", "Label(self.left, text=\"Blood Group\", font=('arial 18 bold'), fg='black', bg='sea green') self.bg.place(x=0,", "(name, age, gender, location, scheduled_time, phone,date,Allergies,Chronic_Conditions,Blood_Group) VALUES(?, ?, ?, ?,", "self.box.place(x=20, y=60) def add_appointment(self): self.val1 = self.name_ent.get() self.val2 = self.age_ent.get()", "width=30) self.chr_ent.place(x=250, y=420) self.chr_ent.insert(0, 'NONE') self.bg = Label(self.left, text=\"Blood Group\",", "green') self.age.place(x=0, y=140) self.gender = Label(self.left, text=\"Gender\", font=('arial 18 bold'),", "fg='black', bg='sea green') self.phone.place(x=0, y=340) self.allergies = Label(self.left, text=\"Allergies\", font=('arial", "?,?,?,?,?)\" c.execute(sql, (self.val1, self.val2, self.val3, self.val4, self.val6, self.val7,self.val5,self.val8,self.val9,self.val10)) conn.commit() tkinter.messagebox.showinfo(\"Success\",", "y=380) self.all_ent.insert(0, 'NONE') self.chronic = Label(self.left, text=\"Chronic Conditions\", font=('arial 18", "= Label(self.left, text=\"Age\", font=('arial 18 bold'), fg='black', bg='sea green') self.age.place(x=0,", "self.all_ent.insert(0, 'NONE') self.chr_ent.insert(0, 'NONE') def view(self): import view view.call() def", "fill=X) Form = Frame(root, height=1) Form.pack(side=TOP, pady=1) lbl_title = Label(Top,", "self.bg_ent.pack() self.bg_ent.place(x=250, y=460) self.name_ent = Entry(self.left, width=30) self.name_ent.place(x=250, y=100) self.age_ent", "0) Top = Frame(root, bd=1, relief=RIDGE) Top.pack(side=TOP, fill=X) Form =", "font=('arial 18 bold'), fg='black', bg='sea green') self.phone.place(x=0, y=340) self.allergies =", "text=\"Read Names\", width=20, height=2, bg='steelblue', command=self.read) self.submit.place(x=600, y=300) self.submit =", "command=self.read) self.submit.place(x=600, y=300) self.submit = Button(self.left, text=\"Exit\", width=20, height=2, bg='steelblue',", "print(\"ty\",self.val3) tkinter.messagebox.showinfo(\"Warning\", \"Please Fill Up All Boxes\") print(self.val3) elif not(pattern1.match(self.val1))", "width=62, height=45) self.box.place(x=20, y=60) def add_appointment(self): self.val1 = self.name_ent.get() self.val2", "self.submit.place(x=270, y=500) self.submit = Button(self.left, text=\"View Appointments\", width=20, height=2, bg='steelblue',", "self.date = Label(self.left, text=\"Appointment Date\", font=('arial 18 bold'), fg='black', bg='sea", "Label(self.left, text=\"Appointment Time\", font=('arial 18 bold'), fg='black', bg='sea green') self.time.place(x=0,", "bold'), fg='black', bg='sea green') self.gender.place(x=0, y=180) self.location = Label(self.left, text=\"Location\",", "self.age_ent.place(x=250, y=140) self.clicked=StringVar() self.clicked.set(\"Male\") self.gender_ent = OptionMenu(self.left,self.clicked,*options) self.gender_ent.pack() self.gender_ent.place(x=250, y=180)", "Patient Details\", width=20, height=2, bg='steelblue', command=self.update) self.submit.place(x=600, y=200) self.submit =", "= sorted(ids) self.final_id = self.new[len(ids)-1] self.logs = Label(self.right, text=\"Logs\", font=('arial", "bg='sea green') self.age.place(x=0, y=140) self.gender = Label(self.left, text=\"Gender\", font=('arial 18", "self.chr_ent.place(x=250, y=420) self.chr_ent.insert(0, 'NONE') self.bg = Label(self.left, text=\"Blood Group\", font=('arial", "self.box = Text(self.right, width=62, height=45) self.box.place(x=20, y=60) def add_appointment(self): self.val1", "self.master = master self.left = Frame(master, width=1000, height=800, bg='sea green')", "text=\"Allergies\", font=('arial 18 bold'), fg='black', bg='sea green') self.allergies.place(x=0, y=380) self.all_ent", "self.left = Frame(master, width=1000, height=800, bg='sea green') self.left.pack(side=LEFT) self.right =", "from tkinter import ttk from tkinter.messagebox import askyesno import re", "sql2 = \"SELECT ID FROM appointments\" self.result = c.execute(sql2) for", "self.val6=='Select Time': print(\"ty\",self.val3) tkinter.messagebox.showinfo(\"Warning\", \"Please Fill Up All Boxes\") print(self.val3)", "self.new[len(ids)-1] self.logs = Label(self.right, text=\"Logs\", font=('arial 28 bold'), fg='white', bg='steelblue')", "update.buildupdate() def read(self): import read read.buildread() def quit(self): answer =", "age, gender, location, scheduled_time, phone,date,Allergies,Chronic_Conditions,Blood_Group) VALUES(?, ?, ?, ?, ?,", "y=140) self.gender = Label(self.left, text=\"Gender\", font=('arial 18 bold'), fg='black', bg='sea", "Date\") self.date_ent = OptionMenu(self.left,self.clicked1,*options1) self.date_ent.pack() self.date_ent.place(x=250, y=260) self.clicked2=StringVar() self.clicked2.set(\"Select Time\")", "= Text(self.right, width=62, height=45) self.box.place(x=20, y=60) def add_appointment(self): self.val1 =", "fg='black', bg='sea green') self.location.place(x=0, y=220) self.date = Label(self.left, text=\"Appointment Date\",", "y=420) self.chr_ent = Entry(self.left, width=30) self.chr_ent.place(x=250, y=420) self.chr_ent.insert(0, 'NONE') self.bg", "command=self.quit) self.submit.place(x=600, y=400) sql2 = \"SELECT ID FROM appointments\" self.result", "Fill Up All Boxes\") print(self.val3) elif not(pattern1.match(self.val1)) or len(self.val1)<2: tkinter.messagebox.showinfo(\"Warning\",\"INVALID", "Details\", width=20, height=2, bg='steelblue', command=self.update) self.submit.place(x=600, y=200) self.submit = Button(self.left,", "or self.val5 == '' or self.val6=='' or self.val7=='' or self.val10=='Select", "pandas as pd import pandas as pd import datetime from", "bold'), fg='black', bg='sea green') self.name.place(x=0, y=100) self.age = Label(self.left, text=\"Age\",", "Time\") self.clicked3.set(\"Select Blood Group\") self.chr_ent.delete(0,END) self.all_ent.delete(0,END) self.all_ent.insert(0, 'NONE') self.chr_ent.insert(0, 'NONE')", "bg='sea green') self.bg.place(x=0, y=460) self.clicked3=StringVar() self.clicked3.set(\"Select Blood Group\") self.bg_ent =", "18 bold'), fg='black', bg='sea green') self.bg.place(x=0, y=460) self.clicked3=StringVar() self.clicked3.set(\"Select Blood", "bg='steelblue', command=self.update) self.submit.place(x=600, y=200) self.submit = Button(self.left, text=\"Read Names\", width=20,", "18 bold'), fg='black', bg='sea green') self.time.place(x=0, y=300) self.phone = Label(self.left,", "self.right = Frame(master, width=1000, height=800, bg='steelblue') self.right.pack(side=RIGHT) self.heading = Label(self.left,", "Top.pack(side=TOP, fill=X) Form = Frame(root, height=1) Form.pack(side=TOP, pady=1) lbl_title =", "= sqlite3.connect('database copy.db') c = conn.cursor() ids = [] class", "18 bold'), fg='black', bg='sea green') self.allergies.place(x=0, y=380) self.all_ent = Entry(self.left,", "self.bg_ent.place(x=250, y=460) self.name_ent = Entry(self.left, width=30) self.name_ent.place(x=250, y=100) self.age_ent =", "self.name_ent = Entry(self.left, width=30) self.name_ent.place(x=250, y=100) self.age_ent = Entry(self.left, width=30)", "y=220) self.clicked1=StringVar() self.clicked1.set(\"Select Date\") self.date_ent = OptionMenu(self.left,self.clicked1,*options1) self.date_ent.pack() self.date_ent.place(x=250, y=260)", "self.val5=='Select Date' or self.val6=='Select Time': print(\"ty\",self.val3) tkinter.messagebox.showinfo(\"Warning\", \"Please Fill Up", "self.date.place(x=0, y=260) self.time = Label(self.left, text=\"Appointment Time\", font=('arial 18 bold'),", "Date' or self.val6=='Select Time': print(\"ty\",self.val3) tkinter.messagebox.showinfo(\"Warning\", \"Please Fill Up All", "if answer: root.destroy() root = Tk() root.title(\"Shalom Clinic\") #root.geometry(\"1200x720+0+0\") root.attributes('-fullscreen',", "text=\"Phone Number\", font=('arial 18 bold'), fg='black', bg='sea green') self.phone.place(x=0, y=340)", "ids = [] class Application: def __init__(self, master): self.master =", "' + str(self.val5)+','+str(self.val6)) self.name_ent.delete(0,END) self.age_ent.delete(0,END) self.location_ent.delete(0,END) self.phone_ent.delete(0,END) self.clicked1.set(\"Select Date\") self.clicked2.set(\"Select", "def view(self): import view view.call() def update(self): import update update.buildupdate()", "= self.phone_ent.get() self.val8 = self.all_ent.get() self.val9 = self.chr_ent.get() self.val10 =", "bg='sea green') self.date.place(x=0, y=260) self.time = Label(self.left, text=\"Appointment Time\", font=('arial", "view view.call() def update(self): import update update.buildupdate() def read(self): import", "conn = sqlite3.connect('database copy.db') c = conn.cursor() ids = []", "self.val6=='' or self.val7=='' or self.val10=='Select Blood Group' or self.val5=='Select Date'", "text=\"Location\", font=('arial 18 bold'), fg='black', bg='sea green') self.location.place(x=0, y=220) self.date", "add_appointment(self): self.val1 = self.name_ent.get() self.val2 = self.age_ent.get() self.val3 = self.clicked.get()", "root.attributes('-fullscreen', True) root.resizable(0, 0) Top = Frame(root, bd=1, relief=RIDGE) Top.pack(side=TOP,", "= OptionMenu(self.left,self.clicked2,*options2) self.time_ent.pack() self.time_ent.place(x=250, y=300) self.phone_ent = Entry(self.left, width=30) self.phone_ent.place(x=250,", "y=180) self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250, y=220) self.clicked1=StringVar() self.clicked1.set(\"Select Date\") self.date_ent = OptionMenu(self.left,self.clicked1,*options1)", "self.age_ent = Entry(self.left, width=30) self.age_ent.place(x=250, y=140) self.clicked=StringVar() self.clicked.set(\"Male\") self.gender_ent =", "or self.val6=='' or self.val7=='' or self.val10=='Select Blood Group' or self.val5=='Select", "== '' or self.val5 == '' or self.val6=='' or self.val7==''", "= Label(self.left, text=\"Patient's Name\", font=('arial 18 bold'), fg='black', bg='sea green')", "tkinter.messagebox.showinfo(\"Warning\", \"INVALID Phone Number\") else: sql = \"INSERT INTO 'appointments'", "Frame(master, width=1000, height=800, bg='steelblue') self.right.pack(side=RIGHT) self.heading = Label(self.left, text=\"Appointments\", font=('arial", "= self.row[0] ids.append(self.id) self.new = sorted(ids) self.final_id = self.new[len(ids)-1] self.logs", "height=800, bg='steelblue') self.right.pack(side=RIGHT) self.heading = Label(self.left, text=\"Appointments\", font=('arial 40 bold'),", "self.chr_ent.get() self.val10 = self.clicked3.get() pattern=re.compile(\"[7-9][0-9]{9}\") pattern=re.compile(\"[7-9][0-9]{9}\") pattern2=re.compile(\"[1-9]([0-9])*\") pattern1=re.compile(r'([A-Z])(\\s*[A-Z])*$') pattern.match(self.val7) if", "self.val3, self.val4, self.val6, self.val7,self.val5,self.val8,self.val9,self.val10)) conn.commit() tkinter.messagebox.showinfo(\"Success\", \"Appointment for \" +", "def add_appointment(self): self.val1 = self.name_ent.get() self.val2 = self.age_ent.get() self.val3 =", "self.gender_ent.place(x=250, y=180) self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250, y=220) self.clicked1=StringVar() self.clicked1.set(\"Select Date\") self.date_ent =", "bg='sea green') self.location.place(x=0, y=220) self.date = Label(self.left, text=\"Appointment Date\", font=('arial", "datesx = pd.date_range(today, date2).tolist() conn = sqlite3.connect('database copy.db') c =", "sql = \"INSERT INTO 'appointments' (name, age, gender, location, scheduled_time,", "text=\"Appointments\", font=('arial 40 bold'), fg='black', bg='sea green') self.heading.place(x=0, y=0) self.name", "Button(self.left, text=\"Read Names\", width=20, height=2, bg='steelblue', command=self.read) self.submit.place(x=600, y=300) self.submit", "bold'), fg='black', bg='sea green') self.time.place(x=0, y=300) self.phone = Label(self.left, text=\"Phone", "Phone Number\") else: sql = \"INSERT INTO 'appointments' (name, age,", "text=\"View/Update Patient Details\", width=20, height=2, bg='steelblue', command=self.update) self.submit.place(x=600, y=200) self.submit", "import view view.call() def update(self): import update update.buildupdate() def read(self):", "askyesno import re import sqlite3 import tkinter.messagebox import pandas as", "self.location = Label(self.left, text=\"Location\", font=('arial 18 bold'), fg='black', bg='sea green')", "height=2, bg='steelblue', command=self.view) self.submit.place(x=600, y=100) self.submit = Button(self.left, text=\"View/Update Patient", "pattern.match(self.val7) if self.val1 == '' or self.val2 == '' or", "len(self.val7)>10: tkinter.messagebox.showinfo(\"Warning\", \"INVALID Phone Number\") else: sql = \"INSERT INTO", "18 bold'), fg='black', bg='sea green') self.chronic.place(x=0, y=420) self.chr_ent = Entry(self.left,", "command=self.view) self.submit.place(x=600, y=100) self.submit = Button(self.left, text=\"View/Update Patient Details\", width=20,", "Names\", width=20, height=2, bg='steelblue', command=self.read) self.submit.place(x=600, y=300) self.submit = Button(self.left,", "bg='steelblue') self.logs.place(x=0, y=0) self.box = Text(self.right, width=62, height=45) self.box.place(x=20, y=60)", "tkinter.messagebox.showinfo(\"Success\", \"Appointment for \" + str(self.val1) + \" has been", "import pandas as pd import pandas as pd import datetime", "want to exit?') if answer: root.destroy() root = Tk() root.title(\"Shalom", "= Frame(root, height=1) Form.pack(side=TOP, pady=1) lbl_title = Label(Top, text =", "y=260) self.time = Label(self.left, text=\"Appointment Time\", font=('arial 18 bold'), fg='black',", "= conn.cursor() ids = [] class Application: def __init__(self, master):", "self.val7 = self.phone_ent.get() self.val8 = self.all_ent.get() self.val9 = self.chr_ent.get() self.val10", "bold'), fg='black', bg='sea green') self.chronic.place(x=0, y=420) self.chr_ent = Entry(self.left, width=30)", "self.location.place(x=0, y=220) self.date = Label(self.left, text=\"Appointment Date\", font=('arial 18 bold'),", "= c.execute(sql2) for self.row in self.result: self.id = self.row[0] ids.append(self.id)", "= '12-31-2050' datesx = pd.date_range(today, date2).tolist() conn = sqlite3.connect('database copy.db')", "self.new = sorted(ids) self.final_id = self.new[len(ids)-1] self.logs = Label(self.right, text=\"Logs\",", "?, ?,?,?,?,?)\" c.execute(sql, (self.val1, self.val2, self.val3, self.val4, self.val6, self.val7,self.val5,self.val8,self.val9,self.val10)) conn.commit()", "import datetime from datetime import date import tkinter as tk", "FROM appointments\" self.result = c.execute(sql2) for self.row in self.result: self.id", "self.val6 = self.clicked2.get() self.val7 = self.phone_ent.get() self.val8 = self.all_ent.get() self.val9", "bold'), fg='black', bg='sea green') self.date.place(x=0, y=260) self.time = Label(self.left, text=\"Appointment", "tkinter.messagebox.showinfo(\"Warning\",\"INVALID Name\") elif not(pattern2.match(self.val2)) or len(self.val2)>=3: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Age\") elif not(pattern.match(self.val7))", "self.submit = Button(self.left, text=\"View Appointments\", width=20, height=2, bg='steelblue', command=self.view) self.submit.place(x=600,", "'05-10-2021' date2 = '12-31-2050' datesx = pd.date_range(today, date2).tolist() conn =", "Label(self.left, text=\"Patient's Name\", font=('arial 18 bold'), fg='black', bg='sea green') self.name.place(x=0,", "self.clicked2.set(\"Select Time\") self.time_ent = OptionMenu(self.left,self.clicked2,*options2) self.time_ent.pack() self.time_ent.place(x=250, y=300) self.phone_ent =", "40 bold'), fg='black', bg='sea green') self.heading.place(x=0, y=0) self.name = Label(self.left,", "Boxes\") print(self.val3) elif not(pattern1.match(self.val1)) or len(self.val1)<2: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Name\") elif not(pattern2.match(self.val2))", "18 bold'), fg='black', bg='sea green') self.gender.place(x=0, y=180) self.location = Label(self.left,", "self.val3 == '' or self.val4 == '' or self.val5 ==", "import ttk from tkinter.messagebox import askyesno import re import sqlite3", "= Label(self.left, text=\"Appointment Date\", font=('arial 18 bold'), fg='black', bg='sea green')", "self.name_ent.get() self.val2 = self.age_ent.get() self.val3 = self.clicked.get() self.val4 = self.location_ent.get()", "Name\") elif not(pattern2.match(self.val2)) or len(self.val2)>=3: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Age\") elif not(pattern.match(self.val7)) or", "bg='steelblue') self.right.pack(side=RIGHT) self.heading = Label(self.left, text=\"Appointments\", font=('arial 40 bold'), fg='black',", "bold'), fg='black', bg='sea green') self.heading.place(x=0, y=0) self.name = Label(self.left, text=\"Patient's", "green') self.date.place(x=0, y=260) self.time = Label(self.left, text=\"Appointment Time\", font=('arial 18", "Exit', message='Are you sure you want to exit?') if answer:", "sqlite3 import tkinter.messagebox import pandas as pd import pandas as", "font=('arial', 15)) lbl_title.pack(fill=X) options=[\"Male\",\"Female\"] options1=datesx options2=[\"10:00:00\",\"11:00:00\",\"13:00:00\"] options3=[\"O+\",\"O-\",\"A+\",\"A-\",\"B+\",\"B-\",\"AB+\",\"AB-\"] b = Application(root)", "command=self.update) self.submit.place(x=600, y=200) self.submit = Button(self.left, text=\"Read Names\", width=20, height=2,", "self.val2 == '' or self.val3 == '' or self.val4 ==", "elif not(pattern2.match(self.val2)) or len(self.val2)>=3: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Age\") elif not(pattern.match(self.val7)) or len(self.val7)>10:", "fg='black', bg='sea green') self.bg.place(x=0, y=460) self.clicked3=StringVar() self.clicked3.set(\"Select Blood Group\") self.bg_ent", "self.submit = Button(self.left, text=\"View/Update Patient Details\", width=20, height=2, bg='steelblue', command=self.update)", "self.phone = Label(self.left, text=\"Phone Number\", font=('arial 18 bold'), fg='black', bg='sea", "= Frame(master, width=1000, height=800, bg='sea green') self.left.pack(side=LEFT) self.right = Frame(master,", "y=200) self.submit = Button(self.left, text=\"Read Names\", width=20, height=2, bg='steelblue', command=self.read)", "= Label(self.left, text=\"Gender\", font=('arial 18 bold'), fg='black', bg='sea green') self.gender.place(x=0,", "font=('arial 18 bold'), fg='black', bg='sea green') self.allergies.place(x=0, y=380) self.all_ent =", "= OptionMenu(self.left,self.clicked1,*options1) self.date_ent.pack() self.date_ent.place(x=250, y=260) self.clicked2=StringVar() self.clicked2.set(\"Select Time\") self.time_ent =", "len(self.val2)>=3: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Age\") elif not(pattern.match(self.val7)) or len(self.val7)>10: tkinter.messagebox.showinfo(\"Warning\", \"INVALID Phone", "update(self): import update update.buildupdate() def read(self): import read read.buildread() def", "y=100) self.age_ent = Entry(self.left, width=30) self.age_ent.place(x=250, y=140) self.clicked=StringVar() self.clicked.set(\"Male\") self.gender_ent", "self.clicked3=StringVar() self.clicked3.set(\"Select Blood Group\") self.bg_ent = OptionMenu(self.left,self.clicked3,*options3) self.bg_ent.pack() self.bg_ent.place(x=250, y=460)", "'NONE') self.chr_ent.insert(0, 'NONE') def view(self): import view view.call() def update(self):", "OptionMenu(self.left,self.clicked1,*options1) self.date_ent.pack() self.date_ent.place(x=250, y=260) self.clicked2=StringVar() self.clicked2.set(\"Select Time\") self.time_ent = OptionMenu(self.left,self.clicked2,*options2)", "fg='black', bg='sea green') self.gender.place(x=0, y=180) self.location = Label(self.left, text=\"Location\", font=('arial", "c.execute(sql, (self.val1, self.val2, self.val3, self.val4, self.val6, self.val7,self.val5,self.val8,self.val9,self.val10)) conn.commit() tkinter.messagebox.showinfo(\"Success\", \"Appointment", "self.phone_ent.get() self.val8 = self.all_ent.get() self.val9 = self.chr_ent.get() self.val10 = self.clicked3.get()", "has been created\" ) self.box.insert(END, '\\n Appointment fixed for '", "datetime import datetime from datetime import date import tkinter as", "height=1) Form.pack(side=TOP, pady=1) lbl_title = Label(Top, text = \"Shalom Clinic\",", "self.phone_ent.place(x=250, y=340) self.submit = Button(self.left, text=\"Add Appointment\", width=20, height=2, bg='steelblue',", "bg='sea green') self.phone.place(x=0, y=340) self.allergies = Label(self.left, text=\"Allergies\", font=('arial 18", "self.age_ent.delete(0,END) self.location_ent.delete(0,END) self.phone_ent.delete(0,END) self.clicked1.set(\"Select Date\") self.clicked2.set(\"Select Time\") self.clicked3.set(\"Select Blood Group\")", "Name\", font=('arial 18 bold'), fg='black', bg='sea green') self.name.place(x=0, y=100) self.age", "tkinter import ttk from tkinter.messagebox import askyesno import re import", "Date\") self.clicked2.set(\"Select Time\") self.clicked3.set(\"Select Blood Group\") self.chr_ent.delete(0,END) self.all_ent.delete(0,END) self.all_ent.insert(0, 'NONE')", "Label(self.left, text=\"Chronic Conditions\", font=('arial 18 bold'), fg='black', bg='sea green') self.chronic.place(x=0,", "= self.clicked.get() self.val4 = self.location_ent.get() self.val5 = self.clicked1.get() self.val6 =", "or len(self.val1)<2: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Name\") elif not(pattern2.match(self.val2)) or len(self.val2)>=3: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Age\")", "y=0) self.box = Text(self.right, width=62, height=45) self.box.place(x=20, y=60) def add_appointment(self):", "= Frame(master, width=1000, height=800, bg='steelblue') self.right.pack(side=RIGHT) self.heading = Label(self.left, text=\"Appointments\",", "parser today = date.today() date1 = '05-10-2021' date2 = '12-31-2050'", "lbl_title.pack(fill=X) options=[\"Male\",\"Female\"] options1=datesx options2=[\"10:00:00\",\"11:00:00\",\"13:00:00\"] options3=[\"O+\",\"O-\",\"A+\",\"A-\",\"B+\",\"B-\",\"AB+\",\"AB-\"] b = Application(root) root.resizable(False, False)", "+ str(self.val1) + '\\n at ' + str(self.val5)+','+str(self.val6)) self.name_ent.delete(0,END) self.age_ent.delete(0,END)", "self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250, y=220) self.clicked1=StringVar() self.clicked1.set(\"Select Date\") self.date_ent = OptionMenu(self.left,self.clicked1,*options1) self.date_ent.pack()", "or self.val6=='Select Time': print(\"ty\",self.val3) tkinter.messagebox.showinfo(\"Warning\", \"Please Fill Up All Boxes\")", "text=\"Add Appointment\", width=20, height=2, bg='steelblue', command=self.add_appointment) self.submit.place(x=270, y=500) self.submit =", "read read.buildread() def quit(self): answer = askyesno(title='Confirm Exit', message='Are you", "'NONE') self.bg = Label(self.left, text=\"Blood Group\", font=('arial 18 bold'), fg='black',", "= self.new[len(ids)-1] self.logs = Label(self.right, text=\"Logs\", font=('arial 28 bold'), fg='white',", "= Label(self.left, text=\"Allergies\", font=('arial 18 bold'), fg='black', bg='sea green') self.allergies.place(x=0,", "else: sql = \"INSERT INTO 'appointments' (name, age, gender, location,", "= Label(self.left, text=\"Chronic Conditions\", font=('arial 18 bold'), fg='black', bg='sea green')", "master self.left = Frame(master, width=1000, height=800, bg='sea green') self.left.pack(side=LEFT) self.right", "= Label(self.right, text=\"Logs\", font=('arial 28 bold'), fg='white', bg='steelblue') self.logs.place(x=0, y=0)", "or self.val5=='Select Date' or self.val6=='Select Time': print(\"ty\",self.val3) tkinter.messagebox.showinfo(\"Warning\", \"Please Fill", "self.val1 = self.name_ent.get() self.val2 = self.age_ent.get() self.val3 = self.clicked.get() self.val4", "self.val10 = self.clicked3.get() pattern=re.compile(\"[7-9][0-9]{9}\") pattern=re.compile(\"[7-9][0-9]{9}\") pattern2=re.compile(\"[1-9]([0-9])*\") pattern1=re.compile(r'([A-Z])(\\s*[A-Z])*$') pattern.match(self.val7) if self.val1", "?, ?, ?, ?,?,?,?,?)\" c.execute(sql, (self.val1, self.val2, self.val3, self.val4, self.val6,", "date.today() date1 = '05-10-2021' date2 = '12-31-2050' datesx = pd.date_range(today,", "self.clicked2=StringVar() self.clicked2.set(\"Select Time\") self.time_ent = OptionMenu(self.left,self.clicked2,*options2) self.time_ent.pack() self.time_ent.place(x=250, y=300) self.phone_ent", "+ str(self.val5)+','+str(self.val6)) self.name_ent.delete(0,END) self.age_ent.delete(0,END) self.location_ent.delete(0,END) self.phone_ent.delete(0,END) self.clicked1.set(\"Select Date\") self.clicked2.set(\"Select Time\")", "font=('arial 40 bold'), fg='black', bg='sea green') self.heading.place(x=0, y=0) self.name =", "(self.val1, self.val2, self.val3, self.val4, self.val6, self.val7,self.val5,self.val8,self.val9,self.val10)) conn.commit() tkinter.messagebox.showinfo(\"Success\", \"Appointment for", "str(self.val1) + '\\n at ' + str(self.val5)+','+str(self.val6)) self.name_ent.delete(0,END) self.age_ent.delete(0,END) self.location_ent.delete(0,END)", "Clinic\") #root.geometry(\"1200x720+0+0\") root.attributes('-fullscreen', True) root.resizable(0, 0) Top = Frame(root, bd=1,", "created\" ) self.box.insert(END, '\\n Appointment fixed for ' + str(self.val1)", "self.val2, self.val3, self.val4, self.val6, self.val7,self.val5,self.val8,self.val9,self.val10)) conn.commit() tkinter.messagebox.showinfo(\"Success\", \"Appointment for \"", "import tkinter.messagebox import pandas as pd import pandas as pd", "y=300) self.phone = Label(self.left, text=\"Phone Number\", font=('arial 18 bold'), fg='black',", "self.submit = Button(self.left, text=\"Read Names\", width=20, height=2, bg='steelblue', command=self.read) self.submit.place(x=600,", "<reponame>jeffrypaul37/Hospital-Management-System from tkinter import * from tkcalendar import Calendar from", "\"SELECT ID FROM appointments\" self.result = c.execute(sql2) for self.row in", "self.age_ent.get() self.val3 = self.clicked.get() self.val4 = self.location_ent.get() self.val5 = self.clicked1.get()", "from tkinter import * from tkcalendar import Calendar from datetime", "Number\", font=('arial 18 bold'), fg='black', bg='sea green') self.phone.place(x=0, y=340) self.allergies", "self.row[0] ids.append(self.id) self.new = sorted(ids) self.final_id = self.new[len(ids)-1] self.logs =", "Text(self.right, width=62, height=45) self.box.place(x=20, y=60) def add_appointment(self): self.val1 = self.name_ent.get()", "rrule, parser today = date.today() date1 = '05-10-2021' date2 =", "Time': print(\"ty\",self.val3) tkinter.messagebox.showinfo(\"Warning\", \"Please Fill Up All Boxes\") print(self.val3) elif", "= Label(self.left, text=\"Location\", font=('arial 18 bold'), fg='black', bg='sea green') self.location.place(x=0,", "All Boxes\") print(self.val3) elif not(pattern1.match(self.val1)) or len(self.val1)<2: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Name\") elif", "bold'), fg='black', bg='sea green') self.location.place(x=0, y=220) self.date = Label(self.left, text=\"Appointment", "width=1000, height=800, bg='sea green') self.left.pack(side=LEFT) self.right = Frame(master, width=1000, height=800,", "self.all_ent.get() self.val9 = self.chr_ent.get() self.val10 = self.clicked3.get() pattern=re.compile(\"[7-9][0-9]{9}\") pattern=re.compile(\"[7-9][0-9]{9}\") pattern2=re.compile(\"[1-9]([0-9])*\")", "Form.pack(side=TOP, pady=1) lbl_title = Label(Top, text = \"Shalom Clinic\", font=('arial',", "'\\n Appointment fixed for ' + str(self.val1) + '\\n at", "self.val4, self.val6, self.val7,self.val5,self.val8,self.val9,self.val10)) conn.commit() tkinter.messagebox.showinfo(\"Success\", \"Appointment for \" + str(self.val1)", "= master self.left = Frame(master, width=1000, height=800, bg='sea green') self.left.pack(side=LEFT)", "Label(self.right, text=\"Logs\", font=('arial 28 bold'), fg='white', bg='steelblue') self.logs.place(x=0, y=0) self.box", "self.chr_ent.insert(0, 'NONE') self.bg = Label(self.left, text=\"Blood Group\", font=('arial 18 bold'),", "ids.append(self.id) self.new = sorted(ids) self.final_id = self.new[len(ids)-1] self.logs = Label(self.right,", "scheduled_time, phone,date,Allergies,Chronic_Conditions,Blood_Group) VALUES(?, ?, ?, ?, ?, ?,?,?,?,?)\" c.execute(sql, (self.val1,", "y=380) self.all_ent = Entry(self.left, width=30) self.all_ent.place(x=250, y=380) self.all_ent.insert(0, 'NONE') self.chronic", "= \"SELECT ID FROM appointments\" self.result = c.execute(sql2) for self.row", "Label(self.left, text=\"Appointments\", font=('arial 40 bold'), fg='black', bg='sea green') self.heading.place(x=0, y=0)", "Frame(root, bd=1, relief=RIDGE) Top.pack(side=TOP, fill=X) Form = Frame(root, height=1) Form.pack(side=TOP,", "import datetime from dateutil import rrule, parser today = date.today()", "green') self.location.place(x=0, y=220) self.date = Label(self.left, text=\"Appointment Date\", font=('arial 18", "self.phone_ent.delete(0,END) self.clicked1.set(\"Select Date\") self.clicked2.set(\"Select Time\") self.clicked3.set(\"Select Blood Group\") self.chr_ent.delete(0,END) self.all_ent.delete(0,END)", "fg='black', bg='sea green') self.allergies.place(x=0, y=380) self.all_ent = Entry(self.left, width=30) self.all_ent.place(x=250,", "self.result: self.id = self.row[0] ids.append(self.id) self.new = sorted(ids) self.final_id =", "import sqlite3 import tkinter.messagebox import pandas as pd import pandas", "= Button(self.left, text=\"Exit\", width=20, height=2, bg='steelblue', command=self.quit) self.submit.place(x=600, y=400) sql2", "'NONE') def view(self): import view view.call() def update(self): import update", "green') self.time.place(x=0, y=300) self.phone = Label(self.left, text=\"Phone Number\", font=('arial 18", "view(self): import view view.call() def update(self): import update update.buildupdate() def", "tkinter as tk from tkinter import ttk from tkinter.messagebox import", "= \"Shalom Clinic\", font=('arial', 15)) lbl_title.pack(fill=X) options=[\"Male\",\"Female\"] options1=datesx options2=[\"10:00:00\",\"11:00:00\",\"13:00:00\"] options3=[\"O+\",\"O-\",\"A+\",\"A-\",\"B+\",\"B-\",\"AB+\",\"AB-\"]", "tkinter import * from tkcalendar import Calendar from datetime import", "18 bold'), fg='black', bg='sea green') self.phone.place(x=0, y=340) self.allergies = Label(self.left,", "def read(self): import read read.buildread() def quit(self): answer = askyesno(title='Confirm", "Label(self.left, text=\"Phone Number\", font=('arial 18 bold'), fg='black', bg='sea green') self.phone.place(x=0,", "pattern1=re.compile(r'([A-Z])(\\s*[A-Z])*$') pattern.match(self.val7) if self.val1 == '' or self.val2 == ''", "y=400) sql2 = \"SELECT ID FROM appointments\" self.result = c.execute(sql2)", "you want to exit?') if answer: root.destroy() root = Tk()", "self.submit.place(x=600, y=400) sql2 = \"SELECT ID FROM appointments\" self.result =", "'\\n at ' + str(self.val5)+','+str(self.val6)) self.name_ent.delete(0,END) self.age_ent.delete(0,END) self.location_ent.delete(0,END) self.phone_ent.delete(0,END) self.clicked1.set(\"Select", "quit(self): answer = askyesno(title='Confirm Exit', message='Are you sure you want", "Button(self.left, text=\"Exit\", width=20, height=2, bg='steelblue', command=self.quit) self.submit.place(x=600, y=400) sql2 =", "master): self.master = master self.left = Frame(master, width=1000, height=800, bg='sea", "bold'), fg='black', bg='sea green') self.phone.place(x=0, y=340) self.allergies = Label(self.left, text=\"Allergies\",", "bold'), fg='black', bg='sea green') self.allergies.place(x=0, y=380) self.all_ent = Entry(self.left, width=30)", "self.val7=='' or self.val10=='Select Blood Group' or self.val5=='Select Date' or self.val6=='Select", "fixed for ' + str(self.val1) + '\\n at ' +", "self.bg_ent = OptionMenu(self.left,self.clicked3,*options3) self.bg_ent.pack() self.bg_ent.place(x=250, y=460) self.name_ent = Entry(self.left, width=30)", "self.location_ent.get() self.val5 = self.clicked1.get() self.val6 = self.clicked2.get() self.val7 = self.phone_ent.get()", "root.title(\"Shalom Clinic\") #root.geometry(\"1200x720+0+0\") root.attributes('-fullscreen', True) root.resizable(0, 0) Top = Frame(root,", "18 bold'), fg='black', bg='sea green') self.age.place(x=0, y=140) self.gender = Label(self.left,", "self.chronic = Label(self.left, text=\"Chronic Conditions\", font=('arial 18 bold'), fg='black', bg='sea", "text=\"Appointment Time\", font=('arial 18 bold'), fg='black', bg='sea green') self.time.place(x=0, y=300)", "self.clicked1.set(\"Select Date\") self.date_ent = OptionMenu(self.left,self.clicked1,*options1) self.date_ent.pack() self.date_ent.place(x=250, y=260) self.clicked2=StringVar() self.clicked2.set(\"Select", "= Entry(self.left, width=30) self.phone_ent.place(x=250, y=340) self.submit = Button(self.left, text=\"Add Appointment\",", "Application: def __init__(self, master): self.master = master self.left = Frame(master,", "\" has been created\" ) self.box.insert(END, '\\n Appointment fixed for", "self.logs = Label(self.right, text=\"Logs\", font=('arial 28 bold'), fg='white', bg='steelblue') self.logs.place(x=0,", "text = \"Shalom Clinic\", font=('arial', 15)) lbl_title.pack(fill=X) options=[\"Male\",\"Female\"] options1=datesx options2=[\"10:00:00\",\"11:00:00\",\"13:00:00\"]", "self.clicked3.get() pattern=re.compile(\"[7-9][0-9]{9}\") pattern=re.compile(\"[7-9][0-9]{9}\") pattern2=re.compile(\"[1-9]([0-9])*\") pattern1=re.compile(r'([A-Z])(\\s*[A-Z])*$') pattern.match(self.val7) if self.val1 == ''", "?, ?, ?,?,?,?,?)\" c.execute(sql, (self.val1, self.val2, self.val3, self.val4, self.val6, self.val7,self.val5,self.val8,self.val9,self.val10))", "bg='sea green') self.heading.place(x=0, y=0) self.name = Label(self.left, text=\"Patient's Name\", font=('arial", "= Button(self.left, text=\"Add Appointment\", width=20, height=2, bg='steelblue', command=self.add_appointment) self.submit.place(x=270, y=500)", "self.time.place(x=0, y=300) self.phone = Label(self.left, text=\"Phone Number\", font=('arial 18 bold'),", "self.location_ent.delete(0,END) self.phone_ent.delete(0,END) self.clicked1.set(\"Select Date\") self.clicked2.set(\"Select Time\") self.clicked3.set(\"Select Blood Group\") self.chr_ent.delete(0,END)", "update update.buildupdate() def read(self): import read read.buildread() def quit(self): answer", "\"Appointment for \" + str(self.val1) + \" has been created\"", "y=60) def add_appointment(self): self.val1 = self.name_ent.get() self.val2 = self.age_ent.get() self.val3", "Frame(master, width=1000, height=800, bg='sea green') self.left.pack(side=LEFT) self.right = Frame(master, width=1000,", "y=140) self.clicked=StringVar() self.clicked.set(\"Male\") self.gender_ent = OptionMenu(self.left,self.clicked,*options) self.gender_ent.pack() self.gender_ent.place(x=250, y=180) self.location_ent=Entry(self.left,width=30)", "= self.all_ent.get() self.val9 = self.chr_ent.get() self.val10 = self.clicked3.get() pattern=re.compile(\"[7-9][0-9]{9}\") pattern=re.compile(\"[7-9][0-9]{9}\")", "self.row in self.result: self.id = self.row[0] ids.append(self.id) self.new = sorted(ids)", "self.age.place(x=0, y=140) self.gender = Label(self.left, text=\"Gender\", font=('arial 18 bold'), fg='black',", "= self.clicked2.get() self.val7 = self.phone_ent.get() self.val8 = self.all_ent.get() self.val9 =", "tkinter.messagebox.showinfo(\"Warning\",\"INVALID Age\") elif not(pattern.match(self.val7)) or len(self.val7)>10: tkinter.messagebox.showinfo(\"Warning\", \"INVALID Phone Number\")", "Form = Frame(root, height=1) Form.pack(side=TOP, pady=1) lbl_title = Label(Top, text", "answer = askyesno(title='Confirm Exit', message='Are you sure you want to", "message='Are you sure you want to exit?') if answer: root.destroy()", "y=340) self.submit = Button(self.left, text=\"Add Appointment\", width=20, height=2, bg='steelblue', command=self.add_appointment)", "elif not(pattern.match(self.val7)) or len(self.val7)>10: tkinter.messagebox.showinfo(\"Warning\", \"INVALID Phone Number\") else: sql", "sure you want to exit?') if answer: root.destroy() root =", "y=460) self.clicked3=StringVar() self.clicked3.set(\"Select Blood Group\") self.bg_ent = OptionMenu(self.left,self.clicked3,*options3) self.bg_ent.pack() self.bg_ent.place(x=250,", "import rrule, parser today = date.today() date1 = '05-10-2021' date2", "Entry(self.left, width=30) self.chr_ent.place(x=250, y=420) self.chr_ent.insert(0, 'NONE') self.bg = Label(self.left, text=\"Blood", "15)) lbl_title.pack(fill=X) options=[\"Male\",\"Female\"] options1=datesx options2=[\"10:00:00\",\"11:00:00\",\"13:00:00\"] options3=[\"O+\",\"O-\",\"A+\",\"A-\",\"B+\",\"B-\",\"AB+\",\"AB-\"] b = Application(root) root.resizable(False,", "self.time_ent.place(x=250, y=300) self.phone_ent = Entry(self.left, width=30) self.phone_ent.place(x=250, y=340) self.submit =", "Group\", font=('arial 18 bold'), fg='black', bg='sea green') self.bg.place(x=0, y=460) self.clicked3=StringVar()", "Button(self.left, text=\"Add Appointment\", width=20, height=2, bg='steelblue', command=self.add_appointment) self.submit.place(x=270, y=500) self.submit", "Clinic\", font=('arial', 15)) lbl_title.pack(fill=X) options=[\"Male\",\"Female\"] options1=datesx options2=[\"10:00:00\",\"11:00:00\",\"13:00:00\"] options3=[\"O+\",\"O-\",\"A+\",\"A-\",\"B+\",\"B-\",\"AB+\",\"AB-\"] b =", "font=('arial 18 bold'), fg='black', bg='sea green') self.time.place(x=0, y=300) self.phone =", "= Label(self.left, text=\"Phone Number\", font=('arial 18 bold'), fg='black', bg='sea green')", "y=420) self.chr_ent.insert(0, 'NONE') self.bg = Label(self.left, text=\"Blood Group\", font=('arial 18", "'appointments' (name, age, gender, location, scheduled_time, phone,date,Allergies,Chronic_Conditions,Blood_Group) VALUES(?, ?, ?,", "ttk from tkinter.messagebox import askyesno import re import sqlite3 import", "re import sqlite3 import tkinter.messagebox import pandas as pd import", "INTO 'appointments' (name, age, gender, location, scheduled_time, phone,date,Allergies,Chronic_Conditions,Blood_Group) VALUES(?, ?,", "from datetime import date import tkinter as tk from tkinter", "for ' + str(self.val1) + '\\n at ' + str(self.val5)+','+str(self.val6))", "text=\"View Appointments\", width=20, height=2, bg='steelblue', command=self.view) self.submit.place(x=600, y=100) self.submit =", "Time\") self.time_ent = OptionMenu(self.left,self.clicked2,*options2) self.time_ent.pack() self.time_ent.place(x=250, y=300) self.phone_ent = Entry(self.left,", "self.submit.place(x=600, y=300) self.submit = Button(self.left, text=\"Exit\", width=20, height=2, bg='steelblue', command=self.quit)", "fg='black', bg='sea green') self.name.place(x=0, y=100) self.age = Label(self.left, text=\"Age\", font=('arial", "font=('arial 18 bold'), fg='black', bg='sea green') self.age.place(x=0, y=140) self.gender =", "\"Shalom Clinic\", font=('arial', 15)) lbl_title.pack(fill=X) options=[\"Male\",\"Female\"] options1=datesx options2=[\"10:00:00\",\"11:00:00\",\"13:00:00\"] options3=[\"O+\",\"O-\",\"A+\",\"A-\",\"B+\",\"B-\",\"AB+\",\"AB-\"] b", "= Button(self.left, text=\"View Appointments\", width=20, height=2, bg='steelblue', command=self.view) self.submit.place(x=600, y=100)", "'12-31-2050' datesx = pd.date_range(today, date2).tolist() conn = sqlite3.connect('database copy.db') c", "self.val2 = self.age_ent.get() self.val3 = self.clicked.get() self.val4 = self.location_ent.get() self.val5", "sqlite3.connect('database copy.db') c = conn.cursor() ids = [] class Application:", "self.age = Label(self.left, text=\"Age\", font=('arial 18 bold'), fg='black', bg='sea green')", "fg='black', bg='sea green') self.heading.place(x=0, y=0) self.name = Label(self.left, text=\"Patient's Name\",", "self.name = Label(self.left, text=\"Patient's Name\", font=('arial 18 bold'), fg='black', bg='sea", "green') self.name.place(x=0, y=100) self.age = Label(self.left, text=\"Age\", font=('arial 18 bold'),", "y=100) self.age = Label(self.left, text=\"Age\", font=('arial 18 bold'), fg='black', bg='sea", "bg='sea green') self.name.place(x=0, y=100) self.age = Label(self.left, text=\"Age\", font=('arial 18", "#root.geometry(\"1200x720+0+0\") root.attributes('-fullscreen', True) root.resizable(0, 0) Top = Frame(root, bd=1, relief=RIDGE)", "phone,date,Allergies,Chronic_Conditions,Blood_Group) VALUES(?, ?, ?, ?, ?, ?,?,?,?,?)\" c.execute(sql, (self.val1, self.val2,", "tk from tkinter import ttk from tkinter.messagebox import askyesno import", "self.date_ent.place(x=250, y=260) self.clicked2=StringVar() self.clicked2.set(\"Select Time\") self.time_ent = OptionMenu(self.left,self.clicked2,*options2) self.time_ent.pack() self.time_ent.place(x=250,", "== '' or self.val4 == '' or self.val5 == ''", "Appointments\", width=20, height=2, bg='steelblue', command=self.view) self.submit.place(x=600, y=100) self.submit = Button(self.left,", "Appointment\", width=20, height=2, bg='steelblue', command=self.add_appointment) self.submit.place(x=270, y=500) self.submit = Button(self.left,", "in self.result: self.id = self.row[0] ids.append(self.id) self.new = sorted(ids) self.final_id", "pd import datetime from dateutil import rrule, parser today =", "' + str(self.val1) + '\\n at ' + str(self.val5)+','+str(self.val6)) self.name_ent.delete(0,END)", "= Label(Top, text = \"Shalom Clinic\", font=('arial', 15)) lbl_title.pack(fill=X) options=[\"Male\",\"Female\"]", "self.location_ent.place(x=250, y=220) self.clicked1=StringVar() self.clicked1.set(\"Select Date\") self.date_ent = OptionMenu(self.left,self.clicked1,*options1) self.date_ent.pack() self.date_ent.place(x=250,", "'' or self.val4 == '' or self.val5 == '' or", "== '' or self.val2 == '' or self.val3 == ''", "self.val8 = self.all_ent.get() self.val9 = self.chr_ent.get() self.val10 = self.clicked3.get() pattern=re.compile(\"[7-9][0-9]{9}\")", "bold'), fg='white', bg='steelblue') self.logs.place(x=0, y=0) self.box = Text(self.right, width=62, height=45)", "conn.cursor() ids = [] class Application: def __init__(self, master): self.master", "Label(self.left, text=\"Appointment Date\", font=('arial 18 bold'), fg='black', bg='sea green') self.date.place(x=0,", "self.val10=='Select Blood Group' or self.val5=='Select Date' or self.val6=='Select Time': print(\"ty\",self.val3)", "= Entry(self.left, width=30) self.chr_ent.place(x=250, y=420) self.chr_ent.insert(0, 'NONE') self.bg = Label(self.left,", "= pd.date_range(today, date2).tolist() conn = sqlite3.connect('database copy.db') c = conn.cursor()", "Label(self.left, text=\"Gender\", font=('arial 18 bold'), fg='black', bg='sea green') self.gender.place(x=0, y=180)", "self.final_id = self.new[len(ids)-1] self.logs = Label(self.right, text=\"Logs\", font=('arial 28 bold'),", "Top = Frame(root, bd=1, relief=RIDGE) Top.pack(side=TOP, fill=X) Form = Frame(root,", "self.right.pack(side=RIGHT) self.heading = Label(self.left, text=\"Appointments\", font=('arial 40 bold'), fg='black', bg='sea", "green') self.chronic.place(x=0, y=420) self.chr_ent = Entry(self.left, width=30) self.chr_ent.place(x=250, y=420) self.chr_ent.insert(0,", "options=[\"Male\",\"Female\"] options1=datesx options2=[\"10:00:00\",\"11:00:00\",\"13:00:00\"] options3=[\"O+\",\"O-\",\"A+\",\"A-\",\"B+\",\"B-\",\"AB+\",\"AB-\"] b = Application(root) root.resizable(False, False) root.mainloop()", "root = Tk() root.title(\"Shalom Clinic\") #root.geometry(\"1200x720+0+0\") root.attributes('-fullscreen', True) root.resizable(0, 0)", "import * from tkcalendar import Calendar from datetime import datetime", "y=340) self.allergies = Label(self.left, text=\"Allergies\", font=('arial 18 bold'), fg='black', bg='sea", "__init__(self, master): self.master = master self.left = Frame(master, width=1000, height=800,", "18 bold'), fg='black', bg='sea green') self.name.place(x=0, y=100) self.age = Label(self.left,", "\"Please Fill Up All Boxes\") print(self.val3) elif not(pattern1.match(self.val1)) or len(self.val1)<2:", "'' or self.val3 == '' or self.val4 == '' or", "height=2, bg='steelblue', command=self.quit) self.submit.place(x=600, y=400) sql2 = \"SELECT ID FROM", "green') self.heading.place(x=0, y=0) self.name = Label(self.left, text=\"Patient's Name\", font=('arial 18", "= self.clicked3.get() pattern=re.compile(\"[7-9][0-9]{9}\") pattern=re.compile(\"[7-9][0-9]{9}\") pattern2=re.compile(\"[1-9]([0-9])*\") pattern1=re.compile(r'([A-Z])(\\s*[A-Z])*$') pattern.match(self.val7) if self.val1 ==", "root.destroy() root = Tk() root.title(\"Shalom Clinic\") #root.geometry(\"1200x720+0+0\") root.attributes('-fullscreen', True) root.resizable(0,", "font=('arial 28 bold'), fg='white', bg='steelblue') self.logs.place(x=0, y=0) self.box = Text(self.right,", "self.phone_ent = Entry(self.left, width=30) self.phone_ent.place(x=250, y=340) self.submit = Button(self.left, text=\"Add", "* from tkcalendar import Calendar from datetime import datetime from", "self.clicked3.set(\"Select Blood Group\") self.chr_ent.delete(0,END) self.all_ent.delete(0,END) self.all_ent.insert(0, 'NONE') self.chr_ent.insert(0, 'NONE') def", "import askyesno import re import sqlite3 import tkinter.messagebox import pandas", "self.gender_ent = OptionMenu(self.left,self.clicked,*options) self.gender_ent.pack() self.gender_ent.place(x=250, y=180) self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250, y=220) self.clicked1=StringVar()", "= OptionMenu(self.left,self.clicked3,*options3) self.bg_ent.pack() self.bg_ent.place(x=250, y=460) self.name_ent = Entry(self.left, width=30) self.name_ent.place(x=250,", "pattern=re.compile(\"[7-9][0-9]{9}\") pattern2=re.compile(\"[1-9]([0-9])*\") pattern1=re.compile(r'([A-Z])(\\s*[A-Z])*$') pattern.match(self.val7) if self.val1 == '' or self.val2", "Number\") else: sql = \"INSERT INTO 'appointments' (name, age, gender,", "green') self.allergies.place(x=0, y=380) self.all_ent = Entry(self.left, width=30) self.all_ent.place(x=250, y=380) self.all_ent.insert(0,", "or len(self.val2)>=3: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Age\") elif not(pattern.match(self.val7)) or len(self.val7)>10: tkinter.messagebox.showinfo(\"Warning\", \"INVALID", "pattern=re.compile(\"[7-9][0-9]{9}\") pattern=re.compile(\"[7-9][0-9]{9}\") pattern2=re.compile(\"[1-9]([0-9])*\") pattern1=re.compile(r'([A-Z])(\\s*[A-Z])*$') pattern.match(self.val7) if self.val1 == '' or", "font=('arial 18 bold'), fg='black', bg='sea green') self.date.place(x=0, y=260) self.time =", "self.result = c.execute(sql2) for self.row in self.result: self.id = self.row[0]", "self.all_ent.delete(0,END) self.all_ent.insert(0, 'NONE') self.chr_ent.insert(0, 'NONE') def view(self): import view view.call()", "view.call() def update(self): import update update.buildupdate() def read(self): import read", "self.chr_ent.insert(0, 'NONE') def view(self): import view view.call() def update(self): import", "self.gender_ent.pack() self.gender_ent.place(x=250, y=180) self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250, y=220) self.clicked1=StringVar() self.clicked1.set(\"Select Date\") self.date_ent", "self.clicked2.get() self.val7 = self.phone_ent.get() self.val8 = self.all_ent.get() self.val9 = self.chr_ent.get()", "Entry(self.left, width=30) self.name_ent.place(x=250, y=100) self.age_ent = Entry(self.left, width=30) self.age_ent.place(x=250, y=140)", "self.date_ent.pack() self.date_ent.place(x=250, y=260) self.clicked2=StringVar() self.clicked2.set(\"Select Time\") self.time_ent = OptionMenu(self.left,self.clicked2,*options2) self.time_ent.pack()", "date2).tolist() conn = sqlite3.connect('database copy.db') c = conn.cursor() ids =", "datetime import date import tkinter as tk from tkinter import", "green') self.gender.place(x=0, y=180) self.location = Label(self.left, text=\"Location\", font=('arial 18 bold'),", "'' or self.val2 == '' or self.val3 == '' or", "tkinter.messagebox import askyesno import re import sqlite3 import tkinter.messagebox import", "self.allergies = Label(self.left, text=\"Allergies\", font=('arial 18 bold'), fg='black', bg='sea green')", "bg='steelblue', command=self.view) self.submit.place(x=600, y=100) self.submit = Button(self.left, text=\"View/Update Patient Details\",", "self.id = self.row[0] ids.append(self.id) self.new = sorted(ids) self.final_id = self.new[len(ids)-1]", "from dateutil import rrule, parser today = date.today() date1 =", "width=30) self.phone_ent.place(x=250, y=340) self.submit = Button(self.left, text=\"Add Appointment\", width=20, height=2,", "OptionMenu(self.left,self.clicked2,*options2) self.time_ent.pack() self.time_ent.place(x=250, y=300) self.phone_ent = Entry(self.left, width=30) self.phone_ent.place(x=250, y=340)", "self.phone.place(x=0, y=340) self.allergies = Label(self.left, text=\"Allergies\", font=('arial 18 bold'), fg='black',", "= date.today() date1 = '05-10-2021' date2 = '12-31-2050' datesx =", "= Label(self.left, text=\"Appointment Time\", font=('arial 18 bold'), fg='black', bg='sea green')", "Button(self.left, text=\"View Appointments\", width=20, height=2, bg='steelblue', command=self.view) self.submit.place(x=600, y=100) self.submit", "= Entry(self.left, width=30) self.age_ent.place(x=250, y=140) self.clicked=StringVar() self.clicked.set(\"Male\") self.gender_ent = OptionMenu(self.left,self.clicked,*options)", "'NONE') self.chronic = Label(self.left, text=\"Chronic Conditions\", font=('arial 18 bold'), fg='black',", "'' or self.val5 == '' or self.val6=='' or self.val7=='' or", "date2 = '12-31-2050' datesx = pd.date_range(today, date2).tolist() conn = sqlite3.connect('database", "self.bg = Label(self.left, text=\"Blood Group\", font=('arial 18 bold'), fg='black', bg='sea", "self.clicked1=StringVar() self.clicked1.set(\"Select Date\") self.date_ent = OptionMenu(self.left,self.clicked1,*options1) self.date_ent.pack() self.date_ent.place(x=250, y=260) self.clicked2=StringVar()", "y=180) self.location = Label(self.left, text=\"Location\", font=('arial 18 bold'), fg='black', bg='sea", "tkinter.messagebox.showinfo(\"Warning\", \"Please Fill Up All Boxes\") print(self.val3) elif not(pattern1.match(self.val1)) or", "Conditions\", font=('arial 18 bold'), fg='black', bg='sea green') self.chronic.place(x=0, y=420) self.chr_ent", "self.clicked.get() self.val4 = self.location_ent.get() self.val5 = self.clicked1.get() self.val6 = self.clicked2.get()", "bold'), fg='black', bg='sea green') self.bg.place(x=0, y=460) self.clicked3=StringVar() self.clicked3.set(\"Select Blood Group\")", "green') self.phone.place(x=0, y=340) self.allergies = Label(self.left, text=\"Allergies\", font=('arial 18 bold'),", "self.date_ent = OptionMenu(self.left,self.clicked1,*options1) self.date_ent.pack() self.date_ent.place(x=250, y=260) self.clicked2=StringVar() self.clicked2.set(\"Select Time\") self.time_ent", "self.chr_ent = Entry(self.left, width=30) self.chr_ent.place(x=250, y=420) self.chr_ent.insert(0, 'NONE') self.bg =", "from tkcalendar import Calendar from datetime import datetime from datetime", "28 bold'), fg='white', bg='steelblue') self.logs.place(x=0, y=0) self.box = Text(self.right, width=62,", "text=\"Chronic Conditions\", font=('arial 18 bold'), fg='black', bg='sea green') self.chronic.place(x=0, y=420)", "self.val7,self.val5,self.val8,self.val9,self.val10)) conn.commit() tkinter.messagebox.showinfo(\"Success\", \"Appointment for \" + str(self.val1) + \"", "text=\"Age\", font=('arial 18 bold'), fg='black', bg='sea green') self.age.place(x=0, y=140) self.gender", "self.left.pack(side=LEFT) self.right = Frame(master, width=1000, height=800, bg='steelblue') self.right.pack(side=RIGHT) self.heading =", "if self.val1 == '' or self.val2 == '' or self.val3", "datetime from dateutil import rrule, parser today = date.today() date1", "self.gender = Label(self.left, text=\"Gender\", font=('arial 18 bold'), fg='black', bg='sea green')", "[] class Application: def __init__(self, master): self.master = master self.left", "bg='sea green') self.time.place(x=0, y=300) self.phone = Label(self.left, text=\"Phone Number\", font=('arial", "+ '\\n at ' + str(self.val5)+','+str(self.val6)) self.name_ent.delete(0,END) self.age_ent.delete(0,END) self.location_ent.delete(0,END) self.phone_ent.delete(0,END)", "or self.val3 == '' or self.val4 == '' or self.val5", "y=300) self.phone_ent = Entry(self.left, width=30) self.phone_ent.place(x=250, y=340) self.submit = Button(self.left,", "at ' + str(self.val5)+','+str(self.val6)) self.name_ent.delete(0,END) self.age_ent.delete(0,END) self.location_ent.delete(0,END) self.phone_ent.delete(0,END) self.clicked1.set(\"Select Date\")", "self.name_ent.delete(0,END) self.age_ent.delete(0,END) self.location_ent.delete(0,END) self.phone_ent.delete(0,END) self.clicked1.set(\"Select Date\") self.clicked2.set(\"Select Time\") self.clicked3.set(\"Select Blood", "Time\", font=('arial 18 bold'), fg='black', bg='sea green') self.time.place(x=0, y=300) self.phone", "fg='white', bg='steelblue') self.logs.place(x=0, y=0) self.box = Text(self.right, width=62, height=45) self.box.place(x=20,", "been created\" ) self.box.insert(END, '\\n Appointment fixed for ' +", "Label(Top, text = \"Shalom Clinic\", font=('arial', 15)) lbl_title.pack(fill=X) options=[\"Male\",\"Female\"] options1=datesx", "Label(self.left, text=\"Allergies\", font=('arial 18 bold'), fg='black', bg='sea green') self.allergies.place(x=0, y=380)", "= OptionMenu(self.left,self.clicked,*options) self.gender_ent.pack() self.gender_ent.place(x=250, y=180) self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250, y=220) self.clicked1=StringVar() self.clicked1.set(\"Select", "self.name.place(x=0, y=100) self.age = Label(self.left, text=\"Age\", font=('arial 18 bold'), fg='black',", "import read read.buildread() def quit(self): answer = askyesno(title='Confirm Exit', message='Are", "or len(self.val7)>10: tkinter.messagebox.showinfo(\"Warning\", \"INVALID Phone Number\") else: sql = \"INSERT", "Date\", font=('arial 18 bold'), fg='black', bg='sea green') self.date.place(x=0, y=260) self.time", "class Application: def __init__(self, master): self.master = master self.left =", "Label(self.left, text=\"Location\", font=('arial 18 bold'), fg='black', bg='sea green') self.location.place(x=0, y=220)", "y=500) self.submit = Button(self.left, text=\"View Appointments\", width=20, height=2, bg='steelblue', command=self.view)", "print(self.val3) elif not(pattern1.match(self.val1)) or len(self.val1)<2: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Name\") elif not(pattern2.match(self.val2)) or", "pady=1) lbl_title = Label(Top, text = \"Shalom Clinic\", font=('arial', 15))", "Entry(self.left, width=30) self.age_ent.place(x=250, y=140) self.clicked=StringVar() self.clicked.set(\"Male\") self.gender_ent = OptionMenu(self.left,self.clicked,*options) self.gender_ent.pack()", "fg='black', bg='sea green') self.time.place(x=0, y=300) self.phone = Label(self.left, text=\"Phone Number\",", "bg='steelblue', command=self.read) self.submit.place(x=600, y=300) self.submit = Button(self.left, text=\"Exit\", width=20, height=2,", "answer: root.destroy() root = Tk() root.title(\"Shalom Clinic\") #root.geometry(\"1200x720+0+0\") root.attributes('-fullscreen', True)", "self.allergies.place(x=0, y=380) self.all_ent = Entry(self.left, width=30) self.all_ent.place(x=250, y=380) self.all_ent.insert(0, 'NONE')", "appointments\" self.result = c.execute(sql2) for self.row in self.result: self.id =", "bg='sea green') self.allergies.place(x=0, y=380) self.all_ent = Entry(self.left, width=30) self.all_ent.place(x=250, y=380)", "= self.age_ent.get() self.val3 = self.clicked.get() self.val4 = self.location_ent.get() self.val5 =", "def quit(self): answer = askyesno(title='Confirm Exit', message='Are you sure you", "for \" + str(self.val1) + \" has been created\" )", "= Label(self.left, text=\"Appointments\", font=('arial 40 bold'), fg='black', bg='sea green') self.heading.place(x=0,", "lbl_title = Label(Top, text = \"Shalom Clinic\", font=('arial', 15)) lbl_title.pack(fill=X)", "green') self.left.pack(side=LEFT) self.right = Frame(master, width=1000, height=800, bg='steelblue') self.right.pack(side=RIGHT) self.heading", "width=30) self.age_ent.place(x=250, y=140) self.clicked=StringVar() self.clicked.set(\"Male\") self.gender_ent = OptionMenu(self.left,self.clicked,*options) self.gender_ent.pack() self.gender_ent.place(x=250,", "= self.chr_ent.get() self.val10 = self.clicked3.get() pattern=re.compile(\"[7-9][0-9]{9}\") pattern=re.compile(\"[7-9][0-9]{9}\") pattern2=re.compile(\"[1-9]([0-9])*\") pattern1=re.compile(r'([A-Z])(\\s*[A-Z])*$') pattern.match(self.val7)", "+ \" has been created\" ) self.box.insert(END, '\\n Appointment fixed", "askyesno(title='Confirm Exit', message='Are you sure you want to exit?') if", "font=('arial 18 bold'), fg='black', bg='sea green') self.name.place(x=0, y=100) self.age =", "self.submit.place(x=600, y=200) self.submit = Button(self.left, text=\"Read Names\", width=20, height=2, bg='steelblue',", "y=0) self.name = Label(self.left, text=\"Patient's Name\", font=('arial 18 bold'), fg='black',", "= Frame(root, bd=1, relief=RIDGE) Top.pack(side=TOP, fill=X) Form = Frame(root, height=1)", "elif not(pattern1.match(self.val1)) or len(self.val1)<2: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Name\") elif not(pattern2.match(self.val2)) or len(self.val2)>=3:", "import pandas as pd import datetime from dateutil import rrule,", "\"INSERT INTO 'appointments' (name, age, gender, location, scheduled_time, phone,date,Allergies,Chronic_Conditions,Blood_Group) VALUES(?,", "'' or self.val6=='' or self.val7=='' or self.val10=='Select Blood Group' or", "self.all_ent = Entry(self.left, width=30) self.all_ent.place(x=250, y=380) self.all_ent.insert(0, 'NONE') self.chronic =", "= askyesno(title='Confirm Exit', message='Are you sure you want to exit?')", "width=1000, height=800, bg='steelblue') self.right.pack(side=RIGHT) self.heading = Label(self.left, text=\"Appointments\", font=('arial 40", "self.time_ent = OptionMenu(self.left,self.clicked2,*options2) self.time_ent.pack() self.time_ent.place(x=250, y=300) self.phone_ent = Entry(self.left, width=30)", "location, scheduled_time, phone,date,Allergies,Chronic_Conditions,Blood_Group) VALUES(?, ?, ?, ?, ?, ?,?,?,?,?)\" c.execute(sql,", "or self.val2 == '' or self.val3 == '' or self.val4", "text=\"Exit\", width=20, height=2, bg='steelblue', command=self.quit) self.submit.place(x=600, y=400) sql2 = \"SELECT", "height=800, bg='sea green') self.left.pack(side=LEFT) self.right = Frame(master, width=1000, height=800, bg='steelblue')", "= Label(self.left, text=\"Blood Group\", font=('arial 18 bold'), fg='black', bg='sea green')", "Calendar from datetime import datetime from datetime import date import", "self.val3 = self.clicked.get() self.val4 = self.location_ent.get() self.val5 = self.clicked1.get() self.val6", "text=\"Appointment Date\", font=('arial 18 bold'), fg='black', bg='sea green') self.date.place(x=0, y=260)", "date import tkinter as tk from tkinter import ttk from", "fg='black', bg='sea green') self.chronic.place(x=0, y=420) self.chr_ent = Entry(self.left, width=30) self.chr_ent.place(x=250,", "= self.clicked1.get() self.val6 = self.clicked2.get() self.val7 = self.phone_ent.get() self.val8 =", "def __init__(self, master): self.master = master self.left = Frame(master, width=1000,", "18 bold'), fg='black', bg='sea green') self.date.place(x=0, y=260) self.time = Label(self.left,", "width=20, height=2, bg='steelblue', command=self.update) self.submit.place(x=600, y=200) self.submit = Button(self.left, text=\"Read", "OptionMenu(self.left,self.clicked3,*options3) self.bg_ent.pack() self.bg_ent.place(x=250, y=460) self.name_ent = Entry(self.left, width=30) self.name_ent.place(x=250, y=100)", "height=45) self.box.place(x=20, y=60) def add_appointment(self): self.val1 = self.name_ent.get() self.val2 =", "Entry(self.left, width=30) self.phone_ent.place(x=250, y=340) self.submit = Button(self.left, text=\"Add Appointment\", width=20,", "Age\") elif not(pattern.match(self.val7)) or len(self.val7)>10: tkinter.messagebox.showinfo(\"Warning\", \"INVALID Phone Number\") else:", "self.chronic.place(x=0, y=420) self.chr_ent = Entry(self.left, width=30) self.chr_ent.place(x=250, y=420) self.chr_ent.insert(0, 'NONE')", "font=('arial 18 bold'), fg='black', bg='sea green') self.bg.place(x=0, y=460) self.clicked3=StringVar() self.clicked3.set(\"Select", "exit?') if answer: root.destroy() root = Tk() root.title(\"Shalom Clinic\") #root.geometry(\"1200x720+0+0\")", "today = date.today() date1 = '05-10-2021' date2 = '12-31-2050' datesx", "self.clicked=StringVar() self.clicked.set(\"Male\") self.gender_ent = OptionMenu(self.left,self.clicked,*options) self.gender_ent.pack() self.gender_ent.place(x=250, y=180) self.location_ent=Entry(self.left,width=30) self.location_ent.place(x=250,", "height=2, bg='steelblue', command=self.add_appointment) self.submit.place(x=270, y=500) self.submit = Button(self.left, text=\"View Appointments\",", "self.val4 = self.location_ent.get() self.val5 = self.clicked1.get() self.val6 = self.clicked2.get() self.val7", "width=20, height=2, bg='steelblue', command=self.quit) self.submit.place(x=600, y=400) sql2 = \"SELECT ID", "as tk from tkinter import ttk from tkinter.messagebox import askyesno", "c.execute(sql2) for self.row in self.result: self.id = self.row[0] ids.append(self.id) self.new", "read.buildread() def quit(self): answer = askyesno(title='Confirm Exit', message='Are you sure", "to exit?') if answer: root.destroy() root = Tk() root.title(\"Shalom Clinic\")", "Tk() root.title(\"Shalom Clinic\") #root.geometry(\"1200x720+0+0\") root.attributes('-fullscreen', True) root.resizable(0, 0) Top =", "bold'), fg='black', bg='sea green') self.age.place(x=0, y=140) self.gender = Label(self.left, text=\"Gender\",", "not(pattern2.match(self.val2)) or len(self.val2)>=3: tkinter.messagebox.showinfo(\"Warning\",\"INVALID Age\") elif not(pattern.match(self.val7)) or len(self.val7)>10: tkinter.messagebox.showinfo(\"Warning\",", "root.resizable(0, 0) Top = Frame(root, bd=1, relief=RIDGE) Top.pack(side=TOP, fill=X) Form", "font=('arial 18 bold'), fg='black', bg='sea green') self.gender.place(x=0, y=180) self.location =", "import date import tkinter as tk from tkinter import ttk", "from tkinter.messagebox import askyesno import re import sqlite3 import tkinter.messagebox", "self.val1 == '' or self.val2 == '' or self.val3 ==", "text=\"Blood Group\", font=('arial 18 bold'), fg='black', bg='sea green') self.bg.place(x=0, y=460)", "y=220) self.date = Label(self.left, text=\"Appointment Date\", font=('arial 18 bold'), fg='black',", "Group\") self.chr_ent.delete(0,END) self.all_ent.delete(0,END) self.all_ent.insert(0, 'NONE') self.chr_ent.insert(0, 'NONE') def view(self): import", "self.chr_ent.delete(0,END) self.all_ent.delete(0,END) self.all_ent.insert(0, 'NONE') self.chr_ent.insert(0, 'NONE') def view(self): import view", "Blood Group\") self.chr_ent.delete(0,END) self.all_ent.delete(0,END) self.all_ent.insert(0, 'NONE') self.chr_ent.insert(0, 'NONE') def view(self):", "self.time = Label(self.left, text=\"Appointment Time\", font=('arial 18 bold'), fg='black', bg='sea", "import Calendar from datetime import datetime from datetime import date", "Appointment fixed for ' + str(self.val1) + '\\n at '", "True) root.resizable(0, 0) Top = Frame(root, bd=1, relief=RIDGE) Top.pack(side=TOP, fill=X)", "Button(self.left, text=\"View/Update Patient Details\", width=20, height=2, bg='steelblue', command=self.update) self.submit.place(x=600, y=200)", "copy.db') c = conn.cursor() ids = [] class Application: def" ]
[ "is_synced=True, ), ), message=UpdateEvent(), ) request = DataUpdateRequest( machine_id=1, machine_name=\"machine", "event_type=ADD, wallet=dict( is_running=True, is_synced=True, ), ), message=UpdateEvent(), ), ] request", "= await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async def", "db_filepath = os.path.join(tmpdir, \"temp.db\") with MonitoringDatabase(db_filepath): messages = await wallets_cmd(db_filepath)", "db: update_events = [ ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=True, is_synced=True,", "os.path.join(tmpdir, \"tmp.db\") now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db: update_events", "None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir, \"temp.db\") with", "with MonitoringDatabase(db_filepath): messages = await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\"))", "from ...protobuf.generated.computer_info_pb2 import ADD, UpdateEvent from ...protobuf.generated.monitoring_service_pb2 import DataUpdateRequest from", "tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir, \"temp.db\") with MonitoringDatabase(db_filepath): messages", "@async_test async def test_no_wallets_case(self) -> None: with tempfile.TemporaryDirectory() as tmpdir:", "1) msg = messages[0] self.assertFalse(msg.startswith(\"Traceback\")) # display online harvester self.assertTrue(\"machine", "import MonitoringDatabase from ...protobuf.generated.computer_info_pb2 import ADD, UpdateEvent from ...protobuf.generated.monitoring_service_pb2 import", "-> None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir, \"temp.db\")", "\"temp.db\") now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db: event =", "message=UpdateEvent(), ) request = DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=[event],", ") request = DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=[event], )", "def test_display_running_wallet(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath =", "= messages[0] self.assertFalse(msg.startswith(\"Traceback\")) # display online harvester self.assertTrue(\"machine A\" in", "def test_no_wallets_case(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath =", "= [ ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=True, is_synced=True, ), ),", "), message=UpdateEvent(), ), ] request = DataUpdateRequest( machine_id=1, machine_name=\"machine A\",", ") db.store_data_update_request(request) messages = await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\"))", "self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async def test_display_running_wallet(self) -> None:", "db.store_data_update_request(request) messages = await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test", "tmpdir: db_filepath = os.path.join(tmpdir, \"tmp.db\") now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath)", "DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=[event], ) db.store_data_update_request(request) messages =", "MonitoringDatabase(db_filepath): messages = await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test", "is_synced=True, ), ), message=UpdateEvent(), ), ] request = DataUpdateRequest( machine_id=1,", "import async_test from .wallets import wallets_cmd class TestWalletsCmd(unittest.TestCase): @async_test async", "messages = await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async", "as tmpdir: db_filepath = os.path.join(tmpdir, \"tmp.db\") now_timestamp = datetime.now().timestamp() with", "wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async def test_not_running_wallet_not_displayed(self) ->", "machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=[event], ) db.store_data_update_request(request) messages = await", "import unittest from datetime import datetime from google.protobuf.json_format import ParseDict", "-> None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir, \"tmp.db\")", "with tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir, \"tmp.db\") now_timestamp =", "wallets_cmd class TestWalletsCmd(unittest.TestCase): @async_test async def test_no_wallets_case(self) -> None: with", "os.path.join(tmpdir, \"temp.db\") with MonitoringDatabase(db_filepath): messages = await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1)", "msg = messages[0] self.assertFalse(msg.startswith(\"Traceback\")) # display online harvester self.assertTrue(\"machine A\"", ".wallets import wallets_cmd class TestWalletsCmd(unittest.TestCase): @async_test async def test_no_wallets_case(self) ->", "DataUpdateRequest from ...utils.testing import async_test from .wallets import wallets_cmd class", "tmpdir: db_filepath = os.path.join(tmpdir, \"temp.db\") now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath)", "async def test_no_wallets_case(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath", "ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=True, is_synced=True, ), ), message=UpdateEvent(), ),", "with MonitoringDatabase(db_filepath) as db: update_events = [ ParseDict( js_dict=dict( event_type=ADD,", "google.protobuf.json_format import ParseDict from ...monitoring.MonitoringDatabase import MonitoringDatabase from ...protobuf.generated.computer_info_pb2 import", "\"temp.db\") with MonitoringDatabase(db_filepath): messages = await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No", "timestamp=now_timestamp, events=update_events, ) db.store_data_update_request(request) messages = await wallets_cmd(db_filepath) print(messages) #", "= await wallets_cmd(db_filepath) print(messages) # no failure self.assertEqual(len(messages), 1) msg", "class TestWalletsCmd(unittest.TestCase): @async_test async def test_no_wallets_case(self) -> None: with tempfile.TemporaryDirectory()", "wallet=dict( is_running=True, is_synced=True, ), ), message=UpdateEvent(), ), ] request =", "import ADD, UpdateEvent from ...protobuf.generated.monitoring_service_pb2 import DataUpdateRequest from ...utils.testing import", "messages = await wallets_cmd(db_filepath) print(messages) # no failure self.assertEqual(len(messages), 1)", "print(messages) # no failure self.assertEqual(len(messages), 1) msg = messages[0] self.assertFalse(msg.startswith(\"Traceback\"))", "= datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db: update_events = [ ParseDict(", "= os.path.join(tmpdir, \"temp.db\") now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db:", "ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=False, is_synced=True, ), ), message=UpdateEvent(), )", "os.path.join(tmpdir, \"temp.db\") now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db: event", "[ ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=True, is_synced=True, ), ), message=UpdateEvent(),", "event = ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=False, is_synced=True, ), ),", "from ...protobuf.generated.monitoring_service_pb2 import DataUpdateRequest from ...utils.testing import async_test from .wallets", "), message=UpdateEvent(), ) request = DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp,", "await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async def test_not_running_wallet_not_displayed(self)", "wallets\")) @async_test async def test_not_running_wallet_not_displayed(self) -> None: with tempfile.TemporaryDirectory() as", "update_events = [ ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=True, is_synced=True, ),", "...protobuf.generated.computer_info_pb2 import ADD, UpdateEvent from ...protobuf.generated.monitoring_service_pb2 import DataUpdateRequest from ...utils.testing", "async def test_display_running_wallet(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath", "import tempfile import unittest from datetime import datetime from google.protobuf.json_format", "wallets\")) @async_test async def test_display_running_wallet(self) -> None: with tempfile.TemporaryDirectory() as", "as db: event = ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=False, is_synced=True,", "), ), message=UpdateEvent(), ) request = DataUpdateRequest( machine_id=1, machine_name=\"machine A\",", "machine_name=\"machine A\", timestamp=now_timestamp, events=[event], ) db.store_data_update_request(request) messages = await wallets_cmd(db_filepath)", "test_not_running_wallet_not_displayed(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir,", ") db.store_data_update_request(request) messages = await wallets_cmd(db_filepath) print(messages) # no failure", "js_dict=dict( event_type=ADD, wallet=dict( is_running=False, is_synced=True, ), ), message=UpdateEvent(), ) request", "self.assertFalse(msg.startswith(\"Traceback\")) # display online harvester self.assertTrue(\"machine A\" in msg) self.assertIn(\"synchronized\",", "A\", timestamp=now_timestamp, events=[event], ) db.store_data_update_request(request) messages = await wallets_cmd(db_filepath) self.assertEqual(len(messages),", "# display online harvester self.assertTrue(\"machine A\" in msg) self.assertIn(\"synchronized\", msg)", "None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir, \"temp.db\") now_timestamp", "await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async def test_display_running_wallet(self)", "), ] request = DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=update_events,", "from .wallets import wallets_cmd class TestWalletsCmd(unittest.TestCase): @async_test async def test_no_wallets_case(self)", "unittest from datetime import datetime from google.protobuf.json_format import ParseDict from", "failure self.assertEqual(len(messages), 1) msg = messages[0] self.assertFalse(msg.startswith(\"Traceback\")) # display online", "MonitoringDatabase(db_filepath) as db: event = ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=False,", "with tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir, \"temp.db\") now_timestamp =", "async_test from .wallets import wallets_cmd class TestWalletsCmd(unittest.TestCase): @async_test async def", "now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db: update_events = [", "as db: update_events = [ ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=True,", "= ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=False, is_synced=True, ), ), message=UpdateEvent(),", "= DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=update_events, ) db.store_data_update_request(request) messages", "no failure self.assertEqual(len(messages), 1) msg = messages[0] self.assertFalse(msg.startswith(\"Traceback\")) # display", "message=UpdateEvent(), ), ] request = DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp,", "await wallets_cmd(db_filepath) print(messages) # no failure self.assertEqual(len(messages), 1) msg =", "...utils.testing import async_test from .wallets import wallets_cmd class TestWalletsCmd(unittest.TestCase): @async_test", "datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db: event = ParseDict( js_dict=dict( event_type=ADD,", "as tmpdir: db_filepath = os.path.join(tmpdir, \"temp.db\") with MonitoringDatabase(db_filepath): messages =", "tmpdir: db_filepath = os.path.join(tmpdir, \"temp.db\") with MonitoringDatabase(db_filepath): messages = await", "request = DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=update_events, ) db.store_data_update_request(request)", "messages[0] self.assertFalse(msg.startswith(\"Traceback\")) # display online harvester self.assertTrue(\"machine A\" in msg)", "db.store_data_update_request(request) messages = await wallets_cmd(db_filepath) print(messages) # no failure self.assertEqual(len(messages),", "test_display_running_wallet(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir,", "is_running=True, is_synced=True, ), ), message=UpdateEvent(), ), ] request = DataUpdateRequest(", "import os import tempfile import unittest from datetime import datetime", "= os.path.join(tmpdir, \"temp.db\") with MonitoringDatabase(db_filepath): messages = await wallets_cmd(db_filepath) self.assertEqual(len(messages),", "db_filepath = os.path.join(tmpdir, \"temp.db\") now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath) as", "ParseDict from ...monitoring.MonitoringDatabase import MonitoringDatabase from ...protobuf.generated.computer_info_pb2 import ADD, UpdateEvent", "MonitoringDatabase from ...protobuf.generated.computer_info_pb2 import ADD, UpdateEvent from ...protobuf.generated.monitoring_service_pb2 import DataUpdateRequest", "events=[event], ) db.store_data_update_request(request) messages = await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No", "timestamp=now_timestamp, events=[event], ) db.store_data_update_request(request) messages = await wallets_cmd(db_filepath) self.assertEqual(len(messages), 1)", "as tmpdir: db_filepath = os.path.join(tmpdir, \"temp.db\") now_timestamp = datetime.now().timestamp() with", "datetime import datetime from google.protobuf.json_format import ParseDict from ...monitoring.MonitoringDatabase import", "db: event = ParseDict( js_dict=dict( event_type=ADD, wallet=dict( is_running=False, is_synced=True, ),", "import wallets_cmd class TestWalletsCmd(unittest.TestCase): @async_test async def test_no_wallets_case(self) -> None:", "self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async def test_display_running_wallet(self) -> None: with tempfile.TemporaryDirectory()", "import datetime from google.protobuf.json_format import ParseDict from ...monitoring.MonitoringDatabase import MonitoringDatabase", "now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db: event = ParseDict(", "= datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db: event = ParseDict( js_dict=dict(", "TestWalletsCmd(unittest.TestCase): @async_test async def test_no_wallets_case(self) -> None: with tempfile.TemporaryDirectory() as", "= os.path.join(tmpdir, \"tmp.db\") now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db:", "tempfile import unittest from datetime import datetime from google.protobuf.json_format import", "DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=update_events, ) db.store_data_update_request(request) messages =", "1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async def test_display_running_wallet(self) -> None: with", "is_running=False, is_synced=True, ), ), message=UpdateEvent(), ) request = DataUpdateRequest( machine_id=1,", "datetime from google.protobuf.json_format import ParseDict from ...monitoring.MonitoringDatabase import MonitoringDatabase from", "from datetime import datetime from google.protobuf.json_format import ParseDict from ...monitoring.MonitoringDatabase", "\"tmp.db\") now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db: update_events =", "] request = DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=update_events, )", "= DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=[event], ) db.store_data_update_request(request) messages", "event_type=ADD, wallet=dict( is_running=False, is_synced=True, ), ), message=UpdateEvent(), ) request =", "MonitoringDatabase(db_filepath) as db: update_events = [ ParseDict( js_dict=dict( event_type=ADD, wallet=dict(", "from google.protobuf.json_format import ParseDict from ...monitoring.MonitoringDatabase import MonitoringDatabase from ...protobuf.generated.computer_info_pb2", "with MonitoringDatabase(db_filepath) as db: event = ParseDict( js_dict=dict( event_type=ADD, wallet=dict(", "from ...monitoring.MonitoringDatabase import MonitoringDatabase from ...protobuf.generated.computer_info_pb2 import ADD, UpdateEvent from", "A\", timestamp=now_timestamp, events=update_events, ) db.store_data_update_request(request) messages = await wallets_cmd(db_filepath) print(messages)", "events=update_events, ) db.store_data_update_request(request) messages = await wallets_cmd(db_filepath) print(messages) # no", "1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async def test_not_running_wallet_not_displayed(self) -> None: with", "machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=update_events, ) db.store_data_update_request(request) messages = await", "tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir, \"tmp.db\") now_timestamp = datetime.now().timestamp()", "@async_test async def test_not_running_wallet_not_displayed(self) -> None: with tempfile.TemporaryDirectory() as tmpdir:", "machine_name=\"machine A\", timestamp=now_timestamp, events=update_events, ) db.store_data_update_request(request) messages = await wallets_cmd(db_filepath)", "wallets_cmd(db_filepath) print(messages) # no failure self.assertEqual(len(messages), 1) msg = messages[0]", "async def test_not_running_wallet_not_displayed(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath", "), ), message=UpdateEvent(), ), ] request = DataUpdateRequest( machine_id=1, machine_name=\"machine", "...monitoring.MonitoringDatabase import MonitoringDatabase from ...protobuf.generated.computer_info_pb2 import ADD, UpdateEvent from ...protobuf.generated.monitoring_service_pb2", "<gh_stars>1-10 import os import tempfile import unittest from datetime import", "UpdateEvent from ...protobuf.generated.monitoring_service_pb2 import DataUpdateRequest from ...utils.testing import async_test from", "from ...utils.testing import async_test from .wallets import wallets_cmd class TestWalletsCmd(unittest.TestCase):", "os import tempfile import unittest from datetime import datetime from", "wallet=dict( is_running=False, is_synced=True, ), ), message=UpdateEvent(), ) request = DataUpdateRequest(", "def test_not_running_wallet_not_displayed(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath =", "None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir, \"tmp.db\") now_timestamp", "js_dict=dict( event_type=ADD, wallet=dict( is_running=True, is_synced=True, ), ), message=UpdateEvent(), ), ]", "# no failure self.assertEqual(len(messages), 1) msg = messages[0] self.assertFalse(msg.startswith(\"Traceback\")) #", "wallets_cmd(db_filepath) self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async def test_display_running_wallet(self) ->", "test_no_wallets_case(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir,", "db_filepath = os.path.join(tmpdir, \"tmp.db\") now_timestamp = datetime.now().timestamp() with MonitoringDatabase(db_filepath) as", "ADD, UpdateEvent from ...protobuf.generated.monitoring_service_pb2 import DataUpdateRequest from ...utils.testing import async_test", "import ParseDict from ...monitoring.MonitoringDatabase import MonitoringDatabase from ...protobuf.generated.computer_info_pb2 import ADD,", "import DataUpdateRequest from ...utils.testing import async_test from .wallets import wallets_cmd", "datetime.now().timestamp() with MonitoringDatabase(db_filepath) as db: update_events = [ ParseDict( js_dict=dict(", "self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async def test_not_running_wallet_not_displayed(self) -> None: with tempfile.TemporaryDirectory()", "request = DataUpdateRequest( machine_id=1, machine_name=\"machine A\", timestamp=now_timestamp, events=[event], ) db.store_data_update_request(request)", "...protobuf.generated.monitoring_service_pb2 import DataUpdateRequest from ...utils.testing import async_test from .wallets import", "tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir, \"temp.db\") now_timestamp = datetime.now().timestamp()", "self.assertEqual(len(messages), 1) msg = messages[0] self.assertFalse(msg.startswith(\"Traceback\")) # display online harvester", "with tempfile.TemporaryDirectory() as tmpdir: db_filepath = os.path.join(tmpdir, \"temp.db\") with MonitoringDatabase(db_filepath):", "self.assertEqual(len(messages), 1) self.assertTrue(messages[0].startswith(\"No wallets\")) @async_test async def test_not_running_wallet_not_displayed(self) -> None:", "@async_test async def test_display_running_wallet(self) -> None: with tempfile.TemporaryDirectory() as tmpdir:" ]
[ "by (2*maxR) has best rendered visualisation results amesh.scale(1/(2*maxR)) open3d.io.write_triangle_mesh(out_file_name, amesh)", "2020. <NAME>, <EMAIL> import os, open3d, numpy as np File_", "File_ = open('ModelNet_flist_short.txt', 'w') if __name__ == \"__main__\": root_dir =", "for root, dirs, files in os.walk(root_dir, topdown=False): for file in", "in file: amesh = open3d.io.read_triangle_mesh(os.path.join(root, file)) out_file_name = os.path.join(root, file).replace('.ply',", "= amesh.get_center() amesh.translate(-center) maxR = (np.asarray(amesh.vertices)**2).sum(axis=1).max()**(1/2) # we found divided", "(np.asarray(amesh.vertices)**2).sum(axis=1).max()**(1/2) # we found divided by (2*maxR) has best rendered", "'.ply' in file: amesh = open3d.io.read_triangle_mesh(os.path.join(root, file)) out_file_name = os.path.join(root,", "for file in files: if '.ply' in file: amesh =", "'_normalised.obj') center = amesh.get_center() amesh.translate(-center) maxR = (np.asarray(amesh.vertices)**2).sum(axis=1).max()**(1/2) # we", "file in files: if '.ply' in file: amesh = open3d.io.read_triangle_mesh(os.path.join(root,", "out_file_name = os.path.join(root, file).replace('.ply', '_normalised.obj') center = amesh.get_center() amesh.translate(-center) maxR", "results amesh.scale(1/(2*maxR)) open3d.io.write_triangle_mesh(out_file_name, amesh) File_.writelines(out_file_name.replace('.obj', '').replace(root_dir, '') + '\\n') print(out_file_name)", "numpy as np File_ = open('ModelNet_flist_short.txt', 'w') if __name__ ==", "= open('ModelNet_flist_short.txt', 'w') if __name__ == \"__main__\": root_dir = \"../data/ModelNet_subset/\"", "(c) 2020. <NAME>, <EMAIL> import os, open3d, numpy as np", "'w') if __name__ == \"__main__\": root_dir = \"../data/ModelNet_subset/\" for root,", "if __name__ == \"__main__\": root_dir = \"../data/ModelNet_subset/\" for root, dirs,", "= os.path.join(root, file).replace('.ply', '_normalised.obj') center = amesh.get_center() amesh.translate(-center) maxR =", "has best rendered visualisation results amesh.scale(1/(2*maxR)) open3d.io.write_triangle_mesh(out_file_name, amesh) File_.writelines(out_file_name.replace('.obj', '').replace(root_dir,", "files: if '.ply' in file: amesh = open3d.io.read_triangle_mesh(os.path.join(root, file)) out_file_name", "in os.walk(root_dir, topdown=False): for file in files: if '.ply' in", "= (np.asarray(amesh.vertices)**2).sum(axis=1).max()**(1/2) # we found divided by (2*maxR) has best", "we found divided by (2*maxR) has best rendered visualisation results", "os.walk(root_dir, topdown=False): for file in files: if '.ply' in file:", "Copyright (c) 2020. <NAME>, <EMAIL> import os, open3d, numpy as", "amesh.translate(-center) maxR = (np.asarray(amesh.vertices)**2).sum(axis=1).max()**(1/2) # we found divided by (2*maxR)", "\"__main__\": root_dir = \"../data/ModelNet_subset/\" for root, dirs, files in os.walk(root_dir,", "== \"__main__\": root_dir = \"../data/ModelNet_subset/\" for root, dirs, files in", "np File_ = open('ModelNet_flist_short.txt', 'w') if __name__ == \"__main__\": root_dir", "files in os.walk(root_dir, topdown=False): for file in files: if '.ply'", "file: amesh = open3d.io.read_triangle_mesh(os.path.join(root, file)) out_file_name = os.path.join(root, file).replace('.ply', '_normalised.obj')", "in files: if '.ply' in file: amesh = open3d.io.read_triangle_mesh(os.path.join(root, file))", "rendered visualisation results amesh.scale(1/(2*maxR)) open3d.io.write_triangle_mesh(out_file_name, amesh) File_.writelines(out_file_name.replace('.obj', '').replace(root_dir, '') +", "__name__ == \"__main__\": root_dir = \"../data/ModelNet_subset/\" for root, dirs, files", "os, open3d, numpy as np File_ = open('ModelNet_flist_short.txt', 'w') if", "open3d.io.read_triangle_mesh(os.path.join(root, file)) out_file_name = os.path.join(root, file).replace('.ply', '_normalised.obj') center = amesh.get_center()", "topdown=False): for file in files: if '.ply' in file: amesh", "# we found divided by (2*maxR) has best rendered visualisation", "best rendered visualisation results amesh.scale(1/(2*maxR)) open3d.io.write_triangle_mesh(out_file_name, amesh) File_.writelines(out_file_name.replace('.obj', '').replace(root_dir, '')", "<NAME>, <EMAIL> import os, open3d, numpy as np File_ =", "\"../data/ModelNet_subset/\" for root, dirs, files in os.walk(root_dir, topdown=False): for file", "open3d, numpy as np File_ = open('ModelNet_flist_short.txt', 'w') if __name__", "file)) out_file_name = os.path.join(root, file).replace('.ply', '_normalised.obj') center = amesh.get_center() amesh.translate(-center)", "maxR = (np.asarray(amesh.vertices)**2).sum(axis=1).max()**(1/2) # we found divided by (2*maxR) has", "root_dir = \"../data/ModelNet_subset/\" for root, dirs, files in os.walk(root_dir, topdown=False):", "amesh = open3d.io.read_triangle_mesh(os.path.join(root, file)) out_file_name = os.path.join(root, file).replace('.ply', '_normalised.obj') center", "if '.ply' in file: amesh = open3d.io.read_triangle_mesh(os.path.join(root, file)) out_file_name =", "= open3d.io.read_triangle_mesh(os.path.join(root, file)) out_file_name = os.path.join(root, file).replace('.ply', '_normalised.obj') center =", "visualisation results amesh.scale(1/(2*maxR)) open3d.io.write_triangle_mesh(out_file_name, amesh) File_.writelines(out_file_name.replace('.obj', '').replace(root_dir, '') + '\\n')", "open('ModelNet_flist_short.txt', 'w') if __name__ == \"__main__\": root_dir = \"../data/ModelNet_subset/\" for", "dirs, files in os.walk(root_dir, topdown=False): for file in files: if", "found divided by (2*maxR) has best rendered visualisation results amesh.scale(1/(2*maxR))", "<reponame>sun-pyo/OcCo<gh_stars>100-1000 # Copyright (c) 2020. <NAME>, <EMAIL> import os, open3d,", "as np File_ = open('ModelNet_flist_short.txt', 'w') if __name__ == \"__main__\":", "center = amesh.get_center() amesh.translate(-center) maxR = (np.asarray(amesh.vertices)**2).sum(axis=1).max()**(1/2) # we found", "import os, open3d, numpy as np File_ = open('ModelNet_flist_short.txt', 'w')", "# Copyright (c) 2020. <NAME>, <EMAIL> import os, open3d, numpy", "root, dirs, files in os.walk(root_dir, topdown=False): for file in files:", "file).replace('.ply', '_normalised.obj') center = amesh.get_center() amesh.translate(-center) maxR = (np.asarray(amesh.vertices)**2).sum(axis=1).max()**(1/2) #", "divided by (2*maxR) has best rendered visualisation results amesh.scale(1/(2*maxR)) open3d.io.write_triangle_mesh(out_file_name,", "amesh.get_center() amesh.translate(-center) maxR = (np.asarray(amesh.vertices)**2).sum(axis=1).max()**(1/2) # we found divided by", "(2*maxR) has best rendered visualisation results amesh.scale(1/(2*maxR)) open3d.io.write_triangle_mesh(out_file_name, amesh) File_.writelines(out_file_name.replace('.obj',", "= \"../data/ModelNet_subset/\" for root, dirs, files in os.walk(root_dir, topdown=False): for", "<EMAIL> import os, open3d, numpy as np File_ = open('ModelNet_flist_short.txt',", "os.path.join(root, file).replace('.ply', '_normalised.obj') center = amesh.get_center() amesh.translate(-center) maxR = (np.asarray(amesh.vertices)**2).sum(axis=1).max()**(1/2)" ]
[ "in dict format. \"\"\" chg_comp = self.fully_charged_entry.composition dischg_comp = self.fully_discharged_entry.composition", "> 0 else None def get_sub_electrodes(self, adjacent_only=True, include_myself=True): \"\"\" If", "= set() for entry in entries: elements.update(entry.composition.elements) #Set an artificial", "pair.entry_charge if adjacent_only \\ else pair[0].entry_charge entry_discharge = pair.entry_discharge if", "1], working_ion_entry) for i in range(len(self._stable_entries) - 1)]) @property def", "self._mass_charge @property def mass_discharge(self): return self._mass_discharge @property def vol_charge(self): return", "Returns: A list of InsertionElectrode objects \"\"\" battery_list = []", "\" \"one of the entries\") #check that the entries do", "{}\" .format(self.mass_charge, self.mass_discharge), \"vol_charge = {}, vol_discharge = {}\" .format(self.vol_charge,", "el in comp_charge if el.symbol != ion_sym}) frame_discharge_comp = Composition({el:", "= {}\" .format(self.vol_charge, self.vol_discharge), \"frac_charge = {}, frac_discharge = {}\"", "#unstable entries ordered by amount of Li asc self._unstable_entries =", "- (comp_charge[working_element] / norm_charge) self._voltage = \\ (((entry_charge.energy / norm_charge)", "electrodes returned will have multiple voltage steps if this is", "used to define an insertion battery electrode. \"\"\" def __init__(self,", "return list_copy if charge_to_discharge else list_copy.reverse() def get_unstable_entries(self, charge_to_discharge=True): \"\"\"", "Generate a summary dict. Args: print_subelectrodes: Also print data on", "unstable_entries = filter(in_range, self.get_unstable_entries()) stable_entries = filter(in_range, self.get_stable_entries()) all_entries =", "contain the same amount of the workin #element if comp_charge.get_atomic_fraction(working_element)", "max_voltage: The maximum allowable voltage allowable for a given step", "voltage for a given step max_voltage: The maximum allowable voltage", "pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge)", "\"s\").to(\"h\") * N_A * 1000 * working_ion_valence #Step 4: add", "0: raise ValueError(\"VoltagePair: The working ion must be present in", "= \\ (comp_discharge[working_element] / norm_discharge) \\ - (comp_charge[working_element] / norm_charge)", "their energy #to be very high elements = set() for", "__status__ = \"Beta\" import itertools from pymatgen.core.composition import Composition from", "Copyright (c) Pymatgen Development Team. # Distributed under the terms", "chemical potential along path. Args: min_voltage: The minimum allowable voltage.", "if not comp_charge.get_atomic_fraction(working_element) > 0 and \\ not comp_discharge.get_atomic_fraction(working_element) >", "2012, The Materials Project\" __version__ = \"0.1\" __maintainer__ = \"<NAME>\"", "True. include_myself: Include this identical electrode in the list of", "> 0 else None def get_max_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Maximum", "do not contain the same amount of the workin #element", "entries are stable vs. unstable pd = PhaseDiagram(pdentries) lifrac =", "tuple(sorted([e for e in pd.stable_entries if e in entries], key=lifrac))", "the insertion path (a subset of the path can be", "not None: data.append(pair.muO2_charge) return min(data) if len(data) > 0 else", "to make phase diagram: determine elements and set their energy", "data.append(pair.decomp_e_discharge) return min(data) if len(data) > 0 else None def", "norm_discharge self._num_ions_transferred = \\ (comp_discharge[working_element] / norm_discharge) \\ - (comp_charge[working_element]", "on all the possible subelectrodes. Returns: A summary of this", "Minimum critical oxygen chemical potential along path. Args: min_voltage: The", "return self._frac_charge @property def frac_discharge(self): return self._frac_discharge @property def voltage(self):", "all compounds along the insertion path (a subset of the", "@property def vol_charge(self): return self._vol_charge @property def vol_discharge(self): return self._vol_discharge", "e.g. TiO2 and LiTiO2. working_ion_entry: A single ComputedEntry or PDEntry", "Args: print_subelectrodes: Also print data on all the possible subelectrodes.", "norm_charge) self._voltage = \\ (((entry_charge.energy / norm_charge) - (entry_discharge.energy /", "Get the stable entries. Args: charge_to_discharge: order from most charge", "the battery, e.g. Li. \"\"\" def __init__(self, entry1, entry2, working_ion_entry):", "dec.process_decoded(d[\"working_ion_entry\"])) def as_dict(self): return {\"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"entries\": [entry.as_dict()", "charge_to_discharge else list_copy.reverse() def get_unstable_entries(self, charge_to_discharge=True): \"\"\" Returns the unstable", "pair.decomp_e_discharge is not None: data.append(pair.decomp_e_discharge) return max(data) if len(data) >", "return self._vol_charge @property def vol_discharge(self): return self._vol_discharge @property def working_ion_entry(self):", "\"\\n\".join(output) @classmethod def from_dict(cls, d): from monty.json import MontyDecoder dec", "determine elements and set their energy #to be very high", "as an Element object \"\"\" return self._working_ion @property def working_ion_entry(self):", "working_ion_valence = max(valence_list) (self.framework, norm_charge) = frame_charge_comp.get_reduced_composition_and_factor() norm_discharge = \\", "self._voltage = \\ (((entry_charge.energy / norm_charge) - (entry_discharge.energy / norm_discharge))", "if print_subelectrodes: f_dict = lambda c: c.as_dict_summary(print_subelectrodes=False) d[\"adj_pairs\"] = map(f_dict,", "least one of the entries contains the working element if", "the battery, e.g. Li. \"\"\" self._entries = entries self._working_ion =", "output.append(\"Avg. volt. = {} V\".format(self.get_average_voltage())) output.append(\"Grav. cap. = {} mAh/g\".format(self.get_capacity_grav()))", "@property def fully_charged_entry(self): \"\"\" The most charged entry along the", "working_ion_entry #Initialize normalized properties self._vol_charge = entry_charge.structure.volume / norm_charge self._vol_discharge", "= self.fully_discharged_entry.composition.reduced_formula output.append(\"InsertionElectrode with endpoints at {} and {}\".format( chg_form,", "if charge_to_discharge else all_entries.reverse() @property def fully_charged_entry(self): \"\"\" The most", "\"\"\" chg_comp = self.fully_charged_entry.composition dischg_comp = self.fully_discharged_entry.composition ion = self.working_ion", "pair.entry_discharge if adjacent_only \\ else pair[1].entry_discharge chg_frac = entry_charge.composition.get_atomic_fraction(ion) dischg_frac", "artificial energy for each element for convex hull generation element_energy", "self.max_voltage, \"min_voltage\": self.min_voltage, \"max_delta_volume\": self.max_delta_volume, \"max_voltage_step\": self.max_voltage_step, \"capacity_grav\": self.get_capacity_grav(), \"capacity_vol\":", "This module is used for analysis of materials with potential", "(a subset of the path can be chosen by the", "@property def voltage(self): return self._voltage @property def mAh(self): return self._mAh", "diagram to determine which entries are stable vs. unstable pd", "self.working_ion_entry)) return battery_list def as_dict_summary(self, print_subelectrodes=True): \"\"\" Generate a summary", "for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.pair.muO2_discharge is not None:", "allowable voltage allowable for a given step Returns: Minimum critical", "self.__class__.__name__, \"entries\": [entry.as_dict() for entry in self._entries], \"working_ion_entry\": self.working_ion_entry.as_dict()} class", "= Element(ion_sym).oxidation_states working_ion_valence = max(valence_list) (self.framework, norm_charge) = frame_charge_comp.get_reduced_composition_and_factor() norm_discharge", "/ norm_discharge)) / \\ self._num_ions_transferred + working_ion_entry.energy_per_atom) / working_ion_valence self._mAh", "if el.symbol != ion_sym}) #Data validation #check that the ion", "in entries], key=lifrac)) #unstable entries ordered by amount of Li", "sorted([e for e in all_entries], key=fsrt) return all_entries if charge_to_discharge", "len(data) > 0 else None def get_max_muO2(self, min_voltage=None, max_voltage=None): \"\"\"", "and LiTiO2, that can be used to define an insertion", "voltage step. working_ion_entry: A single ComputedEntry or PDEntry representing the", "an insertion battery electrode. \"\"\" def __init__(self, entries, working_ion_entry): \"\"\"", "from pymatgen.core.composition import Composition from pymatgen.core.units import Charge, Time from", "across the battery, e.g. Li. \"\"\" def __init__(self, entry1, entry2,", "PDEntry representing the element that carries charge across the battery,", "are adjacent on the convex hull, i.e. no electrodes returned", "License. from __future__ import division, unicode_literals \"\"\" This module is", "lifrac = lambda e: e.composition.get_atomic_fraction(self._working_ion) #stable entries ordered by amount", "None: data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is not None: data.append(pair.decomp_e_discharge) return min(data)", "filter(in_range, self.get_unstable_entries()) stable_entries = filter(in_range, self.get_stable_entries()) all_entries = list(stable_entries) all_entries.extend(unstable_entries)", "the entries do not contain the same amount of the", "of results. Returns: A list of InsertionElectrode objects \"\"\" battery_list", "this electrode\"s properties in dict format. \"\"\" chg_comp = self.fully_charged_entry.composition", "\" \"cannot be the same in both the entries\") #check", "self.muO2_charge = entry_charge.data.get(\"muO2\", None) self.muO2_discharge = entry_discharge.data.get(\"muO2\", None) self.entry_charge =", "critical oxygen chemical potential along path. Args: min_voltage: The minimum", "working ion {}\" .format(self._working_ion_entry.composition.reduced_formula), \"V = {}, mAh = {}\".format(self.voltage,", "* \\ Time(1, \"s\").to(\"h\") * N_A * 1000 * working_ion_valence", "\"energy_vol\": self.get_energy_density(), \"working_ion\": self._working_ion.symbol, \"nsteps\": self.num_steps, \"framework\": self._vpairs[0].framework.to_data_dict, \"formula_charge\": chg_comp.reduced_formula,", "#Set an artificial energy for each element for convex hull", "e in all_entries], key=fsrt) return all_entries if charge_to_discharge else all_entries.reverse()", "pymatgen.phasediagram.maker import PhaseDiagram from pymatgen.phasediagram.entries import PDEntry from pymatgen.apps.battery.battery_abc import", "__maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __date__ = \"Jan 13,", "None def get_max_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Maximum critical oxygen chemical", "not frame_charge_comp.reduced_formula == \\ frame_discharge_comp.reduced_formula: raise ValueError(\"VoltagePair: the specified entries", "entries. Args: charge_to_discharge: order from most charge to most discharged", "not comp_charge.get_atomic_fraction(working_element) > 0 and \\ not comp_discharge.get_atomic_fraction(working_element) > 0:", "= entry_charge self.entry_discharge = entry_discharge self.normalization_charge = norm_charge self.normalization_discharge =", "list(stable_entries) all_entries.extend(unstable_entries) battery_list.append(self.__class__(all_entries, self.working_ion_entry)) return battery_list def as_dict_summary(self, print_subelectrodes=True): \"\"\"", "in entries], key=lifrac)) #create voltage pairs self._vpairs = tuple([InsertionVoltagePair(self._stable_entries[i], self._stable_entries[i", "if charge_to_discharge else list_copy.reverse() def get_unstable_entries(self, charge_to_discharge=True): \"\"\" Returns the", "most discharged state? Defaults to True. Returns: A list of", "normalized properties self._vol_charge = entry_charge.structure.volume / norm_charge self._vol_discharge = entry_discharge.structure.volume", "maximum allowable voltage allowable for a given step Returns: Minimum", "(optional) hull and muO2 data self.decomp_e_charge = \\ entry_charge.data.get(\"decomposition_energy\", None)", "comp_charge.weight / norm_charge self._mass_discharge = comp_discharge.weight / norm_discharge self._num_ions_transferred =", "Only return electrodes from compounds that are adjacent on the", "for a given step max_voltage: The maximum allowable voltage allowable", "working_ion(self): \"\"\" The working ion as an Element object \"\"\"", "def __init__(self, entry1, entry2, working_ion_entry): #initialize some internal variables working_element", "same compositional framework\") #Initialize normalization factors, charged and discharged entries", "some options Args: adjacent_only: Only return electrodes from compounds that", "\"\"\" A set of topotactically related compounds, with different amounts", "self._vpairs = tuple([InsertionVoltagePair(self._stable_entries[i], self._stable_entries[i + 1], working_ion_entry) for i in", "Args: entries: A list of ComputedStructureEntries (or subclasses) representing the", "# Distributed under the terms of the MIT License. from", "entry in entries: elements.update(entry.composition.elements) #Set an artificial energy for each", "self.get_energy_density(), \"working_ion\": self._working_ion.symbol, \"nsteps\": self.num_steps, \"framework\": self._vpairs[0].framework.to_data_dict, \"formula_charge\": chg_comp.reduced_formula, \"formula_discharge\":", "self.fully_discharged_entry.composition ion = self.working_ion d = {\"average_voltage\": self.get_average_voltage(), \"max_voltage\": self.max_voltage,", "pdentries.extend([PDEntry(Composition({el:1}), element_energy) for el in elements]) #Make phase diagram to", "#initialize some internal variables working_element = working_ion_entry.composition.elements[0] entry_charge = entry1", "max_voltage: The maximum allowable voltage. Returns: Minimum decomposition energy of", ".format(self._working_ion_entry.composition.reduced_formula), \"V = {}, mAh = {}\".format(self.voltage, self.mAh), \"mass_charge =", "self.normalization_charge = norm_charge self.normalization_discharge = norm_discharge self._frac_charge = comp_charge.get_atomic_fraction(working_element) self._frac_discharge", "#check that at least one of the entries contains the", "== \\ frame_discharge_comp.reduced_formula: raise ValueError(\"VoltagePair: the specified entries must have", "by the optional arguments). \"\"\" data = [] for pair", "across the battery, e.g. Li. \"\"\" self._entries = entries self._working_ion", "new InsertionElectrode. Args: entries: A list of ComputedStructureEntries (or subclasses)", "list of results. Returns: A list of InsertionElectrode objects \"\"\"", "self._num_ions_transferred = \\ (comp_discharge[working_element] / norm_discharge) \\ - (comp_charge[working_element] /", "might contain three subelectrodes: [LiTiO2 --> TiO2, LiTiO2 --> Li0.5TiO2,", "entry_charge) comp_charge = entry_charge.composition comp_discharge = entry_discharge.composition ion_sym = working_element.symbol", "both the entries\") #check that the frameworks of the entries", "= {}\" .format(self.mass_charge, self.mass_discharge), \"vol_charge = {}, vol_discharge = {}\"", "return all_entries if charge_to_discharge else all_entries.reverse() @property def fully_charged_entry(self): \"\"\"", "of the entries in the voltage step. entry2: Entry corresponding", "the battery, e.g. TiO2 and LiTiO2. working_ion_entry: A single ComputedEntry", "= lambda e: e.composition.get_atomic_fraction(self.working_ion) all_entries = sorted([e for e in", "tuple(sorted([e for e in pd.unstable_entries if e in entries], key=lifrac))", "entries are equivalent if not frame_charge_comp.reduced_formula == \\ frame_discharge_comp.reduced_formula: raise", "= entries self._working_ion = working_ion_entry.composition.elements[0] self._working_ion_entry = working_ion_entry #Prepare to", "# coding: utf-8 # Copyright (c) Pymatgen Development Team. #", "be used to define an insertion battery electrode. \"\"\" def", "mAh(self): return self._mAh @property def mass_charge(self): return self._mass_charge @property def", "entry_discharge != self.fully_discharged_entry: unstable_entries = filter(in_range, self.get_unstable_entries()) stable_entries = filter(in_range,", "voltage. Returns: Minimum decomposition energy of all compounds along the", "\\ frame_discharge_comp.get_reduced_composition_and_factor()[1] self._working_ion_entry = working_ion_entry #Initialize normalized properties self._vol_charge =", "entry_discharge.composition.get_atomic_fraction(ion) def in_range(entry): frac = entry.composition.get_atomic_fraction(ion) return chg_frac <= frac", "= self.fully_discharged_entry.composition ion = self.working_ion d = {\"average_voltage\": self.get_average_voltage(), \"max_voltage\":", "pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge is not None:", "adjacent on the convex hull, i.e. no electrodes returned will", "frame_charge_comp.get_reduced_composition_and_factor() norm_discharge = \\ frame_discharge_comp.get_reduced_composition_and_factor()[1] self._working_ion_entry = working_ion_entry #Initialize normalized", "the specified entries must have the\" \" same compositional framework\")", "Include this identical electrode in the list of results. Returns:", "include_myself or entry_charge != self.fully_charged_entry \\ or entry_discharge != self.fully_discharged_entry:", "#element if comp_charge.get_atomic_fraction(working_element) == \\ comp_discharge.get_atomic_fraction(working_element): raise ValueError(\"VoltagePair: The working", "N_A * 1000 * working_ion_valence #Step 4: add (optional) hull", "None) self.muO2_charge = entry_charge.data.get(\"muO2\", None) self.muO2_discharge = entry_discharge.data.get(\"muO2\", None) self.entry_charge", "min(data) if len(data) > 0 else None def get_sub_electrodes(self, adjacent_only=True,", "= list(self._unstable_entries) return list_copy if charge_to_discharge else list_copy.reverse() def get_all_entries(self,", "in self._entries], \"working_ion_entry\": self.working_ion_entry.as_dict()} class InsertionVoltagePair(AbstractVoltagePair): \"\"\" Defines an Insertion", "if charge_to_discharge else list_copy.reverse() def get_all_entries(self, charge_to_discharge=True): \"\"\" Return all", "to return all the subelectrodes with some options Args: adjacent_only:", "{\"average_voltage\": self.get_average_voltage(), \"max_voltage\": self.max_voltage, \"min_voltage\": self.min_voltage, \"max_delta_volume\": self.max_delta_volume, \"max_voltage_step\": self.max_voltage_step,", "all_entries], key=fsrt) return all_entries if charge_to_discharge else all_entries.reverse() @property def", "#Step 4: add (optional) hull and muO2 data self.decomp_e_charge =", "= self.working_ion d = {\"average_voltage\": self.get_average_voltage(), \"max_voltage\": self.max_voltage, \"min_voltage\": self.min_voltage,", "the topotactic path. \"\"\" return self._stable_entries[-1] def get_max_instability(self, min_voltage=None, max_voltage=None):", "(entry_charge, entry_discharge) = (entry_discharge, entry_charge) comp_charge = entry_charge.composition comp_discharge =", "return min(data) if len(data) > 0 else None def get_max_muO2(self,", "of stable entries in the electrode, ordered by amount of", "None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge is not None: data.append(pair.muO2_charge) return max(data)", "ion = self._working_ion for pair in pair_it: entry_charge = pair.entry_charge", "identical electrode in the list of results. Returns: A list", "for pair in pair_it: entry_charge = pair.entry_charge if adjacent_only \\", "= working_ion_entry.composition.elements[0] self._working_ion_entry = working_ion_entry #Prepare to make phase diagram:", "= entry_discharge.composition ion_sym = working_element.symbol frame_charge_comp = Composition({el: comp_charge[el] for", "__version__ = \"0.1\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __date__", "frac <= dischg_frac if include_myself or entry_charge != self.fully_charged_entry \\", "just a single element if not working_ion_entry.composition.is_element: raise ValueError(\"VoltagePair: The", "the entries\") #check that the entries do not contain the", "same amount of the workin #element if comp_charge.get_atomic_fraction(working_element) == \\", "of the working ion. \"\"\" all_entries = list(self.get_stable_entries()) all_entries.extend(self.get_unstable_entries()) #sort", "= {}, vol_discharge = {}\" .format(self.vol_charge, self.vol_discharge), \"frac_charge = {},", "get_max_instability(self, min_voltage=None, max_voltage=None): \"\"\" The maximum instability along a path", "\\ frame_discharge_comp.reduced_formula: raise ValueError(\"VoltagePair: the specified entries must have the\"", "Development Team. # Distributed under the terms of the MIT", "have the\" \" same compositional framework\") #Initialize normalization factors, charged", "carries charge across the battery, e.g. Li. \"\"\" def __init__(self,", "self.__repr__() def __repr__(self): output = [] chg_form = self.fully_charged_entry.composition.reduced_formula dischg_form", "method can be used to return all the subelectrodes with", "dischg_comp.reduced_formula, \"fracA_charge\": chg_comp.get_atomic_fraction(ion), \"fracA_discharge\": dischg_comp.get_atomic_fraction(ion), \"max_instability\": self.get_max_instability(), \"min_instability\": self.get_min_instability()} if", "for entry in entries]) + 10 pdentries = [] pdentries.extend(entries)", "Voltage Pair. Args: entry1: Entry corresponding to one of the", "path. \"\"\" return self._stable_entries[0] @property def fully_discharged_entry(self): \"\"\" The most", ".format(self.mass_charge, self.mass_discharge), \"vol_charge = {}, vol_discharge = {}\" .format(self.vol_charge, self.vol_discharge),", "max_voltage=None): \"\"\" Maximum critical oxygen chemical potential along path. Args:", "endpoints at {} and {}\".format( chg_form, dischg_form)) output.append(\"Avg. volt. =", "self.fully_charged_entry.composition.reduced_formula dischg_form = self.fully_discharged_entry.composition.reduced_formula output.append(\"InsertionElectrode with endpoints at {} and", "voltage. max_voltage: The maximum allowable voltage. Returns: Maximum decomposition energy", "The minimum instability along a path for a specific voltage", "working_ion_entry) for i in range(len(self._stable_entries) - 1)]) @property def working_ion(self):", "not None: data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is not None: data.append(pair.decomp_e_discharge) return", "state? Defaults to True. Returns: A list of unstable entries", "self._num_ions_transferred + working_ion_entry.energy_per_atom) / working_ion_valence self._mAh = self._num_ions_transferred * Charge(1,", "amount of Li asc self._stable_entries = tuple(sorted([e for e in", "= \\ frame_discharge_comp.get_reduced_composition_and_factor()[1] self._working_ion_entry = working_ion_entry #Initialize normalized properties self._vol_charge", "data on all the possible subelectrodes. Returns: A summary of", "of topotactically related compounds, with different amounts of a single", "charged entry along the topotactic path. \"\"\" return self._stable_entries[0] @property", "the working ion. \"\"\" list_copy = list(self._stable_entries) return list_copy if", "if not frame_charge_comp.reduced_formula == \\ frame_discharge_comp.reduced_formula: raise ValueError(\"VoltagePair: the specified", "The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns:", "mAh = {}\".format(self.voltage, self.mAh), \"mass_charge = {}, mass_discharge = {}\"", "pd.unstable_entries if e in entries], key=lifrac)) #create voltage pairs self._vpairs", "\\ (((entry_charge.energy / norm_charge) - (entry_discharge.energy / norm_discharge)) / \\", "state? Default to True. Returns: A list of stable entries", "vol_discharge = {}\" .format(self.vol_charge, self.vol_discharge), \"frac_charge = {}, frac_discharge =", "pd = PhaseDiagram(pdentries) lifrac = lambda e: e.composition.get_atomic_fraction(self._working_ion) #stable entries", "For example, an LiTiO2 electrode might contain three subelectrodes: [LiTiO2", "Returns: Minimum decomposition energy of all compounds along the insertion", "+ 10 pdentries = [] pdentries.extend(entries) pdentries.extend([PDEntry(Composition({el:1}), element_energy) for el", "element if not working_ion_entry.composition.is_element: raise ValueError(\"VoltagePair: The working ion specified", "= [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.pair.muO2_discharge is", "list of all entries in the electrode (both stable and", "analysis of materials with potential application as intercalation batteries. \"\"\"", "entry_charge.composition.get_atomic_fraction(ion) dischg_frac = entry_discharge.composition.get_atomic_fraction(ion) def in_range(entry): frac = entry.composition.get_atomic_fraction(ion) return", "None) self.muO2_discharge = entry_discharge.data.get(\"muO2\", None) self.entry_charge = entry_charge self.entry_discharge =", "\"\"\" __author__ = \"<NAME>, <NAME>\" __copyright__ = \"Copyright 2012, The", "lambda e: e.composition.get_atomic_fraction(self.working_ion) all_entries = sorted([e for e in all_entries],", "Project\" __version__ = \"0.1\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\"", "the other entry in the voltage step. working_ion_entry: A single", "@property def working_ion_entry(self): return self._working_ion_entry @property def voltage_pairs(self): return self._vpairs", "compounds, with different amounts of a single element, e.g. TiO2", "define an insertion battery electrode. \"\"\" def __init__(self, entries, working_ion_entry):", "entry2: Entry corresponding to the other entry in the voltage", "of the voltage steps to define other electrodes. For example,", "self.max_delta_volume, \"max_voltage_step\": self.max_voltage_step, \"capacity_grav\": self.get_capacity_grav(), \"capacity_vol\": self.get_capacity_vol(), \"energy_grav\": self.get_specific_energy(), \"energy_vol\":", "!= self.fully_charged_entry \\ or entry_discharge != self.fully_discharged_entry: unstable_entries = filter(in_range,", "import Composition from pymatgen.core.units import Charge, Time from pymatgen.phasediagram.maker import", "working_ion_entry.energy_per_atom) / working_ion_valence self._mAh = self._num_ions_transferred * Charge(1, \"e\").to(\"C\") *", "will have multiple voltage steps if this is set True.", "= {}\".format(self.voltage, self.mAh), \"mass_charge = {}, mass_discharge = {}\" .format(self.mass_charge,", "the workin #element if comp_charge.get_atomic_fraction(working_element) == \\ comp_discharge.get_atomic_fraction(working_element): raise ValueError(\"VoltagePair:", "self._select_in_voltage_range(min_voltage, max_voltage): if pair.decomp_e_charge is not None: data.append(pair.decomp_e_charge) if pair.decomp_e_discharge", "set of topotactically related compounds, with different amounts of a", "None) self.entry_charge = entry_charge self.entry_discharge = entry_discharge self.normalization_charge = norm_charge", "Create a new InsertionElectrode. Args: entries: A list of ComputedStructureEntries", "max_voltage=None): \"\"\" The minimum instability along a path for a", "A list of stable entries in the electrode, ordered by", "Returns: Maximum decomposition energy of all compounds along the insertion", "maximum instability along a path for a specific voltage range.", "/ norm_charge) - (entry_discharge.energy / norm_discharge)) / \\ self._num_ions_transferred +", "voltage. Returns: Maximum critical oxygen chemical of all compounds along", "ion. \"\"\" list_copy = list(self._unstable_entries) return list_copy if charge_to_discharge else", "print_subelectrodes: Also print data on all the possible subelectrodes. Returns:", "from scipy.constants import N_A class InsertionElectrode(AbstractElectrode): \"\"\" A set of", "MontyDecoder() return cls(dec.process_decoded(d[\"entries\"]), dec.process_decoded(d[\"working_ion_entry\"])) def as_dict(self): return {\"@module\": self.__class__.__module__, \"@class\":", "frame_discharge_comp = Composition({el: comp_discharge[el] for el in comp_discharge if el.symbol", "specific voltage range. Args: min_voltage: The minimum allowable voltage. max_voltage:", "LiTiO2. working_ion_entry: A single ComputedEntry or PDEntry representing the element", "return max(data) if len(data) > 0 else None def get_min_muO2(self,", "dict. Args: print_subelectrodes: Also print data on all the possible", "entries self._working_ion = working_ion_entry.composition.elements[0] self._working_ion_entry = working_ion_entry #Prepare to make", "(entry_discharge, entry_charge) comp_charge = entry_charge.composition comp_discharge = entry_discharge.composition ion_sym =", "/ norm_discharge) \\ - (comp_charge[working_element] / norm_charge) self._voltage = \\", "possible subelectrodes. Returns: A summary of this electrode\"s properties in", "asc self._unstable_entries = tuple(sorted([e for e in pd.unstable_entries if e", "entry in self._entries], \"working_ion_entry\": self.working_ion_entry.as_dict()} class InsertionVoltagePair(AbstractVoltagePair): \"\"\" Defines an", "subset of the voltage steps to define other electrodes. For", "given step Returns: Minimum critical oxygen chemical of all compounds", "min_voltage: The minimum allowable voltage for a given step max_voltage:", "pair in pair_it: entry_charge = pair.entry_charge if adjacent_only \\ else", "\"\"\" Maximum critical oxygen chemical potential along path. Args: min_voltage:", "order from most charge to most discharged state? Defaults to", "2) ion = self._working_ion for pair in pair_it: entry_charge =", "potential application as intercalation batteries. \"\"\" __author__ = \"<NAME>, <NAME>\"", "= Composition({el: comp_discharge[el] for el in comp_discharge if el.symbol !=", "get_unstable_entries(self, charge_to_discharge=True): \"\"\" Returns the unstable entries for the electrode.", "def get_all_entries(self, charge_to_discharge=True): \"\"\" Return all entries input for the", "or entry_charge != self.fully_charged_entry \\ or entry_discharge != self.fully_discharged_entry: unstable_entries", "entries], key=lifrac)) #unstable entries ordered by amount of Li asc", "4: add (optional) hull and muO2 data self.decomp_e_charge = \\", "= [\"Insertion voltage pair with working ion {}\" .format(self._working_ion_entry.composition.reduced_formula), \"V", "self._vpairs def get_stable_entries(self, charge_to_discharge=True): \"\"\" Get the stable entries. Args:", "@property def vol_discharge(self): return self._vol_discharge @property def working_ion_entry(self): return self._working_ion_entry", "None: data.append(pair.muO2_charge) return max(data) if len(data) > 0 else None", "unstable entries for the electrode. Args: charge_to_discharge: Order from most", "LiTiO2 electrode might contain three subelectrodes: [LiTiO2 --> TiO2, LiTiO2", "working ion atomic percentage \" \"cannot be the same in", "return electrodes from compounds that are adjacent on the convex", "arguments). \"\"\" data = [] for pair in self._select_in_voltage_range(min_voltage, max_voltage):", "discharged state? Defaults to True. Returns: A list of unstable", "norm_discharge = \\ frame_discharge_comp.get_reduced_composition_and_factor()[1] self._working_ion_entry = working_ion_entry #Initialize normalized properties", "\"e\").to(\"C\") * \\ Time(1, \"s\").to(\"h\") * N_A * 1000 *", "AbstractElectrode, \\ AbstractVoltagePair from pymatgen.core.periodic_table import Element from scipy.constants import", "return d def __str__(self): return self.__repr__() def __repr__(self): output =", "the possible subelectrodes. Returns: A summary of this electrode\"s properties", "Args: adjacent_only: Only return electrodes from compounds that are adjacent", "norm_discharge comp_charge = entry_charge.composition comp_discharge = entry_discharge.composition self._mass_charge = comp_charge.weight", "subclasses) representing the different topotactic states of the battery, e.g.", "generation element_energy = max([entry.energy_per_atom for entry in entries]) + 10", "len(data) > 0 else None def get_min_muO2(self, min_voltage=None, max_voltage=None): \"\"\"", "= comp_charge.get_atomic_fraction(working_element) self._frac_discharge = \\ comp_discharge.get_atomic_fraction(working_element) @property def frac_charge(self): return", "minimum allowable voltage for a given step max_voltage: The maximum", "for el in comp_discharge if el.symbol != ion_sym}) #Data validation", "__init__(self, entries, working_ion_entry): \"\"\" Create a new InsertionElectrode. Args: entries:", "charge across the battery, e.g. Li. \"\"\" self._entries = entries", "by amount of the working ion. \"\"\" list_copy = list(self._unstable_entries)", "battery_list def as_dict_summary(self, print_subelectrodes=True): \"\"\" Generate a summary dict. Args:", "Li0.5TiO2 --> TiO2] This method can be used to return", "raise ValueError(\"VoltagePair: The working ion atomic percentage \" \"cannot be", "of the entries contains the working element if not comp_charge.get_atomic_fraction(working_element)", "ion must be present in \" \"one of the entries\")", "frameworks of the entries are equivalent if not frame_charge_comp.reduced_formula ==", "self.max_voltage_step, \"capacity_grav\": self.get_capacity_grav(), \"capacity_vol\": self.get_capacity_vol(), \"energy_grav\": self.get_specific_energy(), \"energy_vol\": self.get_energy_density(), \"working_ion\":", "normalization factors, charged and discharged entries valence_list = Element(ion_sym).oxidation_states working_ion_valence", "list(self.get_stable_entries()) all_entries.extend(self.get_unstable_entries()) #sort all entries by amount of working ion", "working ion. \"\"\" list_copy = list(self._stable_entries) return list_copy if charge_to_discharge", "PDEntry from pymatgen.apps.battery.battery_abc import AbstractElectrode, \\ AbstractVoltagePair from pymatgen.core.periodic_table import", "muO2 data self.decomp_e_charge = \\ entry_charge.data.get(\"decomposition_energy\", None) self.decomp_e_discharge = \\", "that the frameworks of the entries are equivalent if not", "the list of results. Returns: A list of InsertionElectrode objects", "charge_to_discharge=True): \"\"\" Returns the unstable entries for the electrode. Args:", "norm_charge) - (entry_discharge.energy / norm_discharge)) / \\ self._num_ions_transferred + working_ion_entry.energy_per_atom)", "that the ion is just a single element if not", "electrode. \"\"\" def __init__(self, entries, working_ion_entry): \"\"\" Create a new", "that the entries do not contain the same amount of", "workin #element if comp_charge.get_atomic_fraction(working_element) == \\ comp_discharge.get_atomic_fraction(working_element): raise ValueError(\"VoltagePair: The", "objects \"\"\" battery_list = [] pair_it = self._vpairs if adjacent_only", "The working ion specified must be \" \"an element\") #check", "path. \"\"\" return self._stable_entries[-1] def get_max_instability(self, min_voltage=None, max_voltage=None): \"\"\" The", "entry_discharge.composition ion_sym = working_element.symbol frame_charge_comp = Composition({el: comp_charge[el] for el", "mAh/g\".format(self.get_capacity_grav())) output.append(\"Vol. cap. = {}\".format(self.get_capacity_vol())) return \"\\n\".join(output) @classmethod def from_dict(cls,", "entry_discharge.data.get(\"decomposition_energy\", None) self.muO2_charge = entry_charge.data.get(\"muO2\", None) self.muO2_discharge = entry_discharge.data.get(\"muO2\", None)", "def __init__(self, entries, working_ion_entry): \"\"\" Create a new InsertionElectrode. Args:", "of the working ion. \"\"\" list_copy = list(self._stable_entries) return list_copy", "batteries. \"\"\" __author__ = \"<NAME>, <NAME>\" __copyright__ = \"Copyright 2012,", "element for convex hull generation element_energy = max([entry.energy_per_atom for entry", "Minimum decomposition energy of all compounds along the insertion path", "filter(in_range, self.get_stable_entries()) all_entries = list(stable_entries) all_entries.extend(unstable_entries) battery_list.append(self.__class__(all_entries, self.working_ion_entry)) return battery_list", "\"nsteps\": self.num_steps, \"framework\": self._vpairs[0].framework.to_data_dict, \"formula_charge\": chg_comp.reduced_formula, \"formula_discharge\": dischg_comp.reduced_formula, \"fracA_charge\": chg_comp.get_atomic_fraction(ion),", "return self._frac_discharge @property def voltage(self): return self._voltage @property def mAh(self):", "list of unstable entries in the electrode, ordered by amount", "else pair[0].entry_charge entry_discharge = pair.entry_discharge if adjacent_only \\ else pair[1].entry_discharge", "ion atomic percentage \" \"cannot be the same in both", "step. working_ion_entry: A single ComputedEntry or PDEntry representing the element", "pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge)", "Defines an Insertion Voltage Pair. Args: entry1: Entry corresponding to", "in the electrode, ordered by amount of the working ion.", "pair.muO2_charge is not None: data.append(pair.muO2_charge) return min(data) if len(data) >", "* Charge(1, \"e\").to(\"C\") * \\ Time(1, \"s\").to(\"h\") * N_A *", "A list of ComputedStructureEntries (or subclasses) representing the different topotactic", "self._working_ion for pair in pair_it: entry_charge = pair.entry_charge if adjacent_only", "with some options Args: adjacent_only: Only return electrodes from compounds", "representing the element that carries charge across the battery, e.g.", "The minimum allowable voltage for a given step max_voltage: The", "!= ion_sym}) frame_discharge_comp = Composition({el: comp_discharge[el] for el in comp_discharge", "#Data validation #check that the ion is just a single", "not None: data.append(pair.muO2_charge) return max(data) if len(data) > 0 else", "itertools from pymatgen.core.composition import Composition from pymatgen.core.units import Charge, Time", "output = [] chg_form = self.fully_charged_entry.composition.reduced_formula dischg_form = self.fully_discharged_entry.composition.reduced_formula output.append(\"InsertionElectrode", "from pymatgen.core.units import Charge, Time from pymatgen.phasediagram.maker import PhaseDiagram from", "in all_entries], key=fsrt) return all_entries if charge_to_discharge else all_entries.reverse() @property", "all_entries if charge_to_discharge else all_entries.reverse() @property def fully_charged_entry(self): \"\"\" The", "return self._stable_entries[-1] def get_max_instability(self, min_voltage=None, max_voltage=None): \"\"\" The maximum instability", "def __str__(self): return self.__repr__() def __repr__(self): output = [] chg_form", "= entry_charge.composition.get_atomic_fraction(ion) dischg_frac = entry_discharge.composition.get_atomic_fraction(ion) def in_range(entry): frac = entry.composition.get_atomic_fraction(ion)", "map(f_dict, self.get_sub_electrodes(adjacent_only=False)) return d def __str__(self): return self.__repr__() def __repr__(self):", "The Materials Project\" __version__ = \"0.1\" __maintainer__ = \"<NAME>\" __email__", "working_ion_entry: A single ComputedEntry or PDEntry representing the element that", "return chg_frac <= frac <= dischg_frac if include_myself or entry_charge", "self.muO2_discharge = entry_discharge.data.get(\"muO2\", None) self.entry_charge = entry_charge self.entry_discharge = entry_discharge", "self.get_sub_electrodes(adjacent_only=True)) d[\"all_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=False)) return d def __str__(self): return", "Minimum critical oxygen chemical of all compounds along the insertion", "print_subelectrodes=True): \"\"\" Generate a summary dict. Args: print_subelectrodes: Also print", "object \"\"\" return self._working_ion @property def working_ion_entry(self): return self._working_ion_entry @property", "data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is not None: data.append(pair.decomp_e_discharge) return max(data) if", "battery, e.g. Li. \"\"\" def __init__(self, entry1, entry2, working_ion_entry): #initialize", "working ion. \"\"\" all_entries = list(self.get_stable_entries()) all_entries.extend(self.get_unstable_entries()) #sort all entries", "if e in entries], key=lifrac)) #create voltage pairs self._vpairs =", "Return all entries input for the electrode. Args: charge_to_discharge: order", "allowable voltage. max_voltage: The maximum allowable voltage. Returns: Maximum critical", "some internal variables working_element = working_ion_entry.composition.elements[0] entry_charge = entry1 entry_discharge", "PhaseDiagram(pdentries) lifrac = lambda e: e.composition.get_atomic_fraction(self._working_ion) #stable entries ordered by", "a single element, e.g. TiO2 and LiTiO2, that can be", "\"energy_grav\": self.get_specific_energy(), \"energy_vol\": self.get_energy_density(), \"working_ion\": self._working_ion.symbol, \"nsteps\": self.num_steps, \"framework\": self._vpairs[0].framework.to_data_dict,", "e.composition.get_atomic_fraction(self._working_ion) #stable entries ordered by amount of Li asc self._stable_entries", "self._frac_discharge @property def voltage(self): return self._voltage @property def mAh(self): return", "for el in elements]) #Make phase diagram to determine which", "Pymatgen Development Team. # Distributed under the terms of the", "min_voltage=None, max_voltage=None): \"\"\" The minimum instability along a path for", "Maximum decomposition energy of all compounds along the insertion path", "self._entries], \"working_ion_entry\": self.working_ion_entry.as_dict()} class InsertionVoltagePair(AbstractVoltagePair): \"\"\" Defines an Insertion Voltage", "set() for entry in entries: elements.update(entry.composition.elements) #Set an artificial energy", "comp_discharge if el.symbol != ion_sym}) #Data validation #check that the", "__repr__(self): output = [] chg_form = self.fully_charged_entry.composition.reduced_formula dischg_form = self.fully_discharged_entry.composition.reduced_formula", "elements]) #Make phase diagram to determine which entries are stable", "{}\" .format(self.vol_charge, self.vol_discharge), \"frac_charge = {}, frac_discharge = {}\" .format(self.frac_charge,", "Element(ion_sym).oxidation_states working_ion_valence = max(valence_list) (self.framework, norm_charge) = frame_charge_comp.get_reduced_composition_and_factor() norm_discharge =", "= tuple(sorted([e for e in pd.unstable_entries if e in entries],", "self._working_ion_entry @property def voltage_pairs(self): return self._vpairs def get_stable_entries(self, charge_to_discharge=True): \"\"\"", "ComputedStructureEntries (or subclasses) representing the different topotactic states of the", "chg_form = self.fully_charged_entry.composition.reduced_formula dischg_form = self.fully_discharged_entry.composition.reduced_formula output.append(\"InsertionElectrode with endpoints at", "cap. = {} mAh/g\".format(self.get_capacity_grav())) output.append(\"Vol. cap. = {}\".format(self.get_capacity_vol())) return \"\\n\".join(output)", "stable entries in the electrode, ordered by amount of the", "comp_discharge = entry_discharge.composition self._mass_charge = comp_charge.weight / norm_charge self._mass_discharge =", "\"min_voltage\": self.min_voltage, \"max_delta_volume\": self.max_delta_volume, \"max_voltage_step\": self.max_voltage_step, \"capacity_grav\": self.get_capacity_grav(), \"capacity_vol\": self.get_capacity_vol(),", "output.append(\"Vol. cap. = {}\".format(self.get_capacity_vol())) return \"\\n\".join(output) @classmethod def from_dict(cls, d):", "chosen by the optional arguments) \"\"\" data = [] for", "0 else None def get_min_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Minimum critical", "internal variables working_element = working_ion_entry.composition.elements[0] entry_charge = entry1 entry_discharge =", "path (a subset of the path can be chosen by", "\\ - (comp_charge[working_element] / norm_charge) self._voltage = \\ (((entry_charge.energy /", "different amounts of a single element, e.g. TiO2 and LiTiO2,", "pairs self._vpairs = tuple([InsertionVoltagePair(self._stable_entries[i], self._stable_entries[i + 1], working_ion_entry) for i", "the\" \" same compositional framework\") #Initialize normalization factors, charged and", "\"max_voltage\": self.max_voltage, \"min_voltage\": self.min_voltage, \"max_delta_volume\": self.max_delta_volume, \"max_voltage_step\": self.max_voltage_step, \"capacity_grav\": self.get_capacity_grav(),", "if el.symbol != ion_sym}) frame_discharge_comp = Composition({el: comp_discharge[el] for el", "data self.decomp_e_charge = \\ entry_charge.data.get(\"decomposition_energy\", None) self.decomp_e_discharge = \\ entry_discharge.data.get(\"decomposition_energy\",", "self.entry_charge = entry_charge self.entry_discharge = entry_discharge self.normalization_charge = norm_charge self.normalization_discharge", "use only a subset of the voltage steps to define", "el in elements]) #Make phase diagram to determine which entries", "\"\"\" This module is used for analysis of materials with", "stable vs. unstable pd = PhaseDiagram(pdentries) lifrac = lambda e:", "\"framework\": self._vpairs[0].framework.to_data_dict, \"formula_charge\": chg_comp.reduced_formula, \"formula_discharge\": dischg_comp.reduced_formula, \"fracA_charge\": chg_comp.get_atomic_fraction(ion), \"fracA_discharge\": dischg_comp.get_atomic_fraction(ion),", "= lambda c: c.as_dict_summary(print_subelectrodes=False) d[\"adj_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=True)) d[\"all_pairs\"] =", "\"\"\" def __init__(self, entries, working_ion_entry): \"\"\" Create a new InsertionElectrode.", "#Initialize normalization factors, charged and discharged entries valence_list = Element(ion_sym).oxidation_states", "all_entries.reverse() @property def fully_charged_entry(self): \"\"\" The most charged entry along", "def fully_charged_entry(self): \"\"\" The most charged entry along the topotactic", "self.fully_charged_entry.composition dischg_comp = self.fully_discharged_entry.composition ion = self.working_ion d = {\"average_voltage\":", "entries by amount of working ion ASC fsrt = lambda", "\\ entry_charge.data.get(\"decomposition_energy\", None) self.decomp_e_discharge = \\ entry_discharge.data.get(\"decomposition_energy\", None) self.muO2_charge =", "from pymatgen.phasediagram.maker import PhaseDiagram from pymatgen.phasediagram.entries import PDEntry from pymatgen.apps.battery.battery_abc", ".format(self.vol_charge, self.vol_discharge), \"frac_charge = {}, frac_discharge = {}\" .format(self.frac_charge, self.frac_discharge)]", "are equivalent if not frame_charge_comp.reduced_formula == \\ frame_discharge_comp.reduced_formula: raise ValueError(\"VoltagePair:", "= PhaseDiagram(pdentries) lifrac = lambda e: e.composition.get_atomic_fraction(self._working_ion) #stable entries ordered", "fsrt = lambda e: e.composition.get_atomic_fraction(self.working_ion) all_entries = sorted([e for e", "\\ else pair[0].entry_charge entry_discharge = pair.entry_discharge if adjacent_only \\ else", "Also print data on all the possible subelectrodes. Returns: A", "pymatgen.core.periodic_table import Element from scipy.constants import N_A class InsertionElectrode(AbstractElectrode): \"\"\"", "return self._working_ion_entry @property def voltage_pairs(self): return self._vpairs def get_stable_entries(self, charge_to_discharge=True):", "ValueError(\"VoltagePair: The working ion specified must be \" \"an element\")", "= entry_charge.structure.volume / norm_charge self._vol_discharge = entry_discharge.structure.volume / norm_discharge comp_charge", "return self._stable_entries[0] @property def fully_discharged_entry(self): \"\"\" The most discharged entry", "chg_comp = self.fully_charged_entry.composition dischg_comp = self.fully_discharged_entry.composition ion = self.working_ion d", "output.append(\"InsertionElectrode with endpoints at {} and {}\".format( chg_form, dischg_form)) output.append(\"Avg.", "#Make phase diagram to determine which entries are stable vs.", "\"<NAME>, <NAME>\" __copyright__ = \"Copyright 2012, The Materials Project\" __version__", "= [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.decomp_e_charge is", "= entry_charge.composition comp_discharge = entry_discharge.composition self._mass_charge = comp_charge.weight / norm_charge", "e in entries], key=lifrac)) #create voltage pairs self._vpairs = tuple([InsertionVoltagePair(self._stable_entries[i],", "single ComputedEntry or PDEntry representing the element that carries charge", "voltage steps if this is set True. include_myself: Include this", "chg_frac = entry_charge.composition.get_atomic_fraction(ion) dischg_frac = entry_discharge.composition.get_atomic_fraction(ion) def in_range(entry): frac =", "chemical of all compounds along the insertion path (a subset", "ComputedEntry or PDEntry representing the element that carries charge across", "of working ion ASC fsrt = lambda e: e.composition.get_atomic_fraction(self.working_ion) all_entries", "\\ AbstractVoltagePair from pymatgen.core.periodic_table import Element from scipy.constants import N_A", "have multiple voltage steps if this is set True. include_myself:", "this electrode contains multiple voltage steps, then it is possible", "@classmethod def from_dict(cls, d): from monty.json import MontyDecoder dec =", "\"\"\" self._entries = entries self._working_ion = working_ion_entry.composition.elements[0] self._working_ion_entry = working_ion_entry", "#check that the frameworks of the entries are equivalent if", "= list(self.get_stable_entries()) all_entries.extend(self.get_unstable_entries()) #sort all entries by amount of working", "[] pair_it = self._vpairs if adjacent_only \\ else itertools.combinations_with_replacement(self._vpairs, 2)", "max_voltage): if pair.decomp_e_charge is not None: data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is", "#Prepare to make phase diagram: determine elements and set their", "\\ else itertools.combinations_with_replacement(self._vpairs, 2) ion = self._working_ion for pair in", "this is set True. include_myself: Include this identical electrode in", "def voltage(self): return self._voltage @property def mAh(self): return self._mAh @property", "from monty.json import MontyDecoder dec = MontyDecoder() return cls(dec.process_decoded(d[\"entries\"]), dec.process_decoded(d[\"working_ion_entry\"]))", "\"capacity_vol\": self.get_capacity_vol(), \"energy_grav\": self.get_specific_energy(), \"energy_vol\": self.get_energy_density(), \"working_ion\": self._working_ion.symbol, \"nsteps\": self.num_steps,", "if pair.decomp_e_discharge is not None: data.append(pair.decomp_e_discharge) return max(data) if len(data)", "len(data) > 0 else None def get_sub_electrodes(self, adjacent_only=True, include_myself=True): \"\"\"", "Li. \"\"\" def __init__(self, entry1, entry2, working_ion_entry): #initialize some internal", "LiTiO2 --> Li0.5TiO2, Li0.5TiO2 --> TiO2] This method can be", "= sorted([e for e in all_entries], key=fsrt) return all_entries if", "is not None: data.append(pair.decomp_e_discharge) return min(data) if len(data) > 0", "@property def frac_discharge(self): return self._frac_discharge @property def voltage(self): return self._voltage", "of the path can be chosen by the optional arguments)", "adjacent_only \\ else itertools.combinations_with_replacement(self._vpairs, 2) ion = self._working_ion for pair", "= [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.muO2_discharge is", "norm_discharge)) / \\ self._num_ions_transferred + working_ion_entry.energy_per_atom) / working_ion_valence self._mAh =", "self.get_unstable_entries()) stable_entries = filter(in_range, self.get_stable_entries()) all_entries = list(stable_entries) all_entries.extend(unstable_entries) battery_list.append(self.__class__(all_entries,", "return max(data) if len(data) > 0 else None def get_min_instability(self,", "is not None: data.append(pair.muO2_charge) return min(data) if len(data) > 0", "\"Copyright 2012, The Materials Project\" __version__ = \"0.1\" __maintainer__ =", "else all_entries.reverse() @property def fully_charged_entry(self): \"\"\" The most charged entry", "battery_list = [] pair_it = self._vpairs if adjacent_only \\ else", "= map(f_dict, self.get_sub_electrodes(adjacent_only=True)) d[\"all_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=False)) return d def", "A list of InsertionElectrode objects \"\"\" battery_list = [] pair_it", "Composition({el: comp_charge[el] for el in comp_charge if el.symbol != ion_sym})", "self._stable_entries[0] @property def fully_discharged_entry(self): \"\"\" The most discharged entry along", "\"max_voltage_step\": self.max_voltage_step, \"capacity_grav\": self.get_capacity_grav(), \"capacity_vol\": self.get_capacity_vol(), \"energy_grav\": self.get_specific_energy(), \"energy_vol\": self.get_energy_density(),", "from pymatgen.apps.battery.battery_abc import AbstractElectrode, \\ AbstractVoltagePair from pymatgen.core.periodic_table import Element", "an artificial energy for each element for convex hull generation", "Returns: A list of all entries in the electrode (both", "in the electrode (both stable and unstable), ordered by amount", "the electrode. Args: charge_to_discharge: order from most charge to most", "min_voltage=None, max_voltage=None): \"\"\" Maximum critical oxygen chemical potential along path.", "def get_sub_electrodes(self, adjacent_only=True, include_myself=True): \"\"\" If this electrode contains multiple", "key=lifrac)) #unstable entries ordered by amount of Li asc self._unstable_entries", "self._vol_charge = entry_charge.structure.volume / norm_charge self._vol_discharge = entry_discharge.structure.volume / norm_discharge", "be chosen by the optional arguments) \"\"\" data = []", "self.get_specific_energy(), \"energy_vol\": self.get_energy_density(), \"working_ion\": self._working_ion.symbol, \"nsteps\": self.num_steps, \"framework\": self._vpairs[0].framework.to_data_dict, \"formula_charge\":", "#check that the ion is just a single element if", "most charge to most discharged state? Default to True. Returns:", "stable and unstable), ordered by amount of the working ion.", "\"<EMAIL>\" __date__ = \"Jan 13, 2012\" __status__ = \"Beta\" import", "and set their energy #to be very high elements =", "self.get_sub_electrodes(adjacent_only=False)) return d def __str__(self): return self.__repr__() def __repr__(self): output", "range(len(self._stable_entries) - 1)]) @property def working_ion(self): \"\"\" The working ion", "entry along the topotactic path. \"\"\" return self._stable_entries[-1] def get_max_instability(self,", "@property def voltage_pairs(self): return self._vpairs def get_stable_entries(self, charge_to_discharge=True): \"\"\" Get", "charge_to_discharge=True): \"\"\" Return all entries input for the electrode. Args:", "get_max_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Maximum critical oxygen chemical potential along", "self._voltage @property def mAh(self): return self._mAh @property def mass_charge(self): return", "0 else None def get_min_instability(self, min_voltage=None, max_voltage=None): \"\"\" The minimum", "def frac_charge(self): return self._frac_charge @property def frac_discharge(self): return self._frac_discharge @property", "mass_discharge(self): return self._mass_discharge @property def vol_charge(self): return self._vol_charge @property def", "entries for the electrode. Args: charge_to_discharge: Order from most charge", "steps, then it is possible to use only a subset", "data = [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.muO2_discharge", "/ norm_discharge comp_charge = entry_charge.composition comp_discharge = entry_discharge.composition self._mass_charge =", "self.decomp_e_discharge = \\ entry_discharge.data.get(\"decomposition_energy\", None) self.muO2_charge = entry_charge.data.get(\"muO2\", None) self.muO2_discharge", "pymatgen.phasediagram.entries import PDEntry from pymatgen.apps.battery.battery_abc import AbstractElectrode, \\ AbstractVoltagePair from", "entries ordered by amount of Li asc self._unstable_entries = tuple(sorted([e", "#to be very high elements = set() for entry in", "voltage steps, then it is possible to use only a", "comp_charge[el] for el in comp_charge if el.symbol != ion_sym}) frame_discharge_comp", "max([entry.energy_per_atom for entry in entries]) + 10 pdentries = []", "equivalent if not frame_charge_comp.reduced_formula == \\ frame_discharge_comp.reduced_formula: raise ValueError(\"VoltagePair: the", "entries: A list of ComputedStructureEntries (or subclasses) representing the different", "in both the entries\") #check that the frameworks of the", "voltage(self): return self._voltage @property def mAh(self): return self._mAh @property def", "entries\") #check that the frameworks of the entries are equivalent", "ion_sym}) frame_discharge_comp = Composition({el: comp_discharge[el] for el in comp_discharge if", "electrode\"s properties in dict format. \"\"\" chg_comp = self.fully_charged_entry.composition dischg_comp", "the electrode. Args: charge_to_discharge: Order from most charge to most", "frame_charge_comp.reduced_formula == \\ frame_discharge_comp.reduced_formula: raise ValueError(\"VoltagePair: the specified entries must", "in pair_it: entry_charge = pair.entry_charge if adjacent_only \\ else pair[0].entry_charge", "/ \\ self._num_ions_transferred + working_ion_entry.energy_per_atom) / working_ion_valence self._mAh = self._num_ions_transferred", "\"max_instability\": self.get_max_instability(), \"min_instability\": self.get_min_instability()} if print_subelectrodes: f_dict = lambda c:", "of this electrode\"s properties in dict format. \"\"\" chg_comp =", "= entry_discharge.data.get(\"muO2\", None) self.entry_charge = entry_charge self.entry_discharge = entry_discharge self.normalization_charge", "amount of the working ion. \"\"\" list_copy = list(self._stable_entries) return", "@property def mAh(self): return self._mAh @property def mass_charge(self): return self._mass_charge", "= tuple(sorted([e for e in pd.stable_entries if e in entries],", "= entry_charge.composition comp_discharge = entry_discharge.composition ion_sym = working_element.symbol frame_charge_comp =", "= {}, mass_discharge = {}\" .format(self.mass_charge, self.mass_discharge), \"vol_charge = {},", "entries in the voltage step. entry2: Entry corresponding to the", "(both stable and unstable), ordered by amount of the working", "comp_discharge[el] for el in comp_discharge if el.symbol != ion_sym}) #Data", "element\") #check that at least one of the entries contains", "\"max_delta_volume\": self.max_delta_volume, \"max_voltage_step\": self.max_voltage_step, \"capacity_grav\": self.get_capacity_grav(), \"capacity_vol\": self.get_capacity_vol(), \"energy_grav\": self.get_specific_energy(),", "This method can be used to return all the subelectrodes", "= entry_discharge.structure.volume / norm_discharge comp_charge = entry_charge.composition comp_discharge = entry_discharge.composition", "the path can be chosen by the optional arguments). \"\"\"", "__email__ = \"<EMAIL>\" __date__ = \"Jan 13, 2012\" __status__ =", "None: data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is not None: data.append(pair.decomp_e_discharge) return max(data)", "e in pd.stable_entries if e in entries], key=lifrac)) #unstable entries", "A list of unstable entries in the electrode, ordered by", "be present in \" \"one of the entries\") #check that", "amount of the working ion. \"\"\" all_entries = list(self.get_stable_entries()) all_entries.extend(self.get_unstable_entries())", "get_sub_electrodes(self, adjacent_only=True, include_myself=True): \"\"\" If this electrode contains multiple voltage", "dischg_frac = entry_discharge.composition.get_atomic_fraction(ion) def in_range(entry): frac = entry.composition.get_atomic_fraction(ion) return chg_frac", "return min(data) if len(data) > 0 else None def get_sub_electrodes(self,", "working_ion_valence self._mAh = self._num_ions_transferred * Charge(1, \"e\").to(\"C\") * \\ Time(1,", "cap. = {}\".format(self.get_capacity_vol())) return \"\\n\".join(output) @classmethod def from_dict(cls, d): from", "related compounds, with different amounts of a single element, e.g.", "max_voltage=None): \"\"\" The maximum instability along a path for a", "allowable voltage. Returns: Maximum critical oxygen chemical of all compounds", "the entries contains the working element if not comp_charge.get_atomic_fraction(working_element) >", "steps if this is set True. include_myself: Include this identical", "self._num_ions_transferred * Charge(1, \"e\").to(\"C\") * \\ Time(1, \"s\").to(\"h\") * N_A", "voltage pair with working ion {}\" .format(self._working_ion_entry.composition.reduced_formula), \"V = {},", "given step max_voltage: The maximum allowable voltage allowable for a", "min(data) if len(data) > 0 else None def get_max_muO2(self, min_voltage=None,", "all_entries.extend(unstable_entries) battery_list.append(self.__class__(all_entries, self.working_ion_entry)) return battery_list def as_dict_summary(self, print_subelectrodes=True): \"\"\" Generate", "(or subclasses) representing the different topotactic states of the battery,", "charge_to_discharge: Order from most charge to most discharged state? Defaults", "<filename>pymatgen/apps/battery/insertion_battery.py # coding: utf-8 # Copyright (c) Pymatgen Development Team.", "= entry_discharge self.normalization_charge = norm_charge self.normalization_discharge = norm_discharge self._frac_charge =", "of a single element, e.g. TiO2 and LiTiO2, that can", "2012\" __status__ = \"Beta\" import itertools from pymatgen.core.composition import Composition", "else list_copy.reverse() def get_unstable_entries(self, charge_to_discharge=True): \"\"\" Returns the unstable entries", "charge_to_discharge else list_copy.reverse() def get_all_entries(self, charge_to_discharge=True): \"\"\" Return all entries", "if e in entries], key=lifrac)) #unstable entries ordered by amount", "entry_charge.composition comp_discharge = entry_discharge.composition self._mass_charge = comp_charge.weight / norm_charge self._mass_discharge", "\"mass_charge = {}, mass_discharge = {}\" .format(self.mass_charge, self.mass_discharge), \"vol_charge =", "of Li asc self._unstable_entries = tuple(sorted([e for e in pd.unstable_entries", "ordered by amount of the working ion. \"\"\" all_entries =", "of ComputedStructureEntries (or subclasses) representing the different topotactic states of", "= [] pdentries.extend(entries) pdentries.extend([PDEntry(Composition({el:1}), element_energy) for el in elements]) #Make", "def vol_charge(self): return self._vol_charge @property def vol_discharge(self): return self._vol_discharge @property", "Entry corresponding to one of the entries in the voltage", "1000 * working_ion_valence #Step 4: add (optional) hull and muO2", "= tuple([InsertionVoltagePair(self._stable_entries[i], self._stable_entries[i + 1], working_ion_entry) for i in range(len(self._stable_entries)", "amount of the working ion. \"\"\" list_copy = list(self._unstable_entries) return", "return list_copy if charge_to_discharge else list_copy.reverse() def get_all_entries(self, charge_to_discharge=True): \"\"\"", "[] chg_form = self.fully_charged_entry.composition.reduced_formula dischg_form = self.fully_discharged_entry.composition.reduced_formula output.append(\"InsertionElectrode with endpoints", "atomic percentage \" \"cannot be the same in both the", "working ion specified must be \" \"an element\") #check that", "TiO2, LiTiO2 --> Li0.5TiO2, Li0.5TiO2 --> TiO2] This method can", "raise ValueError(\"VoltagePair: the specified entries must have the\" \" same", "entries input for the electrode. Args: charge_to_discharge: order from most", "comp_charge.get_atomic_fraction(working_element) > 0 and \\ not comp_discharge.get_atomic_fraction(working_element) > 0: raise", "\"cannot be the same in both the entries\") #check that", "+ 1], working_ion_entry) for i in range(len(self._stable_entries) - 1)]) @property", "self.get_capacity_vol(), \"energy_grav\": self.get_specific_energy(), \"energy_vol\": self.get_energy_density(), \"working_ion\": self._working_ion.symbol, \"nsteps\": self.num_steps, \"framework\":", "to True. Returns: A list of stable entries in the", "ion {}\" .format(self._working_ion_entry.composition.reduced_formula), \"V = {}, mAh = {}\".format(self.voltage, self.mAh),", "fully_charged_entry(self): \"\"\" The most charged entry along the topotactic path.", "dischg_form = self.fully_discharged_entry.composition.reduced_formula output.append(\"InsertionElectrode with endpoints at {} and {}\".format(", "The maximum allowable voltage. Returns: Maximum critical oxygen chemical of", "are stable vs. unstable pd = PhaseDiagram(pdentries) lifrac = lambda", "to most discharged state? Defaults to True. Returns: A list", "example, an LiTiO2 electrode might contain three subelectrodes: [LiTiO2 -->", "potential along path. Args: min_voltage: The minimum allowable voltage for", "insertion path (a subset of the path can be chosen", "that at least one of the entries contains the working", "!= ion_sym}) #Data validation #check that the ion is just", "high elements = set() for entry in entries: elements.update(entry.composition.elements) #Set", "single element, e.g. TiO2 and LiTiO2, that can be used", "itertools.combinations_with_replacement(self._vpairs, 2) ion = self._working_ion for pair in pair_it: entry_charge", "import AbstractElectrode, \\ AbstractVoltagePair from pymatgen.core.periodic_table import Element from scipy.constants", "norm_discharge) \\ - (comp_charge[working_element] / norm_charge) self._voltage = \\ (((entry_charge.energy", "other entry in the voltage step. working_ion_entry: A single ComputedEntry", "InsertionVoltagePair(AbstractVoltagePair): \"\"\" Defines an Insertion Voltage Pair. Args: entry1: Entry", "from compounds that are adjacent on the convex hull, i.e.", "- 1)]) @property def working_ion(self): \"\"\" The working ion as", "working_ion_entry): \"\"\" Create a new InsertionElectrode. Args: entries: A list", "ValueError(\"VoltagePair: The working ion must be present in \" \"one", "application as intercalation batteries. \"\"\" __author__ = \"<NAME>, <NAME>\" __copyright__", "summary dict. Args: print_subelectrodes: Also print data on all the", "used to return all the subelectrodes with some options Args:", "all entries by amount of working ion ASC fsrt =", "d = {\"average_voltage\": self.get_average_voltage(), \"max_voltage\": self.max_voltage, \"min_voltage\": self.min_voltage, \"max_delta_volume\": self.max_delta_volume,", "{}\".format(self.get_capacity_vol())) return \"\\n\".join(output) @classmethod def from_dict(cls, d): from monty.json import", "el in comp_discharge if el.symbol != ion_sym}) #Data validation #check", "all entries in the electrode (both stable and unstable), ordered", "working_ion_entry(self): return self._working_ion_entry def __repr__(self): output = [\"Insertion voltage pair", "entry_charge.composition.get_atomic_fraction(working_element) \\ > entry2.composition.get_atomic_fraction(working_element): (entry_charge, entry_discharge) = (entry_discharge, entry_charge) comp_charge", "charge_to_discharge else all_entries.reverse() @property def fully_charged_entry(self): \"\"\" The most charged", "return self._mAh @property def mass_charge(self): return self._mass_charge @property def mass_discharge(self):", "different topotactic states of the battery, e.g. TiO2 and LiTiO2.", "= max(valence_list) (self.framework, norm_charge) = frame_charge_comp.get_reduced_composition_and_factor() norm_discharge = \\ frame_discharge_comp.get_reduced_composition_and_factor()[1]", "ion is just a single element if not working_ion_entry.composition.is_element: raise", "[] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.pair.muO2_discharge is not", "return self._mass_discharge @property def vol_charge(self): return self._vol_charge @property def vol_discharge(self):", "element if not comp_charge.get_atomic_fraction(working_element) > 0 and \\ not comp_discharge.get_atomic_fraction(working_element)", "allowable voltage for a given step max_voltage: The maximum allowable", "self._select_in_voltage_range(min_voltage, max_voltage): if pair.pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge", "the electrode (both stable and unstable), ordered by amount of", "def as_dict(self): return {\"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"entries\": [entry.as_dict() for", "import PDEntry from pymatgen.apps.battery.battery_abc import AbstractElectrode, \\ AbstractVoltagePair from pymatgen.core.periodic_table", "self._mAh @property def mass_charge(self): return self._mass_charge @property def mass_discharge(self): return", "options Args: adjacent_only: Only return electrodes from compounds that are", "self._vpairs if adjacent_only \\ else itertools.combinations_with_replacement(self._vpairs, 2) ion = self._working_ion", "unstable pd = PhaseDiagram(pdentries) lifrac = lambda e: e.composition.get_atomic_fraction(self._working_ion) #stable", "volt. = {} V\".format(self.get_average_voltage())) output.append(\"Grav. cap. = {} mAh/g\".format(self.get_capacity_grav())) output.append(\"Vol.", "Defaults to True. Returns: A list of unstable entries in", "The working ion as an Element object \"\"\" return self._working_ion", "\"\"\" Returns the unstable entries for the electrode. Args: charge_to_discharge:", "asc self._stable_entries = tuple(sorted([e for e in pd.stable_entries if e", "all the possible subelectrodes. Returns: A summary of this electrode\"s", "min_voltage=None, max_voltage=None): \"\"\" The maximum instability along a path for", "Insertion Voltage Pair. Args: entry1: Entry corresponding to one of", "self._select_in_voltage_range(min_voltage, max_voltage): if pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge", "\"\"\" If this electrode contains multiple voltage steps, then it", "of the path can be chosen by the optional arguments).", "= self._num_ions_transferred * Charge(1, \"e\").to(\"C\") * \\ Time(1, \"s\").to(\"h\") *", "tuple([InsertionVoltagePair(self._stable_entries[i], self._stable_entries[i + 1], working_ion_entry) for i in range(len(self._stable_entries) -", "[] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.decomp_e_charge is not", "the topotactic path. \"\"\" return self._stable_entries[0] @property def fully_discharged_entry(self): \"\"\"", "entries: elements.update(entry.composition.elements) #Set an artificial energy for each element for", "import Element from scipy.constants import N_A class InsertionElectrode(AbstractElectrode): \"\"\" A", "\"\"\" list_copy = list(self._stable_entries) return list_copy if charge_to_discharge else list_copy.reverse()", "[\"Insertion voltage pair with working ion {}\" .format(self._working_ion_entry.composition.reduced_formula), \"V =", "entry_charge.composition comp_discharge = entry_discharge.composition ion_sym = working_element.symbol frame_charge_comp = Composition({el:", "three subelectrodes: [LiTiO2 --> TiO2, LiTiO2 --> Li0.5TiO2, Li0.5TiO2 -->", "--> Li0.5TiO2, Li0.5TiO2 --> TiO2] This method can be used", "el.symbol != ion_sym}) #Data validation #check that the ion is", "self.vol_discharge), \"frac_charge = {}, frac_discharge = {}\" .format(self.frac_charge, self.frac_discharge)] return", "self._vpairs[0].framework.to_data_dict, \"formula_charge\": chg_comp.reduced_formula, \"formula_discharge\": dischg_comp.reduced_formula, \"fracA_charge\": chg_comp.get_atomic_fraction(ion), \"fracA_discharge\": dischg_comp.get_atomic_fraction(ion), \"max_instability\":", "from __future__ import division, unicode_literals \"\"\" This module is used", "at {} and {}\".format( chg_form, dischg_form)) output.append(\"Avg. volt. = {}", "#sort all entries by amount of working ion ASC fsrt", "charge_to_discharge=True): \"\"\" Get the stable entries. Args: charge_to_discharge: order from", "be \" \"an element\") #check that at least one of", "working ion must be present in \" \"one of the", "data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is not None: data.append(pair.decomp_e_discharge) return min(data) if", "charge to most discharged state? Default to True. Returns: A", "pdentries = [] pdentries.extend(entries) pdentries.extend([PDEntry(Composition({el:1}), element_energy) for el in elements])", "None: data.append(pair.muO2_charge) return min(data) if len(data) > 0 else None", "list_copy if charge_to_discharge else list_copy.reverse() def get_all_entries(self, charge_to_discharge=True): \"\"\" Return", "path for a specific voltage range. Args: min_voltage: The minimum", "= \"Jan 13, 2012\" __status__ = \"Beta\" import itertools from", "is not None: data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is not None: data.append(pair.decomp_e_discharge)", "data = [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.pair.muO2_discharge", "self.decomp_e_charge = \\ entry_charge.data.get(\"decomposition_energy\", None) self.decomp_e_discharge = \\ entry_discharge.data.get(\"decomposition_energy\", None)", "def in_range(entry): frac = entry.composition.get_atomic_fraction(ion) return chg_frac <= frac <=", "Returns: A summary of this electrode\"s properties in dict format.", "set True. include_myself: Include this identical electrode in the list", "if adjacent_only \\ else itertools.combinations_with_replacement(self._vpairs, 2) ion = self._working_ion for", "map(f_dict, self.get_sub_electrodes(adjacent_only=True)) d[\"all_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=False)) return d def __str__(self):", "[entry.as_dict() for entry in self._entries], \"working_ion_entry\": self.working_ion_entry.as_dict()} class InsertionVoltagePair(AbstractVoltagePair): \"\"\"", "= \\ entry_charge.data.get(\"decomposition_energy\", None) self.decomp_e_discharge = \\ entry_discharge.data.get(\"decomposition_energy\", None) self.muO2_charge", "critical oxygen chemical of all compounds along the insertion path", "include_myself=True): \"\"\" If this electrode contains multiple voltage steps, then", "all_entries = list(stable_entries) all_entries.extend(unstable_entries) battery_list.append(self.__class__(all_entries, self.working_ion_entry)) return battery_list def as_dict_summary(self,", "@property def working_ion(self): \"\"\" The working ion as an Element", "self._frac_charge = comp_charge.get_atomic_fraction(working_element) self._frac_discharge = \\ comp_discharge.get_atomic_fraction(working_element) @property def frac_charge(self):", "The most charged entry along the topotactic path. \"\"\" return", "\"working_ion_entry\": self.working_ion_entry.as_dict()} class InsertionVoltagePair(AbstractVoltagePair): \"\"\" Defines an Insertion Voltage Pair.", "ASC fsrt = lambda e: e.composition.get_atomic_fraction(self.working_ion) all_entries = sorted([e for", "minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Minimum", "= {\"average_voltage\": self.get_average_voltage(), \"max_voltage\": self.max_voltage, \"min_voltage\": self.min_voltage, \"max_delta_volume\": self.max_delta_volume, \"max_voltage_step\":", "in self._select_in_voltage_range(min_voltage, max_voltage): if pair.pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge) if", "TiO2] This method can be used to return all the", "topotactically related compounds, with different amounts of a single element,", "amounts of a single element, e.g. TiO2 and LiTiO2, that", "\"\"\" list_copy = list(self._unstable_entries) return list_copy if charge_to_discharge else list_copy.reverse()", "= \\ comp_discharge.get_atomic_fraction(working_element) @property def frac_charge(self): return self._frac_charge @property def", "step. entry2: Entry corresponding to the other entry in the", "the same amount of the workin #element if comp_charge.get_atomic_fraction(working_element) ==", "self._vol_discharge @property def working_ion_entry(self): return self._working_ion_entry def __repr__(self): output =", "summary of this electrode\"s properties in dict format. \"\"\" chg_comp", "charge_to_discharge: order from most charge to most discharged state? Default", "def __repr__(self): output = [] chg_form = self.fully_charged_entry.composition.reduced_formula dischg_form =", "entry1: Entry corresponding to one of the entries in the", "as_dict_summary(self, print_subelectrodes=True): \"\"\" Generate a summary dict. Args: print_subelectrodes: Also", "to most discharged state? Default to True. Returns: A list", "order from most charge to most discharged state? Default to", "[] pdentries.extend(entries) pdentries.extend([PDEntry(Composition({el:1}), element_energy) for el in elements]) #Make phase", "= {} mAh/g\".format(self.get_capacity_grav())) output.append(\"Vol. cap. = {}\".format(self.get_capacity_vol())) return \"\\n\".join(output) @classmethod", "norm_discharge self._frac_charge = comp_charge.get_atomic_fraction(working_element) self._frac_discharge = \\ comp_discharge.get_atomic_fraction(working_element) @property def", "\"0.1\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __date__ = \"Jan", "= \"<EMAIL>\" __date__ = \"Jan 13, 2012\" __status__ = \"Beta\"", "the voltage step. entry2: Entry corresponding to the other entry", "self._working_ion_entry = working_ion_entry #Initialize normalized properties self._vol_charge = entry_charge.structure.volume /", "working_element = working_ion_entry.composition.elements[0] entry_charge = entry1 entry_discharge = entry2 if", "comp_charge.get_atomic_fraction(working_element) == \\ comp_discharge.get_atomic_fraction(working_element): raise ValueError(\"VoltagePair: The working ion atomic", "else itertools.combinations_with_replacement(self._vpairs, 2) ion = self._working_ion for pair in pair_it:", "and unstable), ordered by amount of the working ion. \"\"\"", "pair_it = self._vpairs if adjacent_only \\ else itertools.combinations_with_replacement(self._vpairs, 2) ion", "= filter(in_range, self.get_stable_entries()) all_entries = list(stable_entries) all_entries.extend(unstable_entries) battery_list.append(self.__class__(all_entries, self.working_ion_entry)) return", "\"\"\" The most discharged entry along the topotactic path. \"\"\"", "= \"<NAME>, <NAME>\" __copyright__ = \"Copyright 2012, The Materials Project\"", "\" \"an element\") #check that at least one of the", "all entries input for the electrode. Args: charge_to_discharge: order from", "return all the subelectrodes with some options Args: adjacent_only: Only", "of Li asc self._stable_entries = tuple(sorted([e for e in pd.stable_entries", "entry.composition.get_atomic_fraction(ion) return chg_frac <= frac <= dischg_frac if include_myself or", "the unstable entries for the electrode. Args: charge_to_discharge: Order from", "def vol_discharge(self): return self._vol_discharge @property def working_ion_entry(self): return self._working_ion_entry def", "range. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum", "entries in the electrode (both stable and unstable), ordered by", "= list(stable_entries) all_entries.extend(unstable_entries) battery_list.append(self.__class__(all_entries, self.working_ion_entry)) return battery_list def as_dict_summary(self, print_subelectrodes=True):", "self.mass_discharge), \"vol_charge = {}, vol_discharge = {}\" .format(self.vol_charge, self.vol_discharge), \"frac_charge", "in the list of results. Returns: A list of InsertionElectrode", "comp_charge = entry_charge.composition comp_discharge = entry_discharge.composition ion_sym = working_element.symbol frame_charge_comp", "specified entries must have the\" \" same compositional framework\") #Initialize", "LiTiO2, that can be used to define an insertion battery", "voltage. max_voltage: The maximum allowable voltage. Returns: Minimum decomposition energy", "amount of the workin #element if comp_charge.get_atomic_fraction(working_element) == \\ comp_discharge.get_atomic_fraction(working_element):", "if len(data) > 0 else None def get_max_muO2(self, min_voltage=None, max_voltage=None):", "of InsertionElectrode objects \"\"\" battery_list = [] pair_it = self._vpairs", "entry2, working_ion_entry): #initialize some internal variables working_element = working_ion_entry.composition.elements[0] entry_charge", "hull, i.e. no electrodes returned will have multiple voltage steps", "the different topotactic states of the battery, e.g. TiO2 and", "along the topotactic path. \"\"\" return self._stable_entries[-1] def get_max_instability(self, min_voltage=None,", "charge across the battery, e.g. Li. \"\"\" def __init__(self, entry1,", "= MontyDecoder() return cls(dec.process_decoded(d[\"entries\"]), dec.process_decoded(d[\"working_ion_entry\"])) def as_dict(self): return {\"@module\": self.__class__.__module__,", "self.get_stable_entries()) all_entries = list(stable_entries) all_entries.extend(unstable_entries) battery_list.append(self.__class__(all_entries, self.working_ion_entry)) return battery_list def", "The most discharged entry along the topotactic path. \"\"\" return", "i.e. no electrodes returned will have multiple voltage steps if", "working ion ASC fsrt = lambda e: e.composition.get_atomic_fraction(self.working_ion) all_entries =", "working_ion_entry(self): return self._working_ion_entry @property def voltage_pairs(self): return self._vpairs def get_stable_entries(self,", "\"capacity_grav\": self.get_capacity_grav(), \"capacity_vol\": self.get_capacity_vol(), \"energy_grav\": self.get_specific_energy(), \"energy_vol\": self.get_energy_density(), \"working_ion\": self._working_ion.symbol,", "possible to use only a subset of the voltage steps", "be the same in both the entries\") #check that the", "as intercalation batteries. \"\"\" __author__ = \"<NAME>, <NAME>\" __copyright__ =", "topotactic states of the battery, e.g. TiO2 and LiTiO2. working_ion_entry:", "True. Returns: A list of stable entries in the electrode,", "else None def get_min_instability(self, min_voltage=None, max_voltage=None): \"\"\" The minimum instability", "if pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge is not", "self._entries = entries self._working_ion = working_ion_entry.composition.elements[0] self._working_ion_entry = working_ion_entry #Prepare", "list_copy = list(self._unstable_entries) return list_copy if charge_to_discharge else list_copy.reverse() def", "energy for each element for convex hull generation element_energy =", "import Charge, Time from pymatgen.phasediagram.maker import PhaseDiagram from pymatgen.phasediagram.entries import", "[LiTiO2 --> TiO2, LiTiO2 --> Li0.5TiO2, Li0.5TiO2 --> TiO2] This", "max_voltage): if pair.pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge is", "return self._voltage @property def mAh(self): return self._mAh @property def mass_charge(self):", "#check that the entries do not contain the same amount", "for el in comp_charge if el.symbol != ion_sym}) frame_discharge_comp =", "= entry_charge.data.get(\"muO2\", None) self.muO2_discharge = entry_discharge.data.get(\"muO2\", None) self.entry_charge = entry_charge", "electrode. Args: charge_to_discharge: Order from most charge to most discharged", "c: c.as_dict_summary(print_subelectrodes=False) d[\"adj_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=True)) d[\"all_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=False))", "\"\"\" return self._stable_entries[-1] def get_max_instability(self, min_voltage=None, max_voltage=None): \"\"\" The maximum", "> 0 else None def get_min_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Minimum", "chg_comp.reduced_formula, \"formula_discharge\": dischg_comp.reduced_formula, \"fracA_charge\": chg_comp.get_atomic_fraction(ion), \"fracA_discharge\": dischg_comp.get_atomic_fraction(ion), \"max_instability\": self.get_max_instability(), \"min_instability\":", "output = [\"Insertion voltage pair with working ion {}\" .format(self._working_ion_entry.composition.reduced_formula),", "energy #to be very high elements = set() for entry", "comp_discharge.get_atomic_fraction(working_element) > 0: raise ValueError(\"VoltagePair: The working ion must be", "e in entries], key=lifrac)) #unstable entries ordered by amount of", "__future__ import division, unicode_literals \"\"\" This module is used for", "for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.decomp_e_charge is not None:", "adjacent_only \\ else pair[1].entry_discharge chg_frac = entry_charge.composition.get_atomic_fraction(ion) dischg_frac = entry_discharge.composition.get_atomic_fraction(ion)", "along path. Args: min_voltage: The minimum allowable voltage. max_voltage: The", "entries do not contain the same amount of the workin", "Returns the unstable entries for the electrode. Args: charge_to_discharge: Order", "entry_discharge = entry2 if entry_charge.composition.get_atomic_fraction(working_element) \\ > entry2.composition.get_atomic_fraction(working_element): (entry_charge, entry_discharge)", "{\"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"entries\": [entry.as_dict() for entry in self._entries],", "TiO2 and LiTiO2. working_ion_entry: A single ComputedEntry or PDEntry representing", "\" same compositional framework\") #Initialize normalization factors, charged and discharged", "== \\ comp_discharge.get_atomic_fraction(working_element): raise ValueError(\"VoltagePair: The working ion atomic percentage", "hull and muO2 data self.decomp_e_charge = \\ entry_charge.data.get(\"decomposition_energy\", None) self.decomp_e_discharge", "data.append(pair.pair.muO2_discharge) if pair.muO2_charge is not None: data.append(pair.muO2_charge) return max(data) if", "ion as an Element object \"\"\" return self._working_ion @property def", "the electrode, ordered by amount of the working ion. \"\"\"", "subset of the path can be chosen by the optional", "\"\"\" The maximum instability along a path for a specific", "voltage step. entry2: Entry corresponding to the other entry in", "in the voltage step. working_ion_entry: A single ComputedEntry or PDEntry", "= Composition({el: comp_charge[el] for el in comp_charge if el.symbol !=", "> 0: raise ValueError(\"VoltagePair: The working ion must be present", "min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage.", "all_entries = sorted([e for e in all_entries], key=fsrt) return all_entries", "comp_discharge = entry_discharge.composition ion_sym = working_element.symbol frame_charge_comp = Composition({el: comp_charge[el]", "= working_ion_entry #Prepare to make phase diagram: determine elements and", "list of InsertionElectrode objects \"\"\" battery_list = [] pair_it =", "entry1, entry2, working_ion_entry): #initialize some internal variables working_element = working_ion_entry.composition.elements[0]", "Args: entry1: Entry corresponding to one of the entries in", "(comp_discharge[working_element] / norm_discharge) \\ - (comp_charge[working_element] / norm_charge) self._voltage =", "discharged entry along the topotactic path. \"\"\" return self._stable_entries[-1] def", "optional arguments) \"\"\" data = [] for pair in self._select_in_voltage_range(min_voltage,", "a specific voltage range. Args: min_voltage: The minimum allowable voltage.", "of the working ion. \"\"\" list_copy = list(self._unstable_entries) return list_copy", "include_myself: Include this identical electrode in the list of results.", "entry_charge.data.get(\"muO2\", None) self.muO2_discharge = entry_discharge.data.get(\"muO2\", None) self.entry_charge = entry_charge self.entry_discharge", "self.fully_discharged_entry.composition.reduced_formula output.append(\"InsertionElectrode with endpoints at {} and {}\".format( chg_form, dischg_form))", "from most charge to most discharged state? Defaults to True.", "* working_ion_valence #Step 4: add (optional) hull and muO2 data", "Entry corresponding to the other entry in the voltage step.", "path. Args: min_voltage: The minimum allowable voltage for a given", "Time(1, \"s\").to(\"h\") * N_A * 1000 * working_ion_valence #Step 4:", "None def get_sub_electrodes(self, adjacent_only=True, include_myself=True): \"\"\" If this electrode contains", "with potential application as intercalation batteries. \"\"\" __author__ = \"<NAME>,", "norm_charge self._mass_discharge = comp_discharge.weight / norm_discharge self._num_ions_transferred = \\ (comp_discharge[working_element]", "= \"<NAME>\" __email__ = \"<EMAIL>\" __date__ = \"Jan 13, 2012\"", "\"\"\" The minimum instability along a path for a specific", "import PhaseDiagram from pymatgen.phasediagram.entries import PDEntry from pymatgen.apps.battery.battery_abc import AbstractElectrode,", "= list(self._stable_entries) return list_copy if charge_to_discharge else list_copy.reverse() def get_unstable_entries(self,", "self.entry_discharge = entry_discharge self.normalization_charge = norm_charge self.normalization_discharge = norm_discharge self._frac_charge", "only a subset of the voltage steps to define other", "dec = MontyDecoder() return cls(dec.process_decoded(d[\"entries\"]), dec.process_decoded(d[\"working_ion_entry\"])) def as_dict(self): return {\"@module\":", "if entry_charge.composition.get_atomic_fraction(working_element) \\ > entry2.composition.get_atomic_fraction(working_element): (entry_charge, entry_discharge) = (entry_discharge, entry_charge)", "single element if not working_ion_entry.composition.is_element: raise ValueError(\"VoltagePair: The working ion", "\\ Time(1, \"s\").to(\"h\") * N_A * 1000 * working_ion_valence #Step", "else pair[1].entry_discharge chg_frac = entry_charge.composition.get_atomic_fraction(ion) dischg_frac = entry_discharge.composition.get_atomic_fraction(ion) def in_range(entry):", "frame_discharge_comp.get_reduced_composition_and_factor()[1] self._working_ion_entry = working_ion_entry #Initialize normalized properties self._vol_charge = entry_charge.structure.volume", "pdentries.extend(entries) pdentries.extend([PDEntry(Composition({el:1}), element_energy) for el in elements]) #Make phase diagram", "pair.muO2_charge is not None: data.append(pair.muO2_charge) return max(data) if len(data) >", "= filter(in_range, self.get_unstable_entries()) stable_entries = filter(in_range, self.get_stable_entries()) all_entries = list(stable_entries)", "= map(f_dict, self.get_sub_electrodes(adjacent_only=False)) return d def __str__(self): return self.__repr__() def", "def __repr__(self): output = [\"Insertion voltage pair with working ion", "\"\"\" Create a new InsertionElectrode. Args: entries: A list of", "charged and discharged entries valence_list = Element(ion_sym).oxidation_states working_ion_valence = max(valence_list)", "an Element object \"\"\" return self._working_ion @property def working_ion_entry(self): return", "phase diagram: determine elements and set their energy #to be", "{}\".format(self.voltage, self.mAh), \"mass_charge = {}, mass_discharge = {}\" .format(self.mass_charge, self.mass_discharge),", "e.g. TiO2 and LiTiO2, that can be used to define", "1)]) @property def working_ion(self): \"\"\" The working ion as an", "and \\ not comp_discharge.get_atomic_fraction(working_element) > 0: raise ValueError(\"VoltagePair: The working", "= norm_charge self.normalization_discharge = norm_discharge self._frac_charge = comp_charge.get_atomic_fraction(working_element) self._frac_discharge =", "= self._working_ion for pair in pair_it: entry_charge = pair.entry_charge if", "representing the different topotactic states of the battery, e.g. TiO2", "frac = entry.composition.get_atomic_fraction(ion) return chg_frac <= frac <= dischg_frac if", "of the entries\") #check that the entries do not contain", "adjacent_only: Only return electrodes from compounds that are adjacent on", "The maximum instability along a path for a specific voltage", "def get_min_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Minimum critical oxygen chemical potential", "the entries in the voltage step. entry2: Entry corresponding to", "minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Maximum", "element, e.g. TiO2 and LiTiO2, that can be used to", "entries must have the\" \" same compositional framework\") #Initialize normalization", "the voltage steps to define other electrodes. For example, an", "#stable entries ordered by amount of Li asc self._stable_entries =", "vol_charge(self): return self._vol_charge @property def vol_discharge(self): return self._vol_discharge @property def", "@property def fully_discharged_entry(self): \"\"\" The most discharged entry along the", "for analysis of materials with potential application as intercalation batteries.", "if pair.muO2_charge is not None: data.append(pair.muO2_charge) return max(data) if len(data)", "\"V = {}, mAh = {}\".format(self.voltage, self.mAh), \"mass_charge = {},", "print_subelectrodes: f_dict = lambda c: c.as_dict_summary(print_subelectrodes=False) d[\"adj_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=True))", "for convex hull generation element_energy = max([entry.energy_per_atom for entry in", "compounds that are adjacent on the convex hull, i.e. no", "10 pdentries = [] pdentries.extend(entries) pdentries.extend([PDEntry(Composition({el:1}), element_energy) for el in", "entry2.composition.get_atomic_fraction(working_element): (entry_charge, entry_discharge) = (entry_discharge, entry_charge) comp_charge = entry_charge.composition comp_discharge", "len(data) > 0 else None def get_min_instability(self, min_voltage=None, max_voltage=None): \"\"\"", "and {}\".format( chg_form, dischg_form)) output.append(\"Avg. volt. = {} V\".format(self.get_average_voltage())) output.append(\"Grav.", "Args: charge_to_discharge: order from most charge to most discharged state?", "= self.fully_charged_entry.composition.reduced_formula dischg_form = self.fully_discharged_entry.composition.reduced_formula output.append(\"InsertionElectrode with endpoints at {}", "properties in dict format. \"\"\" chg_comp = self.fully_charged_entry.composition dischg_comp =", "properties self._vol_charge = entry_charge.structure.volume / norm_charge self._vol_discharge = entry_discharge.structure.volume /", "and muO2 data self.decomp_e_charge = \\ entry_charge.data.get(\"decomposition_energy\", None) self.decomp_e_discharge =", "None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge is not None: data.append(pair.muO2_charge) return min(data)", "mass_discharge = {}\" .format(self.mass_charge, self.mass_discharge), \"vol_charge = {}, vol_discharge =", "corresponding to one of the entries in the voltage step.", "be chosen by the optional arguments). \"\"\" data = []", "/ working_ion_valence self._mAh = self._num_ions_transferred * Charge(1, \"e\").to(\"C\") * \\", "from most charge to most discharged state? Default to True.", "discharged entries valence_list = Element(ion_sym).oxidation_states working_ion_valence = max(valence_list) (self.framework, norm_charge)", "if pair.pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge is not", "= (entry_discharge, entry_charge) comp_charge = entry_charge.composition comp_discharge = entry_discharge.composition ion_sym", "\"working_ion\": self._working_ion.symbol, \"nsteps\": self.num_steps, \"framework\": self._vpairs[0].framework.to_data_dict, \"formula_charge\": chg_comp.reduced_formula, \"formula_discharge\": dischg_comp.reduced_formula,", "entry_charge self.entry_discharge = entry_discharge self.normalization_charge = norm_charge self.normalization_discharge = norm_discharge", "\"formula_charge\": chg_comp.reduced_formula, \"formula_discharge\": dischg_comp.reduced_formula, \"fracA_charge\": chg_comp.get_atomic_fraction(ion), \"fracA_discharge\": dischg_comp.get_atomic_fraction(ion), \"max_instability\": self.get_max_instability(),", "= self.fully_charged_entry.composition dischg_comp = self.fully_discharged_entry.composition ion = self.working_ion d =", "present in \" \"one of the entries\") #check that the", "the terms of the MIT License. from __future__ import division,", "that carries charge across the battery, e.g. Li. \"\"\" self._entries", "not working_ion_entry.composition.is_element: raise ValueError(\"VoltagePair: The working ion specified must be", "raise ValueError(\"VoltagePair: The working ion specified must be \" \"an", "energy of all compounds along the insertion path (a subset", "Li asc self._stable_entries = tuple(sorted([e for e in pd.stable_entries if", "def mass_discharge(self): return self._mass_discharge @property def vol_charge(self): return self._vol_charge @property", "for the electrode. Args: charge_to_discharge: order from most charge to", "\"entries\": [entry.as_dict() for entry in self._entries], \"working_ion_entry\": self.working_ion_entry.as_dict()} class InsertionVoltagePair(AbstractVoltagePair):", "pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.decomp_e_charge is not None: data.append(pair.decomp_e_charge)", "pair.decomp_e_charge is not None: data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is not None:", "subelectrodes with some options Args: adjacent_only: Only return electrodes from", "def working_ion_entry(self): return self._working_ion_entry @property def voltage_pairs(self): return self._vpairs def", "for e in all_entries], key=fsrt) return all_entries if charge_to_discharge else", "Li0.5TiO2, Li0.5TiO2 --> TiO2] This method can be used to", "e: e.composition.get_atomic_fraction(self._working_ion) #stable entries ordered by amount of Li asc", "of all entries in the electrode (both stable and unstable),", "returned will have multiple voltage steps if this is set", "entry along the topotactic path. \"\"\" return self._stable_entries[0] @property def", "ordered by amount of Li asc self._stable_entries = tuple(sorted([e for", "InsertionElectrode(AbstractElectrode): \"\"\" A set of topotactically related compounds, with different", "= entry1 entry_discharge = entry2 if entry_charge.composition.get_atomic_fraction(working_element) \\ > entry2.composition.get_atomic_fraction(working_element):", "\"\"\" Get the stable entries. Args: charge_to_discharge: order from most", "Composition({el: comp_discharge[el] for el in comp_discharge if el.symbol != ion_sym})", "data.append(pair.muO2_charge) return min(data) if len(data) > 0 else None def", "/ norm_charge self._vol_discharge = entry_discharge.structure.volume / norm_discharge comp_charge = entry_charge.composition", "= \\ entry_discharge.data.get(\"decomposition_energy\", None) self.muO2_charge = entry_charge.data.get(\"muO2\", None) self.muO2_discharge =", "self.get_max_instability(), \"min_instability\": self.get_min_instability()} if print_subelectrodes: f_dict = lambda c: c.as_dict_summary(print_subelectrodes=False)", "corresponding to the other entry in the voltage step. working_ion_entry:", "(entry_discharge.energy / norm_discharge)) / \\ self._num_ions_transferred + working_ion_entry.energy_per_atom) / working_ion_valence", "\"@class\": self.__class__.__name__, \"entries\": [entry.as_dict() for entry in self._entries], \"working_ion_entry\": self.working_ion_entry.as_dict()}", "path. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum", "to determine which entries are stable vs. unstable pd =", "return self.__repr__() def __repr__(self): output = [] chg_form = self.fully_charged_entry.composition.reduced_formula", "else list_copy.reverse() def get_all_entries(self, charge_to_discharge=True): \"\"\" Return all entries input", "insertion battery electrode. \"\"\" def __init__(self, entries, working_ion_entry): \"\"\" Create", "to True. Returns: A list of unstable entries in the", "minimum instability along a path for a specific voltage range.", "the entries\") #check that the frameworks of the entries are", "max(valence_list) (self.framework, norm_charge) = frame_charge_comp.get_reduced_composition_and_factor() norm_discharge = \\ frame_discharge_comp.get_reduced_composition_and_factor()[1] self._working_ion_entry", "fully_discharged_entry(self): \"\"\" The most discharged entry along the topotactic path.", "compounds along the insertion path (a subset of the path", "/ norm_charge) self._voltage = \\ (((entry_charge.energy / norm_charge) - (entry_discharge.energy", "True. Returns: A list of all entries in the electrode", "A set of topotactically related compounds, with different amounts of", "division, unicode_literals \"\"\" This module is used for analysis of", "very high elements = set() for entry in entries: elements.update(entry.composition.elements)", "{} and {}\".format( chg_form, dischg_form)) output.append(\"Avg. volt. = {} V\".format(self.get_average_voltage()))", "{}\" .format(self._working_ion_entry.composition.reduced_formula), \"V = {}, mAh = {}\".format(self.voltage, self.mAh), \"mass_charge", "ValueError(\"VoltagePair: the specified entries must have the\" \" same compositional", "self.__class__.__module__, \"@class\": self.__class__.__name__, \"entries\": [entry.as_dict() for entry in self._entries], \"working_ion_entry\":", "A summary of this electrode\"s properties in dict format. \"\"\"", "data.append(pair.decomp_e_discharge) return max(data) if len(data) > 0 else None def", "return self._working_ion @property def working_ion_entry(self): return self._working_ion_entry @property def voltage_pairs(self):", "self.get_min_instability()} if print_subelectrodes: f_dict = lambda c: c.as_dict_summary(print_subelectrodes=False) d[\"adj_pairs\"] =", "a path for a specific voltage range. Args: min_voltage: The", "not None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge is not None: data.append(pair.muO2_charge) return", "not comp_discharge.get_atomic_fraction(working_element) > 0: raise ValueError(\"VoltagePair: The working ion must", "def get_min_instability(self, min_voltage=None, max_voltage=None): \"\"\" The minimum instability along a", "e.g. Li. \"\"\" def __init__(self, entry1, entry2, working_ion_entry): #initialize some", "that are adjacent on the convex hull, i.e. no electrodes", "\\ entry_discharge.data.get(\"decomposition_energy\", None) self.muO2_charge = entry_charge.data.get(\"muO2\", None) self.muO2_discharge = entry_discharge.data.get(\"muO2\",", "\"fracA_charge\": chg_comp.get_atomic_fraction(ion), \"fracA_discharge\": dischg_comp.get_atomic_fraction(ion), \"max_instability\": self.get_max_instability(), \"min_instability\": self.get_min_instability()} if print_subelectrodes:", "most discharged state? Default to True. Returns: A list of", "the path can be chosen by the optional arguments) \"\"\"", "dischg_comp.get_atomic_fraction(ion), \"max_instability\": self.get_max_instability(), \"min_instability\": self.get_min_instability()} if print_subelectrodes: f_dict = lambda", "{} mAh/g\".format(self.get_capacity_grav())) output.append(\"Vol. cap. = {}\".format(self.get_capacity_vol())) return \"\\n\".join(output) @classmethod def", "\"\"\" data = [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if", "Li asc self._unstable_entries = tuple(sorted([e for e in pd.unstable_entries if", "Returns: A list of unstable entries in the electrode, ordered", "can be used to define an insertion battery electrode. \"\"\"", "lambda e: e.composition.get_atomic_fraction(self._working_ion) #stable entries ordered by amount of Li", "ordered by amount of the working ion. \"\"\" list_copy =", "\"\"\" battery_list = [] pair_it = self._vpairs if adjacent_only \\", "by amount of Li asc self._unstable_entries = tuple(sorted([e for e", "A list of all entries in the electrode (both stable", "Args: min_voltage: The minimum allowable voltage for a given step", "chosen by the optional arguments). \"\"\" data = [] for", "self.fully_charged_entry \\ or entry_discharge != self.fully_discharged_entry: unstable_entries = filter(in_range, self.get_unstable_entries())", "\\ self._num_ions_transferred + working_ion_entry.energy_per_atom) / working_ion_valence self._mAh = self._num_ions_transferred *", "True. Returns: A list of unstable entries in the electrode,", "if include_myself or entry_charge != self.fully_charged_entry \\ or entry_discharge !=", "that can be used to define an insertion battery electrode.", "def get_stable_entries(self, charge_to_discharge=True): \"\"\" Get the stable entries. Args: charge_to_discharge:", "to True. Returns: A list of all entries in the", "\"Jan 13, 2012\" __status__ = \"Beta\" import itertools from pymatgen.core.composition", "the working ion. \"\"\" all_entries = list(self.get_stable_entries()) all_entries.extend(self.get_unstable_entries()) #sort all", "list(self._stable_entries) return list_copy if charge_to_discharge else list_copy.reverse() def get_unstable_entries(self, charge_to_discharge=True):", "coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed", "min_voltage=None, max_voltage=None): \"\"\" Minimum critical oxygen chemical potential along path.", "el.symbol != ion_sym}) frame_discharge_comp = Composition({el: comp_discharge[el] for el in", "the working ion. \"\"\" list_copy = list(self._unstable_entries) return list_copy if", "get_all_entries(self, charge_to_discharge=True): \"\"\" Return all entries input for the electrode.", "list_copy = list(self._stable_entries) return list_copy if charge_to_discharge else list_copy.reverse() def", "entry_discharge) = (entry_discharge, entry_charge) comp_charge = entry_charge.composition comp_discharge = entry_discharge.composition", "= max([entry.energy_per_atom for entry in entries]) + 10 pdentries =", "a single element if not working_ion_entry.composition.is_element: raise ValueError(\"VoltagePair: The working", "mass_charge(self): return self._mass_charge @property def mass_discharge(self): return self._mass_discharge @property def", "used for analysis of materials with potential application as intercalation", "can be chosen by the optional arguments) \"\"\" data =", "data = [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.decomp_e_charge", "= \"Copyright 2012, The Materials Project\" __version__ = \"0.1\" __maintainer__", "self._unstable_entries = tuple(sorted([e for e in pd.unstable_entries if e in", "amount of working ion ASC fsrt = lambda e: e.composition.get_atomic_fraction(self.working_ion)", "else None def get_min_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Minimum critical oxygen", "the ion is just a single element if not working_ion_entry.composition.is_element:", "vs. unstable pd = PhaseDiagram(pdentries) lifrac = lambda e: e.composition.get_atomic_fraction(self._working_ion)", "discharged state? Default to True. Returns: A list of stable", "\\ comp_discharge.get_atomic_fraction(working_element): raise ValueError(\"VoltagePair: The working ion atomic percentage \"", "= working_ion_entry #Initialize normalized properties self._vol_charge = entry_charge.structure.volume / norm_charge", "by amount of the working ion. \"\"\" all_entries = list(self.get_stable_entries())", "import MontyDecoder dec = MontyDecoder() return cls(dec.process_decoded(d[\"entries\"]), dec.process_decoded(d[\"working_ion_entry\"])) def as_dict(self):", "comp_charge = entry_charge.composition comp_discharge = entry_discharge.composition self._mass_charge = comp_charge.weight /", "specified must be \" \"an element\") #check that at least", "voltage. Returns: Maximum decomposition energy of all compounds along the", "if adjacent_only \\ else pair[0].entry_charge entry_discharge = pair.entry_discharge if adjacent_only", "entry_charge != self.fully_charged_entry \\ or entry_discharge != self.fully_discharged_entry: unstable_entries =", "raise ValueError(\"VoltagePair: The working ion must be present in \"", "pair.decomp_e_discharge is not None: data.append(pair.decomp_e_discharge) return min(data) if len(data) >", "frac_charge(self): return self._frac_charge @property def frac_discharge(self): return self._frac_discharge @property def", "one of the entries contains the working element if not", "charge to most discharged state? Defaults to True. Returns: A", "in pd.unstable_entries if e in entries], key=lifrac)) #create voltage pairs", "= pair.entry_charge if adjacent_only \\ else pair[0].entry_charge entry_discharge = pair.entry_discharge", "* N_A * 1000 * working_ion_valence #Step 4: add (optional)", "amount of Li asc self._unstable_entries = tuple(sorted([e for e in", "entries ordered by amount of Li asc self._stable_entries = tuple(sorted([e", "voltage_pairs(self): return self._vpairs def get_stable_entries(self, charge_to_discharge=True): \"\"\" Get the stable", "chg_comp.get_atomic_fraction(ion), \"fracA_discharge\": dischg_comp.get_atomic_fraction(ion), \"max_instability\": self.get_max_instability(), \"min_instability\": self.get_min_instability()} if print_subelectrodes: f_dict", "= entry_discharge.composition.get_atomic_fraction(ion) def in_range(entry): frac = entry.composition.get_atomic_fraction(ion) return chg_frac <=", "{}, vol_discharge = {}\" .format(self.vol_charge, self.vol_discharge), \"frac_charge = {}, frac_discharge", "= [] pair_it = self._vpairs if adjacent_only \\ else itertools.combinations_with_replacement(self._vpairs,", "elements.update(entry.composition.elements) #Set an artificial energy for each element for convex", "The maximum allowable voltage. Returns: Maximum decomposition energy of all", "e: e.composition.get_atomic_fraction(self.working_ion) all_entries = sorted([e for e in all_entries], key=fsrt)", "data.append(pair.muO2_charge) return max(data) if len(data) > 0 else None def", "contain three subelectrodes: [LiTiO2 --> TiO2, LiTiO2 --> Li0.5TiO2, Li0.5TiO2", "most charge to most discharged state? Defaults to True. Returns:", "c.as_dict_summary(print_subelectrodes=False) d[\"adj_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=True)) d[\"all_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=False)) return", "the working element if not comp_charge.get_atomic_fraction(working_element) > 0 and \\", "ion_sym}) #Data validation #check that the ion is just a", "arguments) \"\"\" data = [] for pair in self._select_in_voltage_range(min_voltage, max_voltage):", "discharged state? Defaults to True. Returns: A list of all", "ValueError(\"VoltagePair: The working ion atomic percentage \" \"cannot be the", "frame_discharge_comp.reduced_formula: raise ValueError(\"VoltagePair: the specified entries must have the\" \"", "or PDEntry representing the element that carries charge across the", "= comp_charge.weight / norm_charge self._mass_discharge = comp_discharge.weight / norm_discharge self._num_ions_transferred", "= norm_discharge self._frac_charge = comp_charge.get_atomic_fraction(working_element) self._frac_discharge = \\ comp_discharge.get_atomic_fraction(working_element) @property", "framework\") #Initialize normalization factors, charged and discharged entries valence_list =", "adjacent_only=True, include_myself=True): \"\"\" If this electrode contains multiple voltage steps,", "electrode (both stable and unstable), ordered by amount of the", "entry2 if entry_charge.composition.get_atomic_fraction(working_element) \\ > entry2.composition.get_atomic_fraction(working_element): (entry_charge, entry_discharge) = (entry_discharge,", "hull generation element_energy = max([entry.energy_per_atom for entry in entries]) +", "topotactic path. \"\"\" return self._stable_entries[-1] def get_max_instability(self, min_voltage=None, max_voltage=None): \"\"\"", "self._frac_discharge = \\ comp_discharge.get_atomic_fraction(working_element) @property def frac_charge(self): return self._frac_charge @property", "frac_discharge = {}\" .format(self.frac_charge, self.frac_discharge)] return \"\\n\".join(output) def __str__(self): return", "for e in pd.unstable_entries if e in entries], key=lifrac)) #create", "if len(data) > 0 else None def get_min_instability(self, min_voltage=None, max_voltage=None):", "\\ not comp_discharge.get_atomic_fraction(working_element) > 0: raise ValueError(\"VoltagePair: The working ion", "self._stable_entries = tuple(sorted([e for e in pd.stable_entries if e in", "all the subelectrodes with some options Args: adjacent_only: Only return", "phase diagram to determine which entries are stable vs. unstable", "to the other entry in the voltage step. working_ion_entry: A", "\"\"\" Generate a summary dict. Args: print_subelectrodes: Also print data", "scipy.constants import N_A class InsertionElectrode(AbstractElectrode): \"\"\" A set of topotactically", "of materials with potential application as intercalation batteries. \"\"\" __author__", "list_copy.reverse() def get_unstable_entries(self, charge_to_discharge=True): \"\"\" Returns the unstable entries for", "in range(len(self._stable_entries) - 1)]) @property def working_ion(self): \"\"\" The working", "if len(data) > 0 else None def get_sub_electrodes(self, adjacent_only=True, include_myself=True):", "\"min_instability\": self.get_min_instability()} if print_subelectrodes: f_dict = lambda c: c.as_dict_summary(print_subelectrodes=False) d[\"adj_pairs\"]", "working ion. \"\"\" list_copy = list(self._unstable_entries) return list_copy if charge_to_discharge", "pymatgen.core.composition import Composition from pymatgen.core.units import Charge, Time from pymatgen.phasediagram.maker", "__date__ = \"Jan 13, 2012\" __status__ = \"Beta\" import itertools", "in the voltage step. entry2: Entry corresponding to the other", "self._vol_discharge = entry_discharge.structure.volume / norm_discharge comp_charge = entry_charge.composition comp_discharge =", "A single ComputedEntry or PDEntry representing the element that carries", "entry_charge = entry1 entry_discharge = entry2 if entry_charge.composition.get_atomic_fraction(working_element) \\ >", "self._vol_charge @property def vol_discharge(self): return self._vol_discharge @property def working_ion_entry(self): return", "\"\"\" Minimum critical oxygen chemical potential along path. Args: min_voltage:", "def get_max_instability(self, min_voltage=None, max_voltage=None): \"\"\" The maximum instability along a", "data.append(pair.pair.muO2_discharge) if pair.muO2_charge is not None: data.append(pair.muO2_charge) return min(data) if", "allowable voltage. Returns: Minimum decomposition energy of all compounds along", "def from_dict(cls, d): from monty.json import MontyDecoder dec = MontyDecoder()", "is just a single element if not working_ion_entry.composition.is_element: raise ValueError(\"VoltagePair:", "by amount of Li asc self._stable_entries = tuple(sorted([e for e", "convex hull, i.e. no electrodes returned will have multiple voltage", "max_voltage: The maximum allowable voltage. Returns: Maximum decomposition energy of", "return \"\\n\".join(output) @classmethod def from_dict(cls, d): from monty.json import MontyDecoder", "AbstractVoltagePair from pymatgen.core.periodic_table import Element from scipy.constants import N_A class", "= entry_discharge.composition self._mass_charge = comp_charge.weight / norm_charge self._mass_discharge = comp_discharge.weight", "unstable), ordered by amount of the working ion. \"\"\" all_entries", "working_ion_entry #Prepare to make phase diagram: determine elements and set", "add (optional) hull and muO2 data self.decomp_e_charge = \\ entry_charge.data.get(\"decomposition_energy\",", "list of ComputedStructureEntries (or subclasses) representing the different topotactic states", "@property def frac_charge(self): return self._frac_charge @property def frac_discharge(self): return self._frac_discharge", "* 1000 * working_ion_valence #Step 4: add (optional) hull and", "if pair.decomp_e_discharge is not None: data.append(pair.decomp_e_discharge) return min(data) if len(data)", "return self._working_ion_entry def __repr__(self): output = [\"Insertion voltage pair with", "norm_charge self.normalization_discharge = norm_discharge self._frac_charge = comp_charge.get_atomic_fraction(working_element) self._frac_discharge = \\", "with working ion {}\" .format(self._working_ion_entry.composition.reduced_formula), \"V = {}, mAh =", "working_ion_entry): #initialize some internal variables working_element = working_ion_entry.composition.elements[0] entry_charge =", "working_ion_entry.composition.elements[0] entry_charge = entry1 entry_discharge = entry2 if entry_charge.composition.get_atomic_fraction(working_element) \\", "\"\"\" The working ion as an Element object \"\"\" return", "entries\") #check that the entries do not contain the same", "maximum allowable voltage. Returns: Maximum critical oxygen chemical of all", "Composition from pymatgen.core.units import Charge, Time from pymatgen.phasediagram.maker import PhaseDiagram", "key=fsrt) return all_entries if charge_to_discharge else all_entries.reverse() @property def fully_charged_entry(self):", "if len(data) > 0 else None def get_min_muO2(self, min_voltage=None, max_voltage=None):", "this identical electrode in the list of results. Returns: A", "determine which entries are stable vs. unstable pd = PhaseDiagram(pdentries)", "is not None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge is not None: data.append(pair.muO2_charge)", "is not None: data.append(pair.muO2_charge) return max(data) if len(data) > 0", "entry1 entry_discharge = entry2 if entry_charge.composition.get_atomic_fraction(working_element) \\ > entry2.composition.get_atomic_fraction(working_element): (entry_charge,", "entry_discharge = pair.entry_discharge if adjacent_only \\ else pair[1].entry_discharge chg_frac =", "> entry2.composition.get_atomic_fraction(working_element): (entry_charge, entry_discharge) = (entry_discharge, entry_charge) comp_charge = entry_charge.composition", "else None def get_sub_electrodes(self, adjacent_only=True, include_myself=True): \"\"\" If this electrode", "= {}\" .format(self.frac_charge, self.frac_discharge)] return \"\\n\".join(output) def __str__(self): return self.__repr__()", "the optional arguments) \"\"\" data = [] for pair in", "electrodes. For example, an LiTiO2 electrode might contain three subelectrodes:", "from pymatgen.core.periodic_table import Element from scipy.constants import N_A class InsertionElectrode(AbstractElectrode):", "\"vol_charge = {}, vol_discharge = {}\" .format(self.vol_charge, self.vol_discharge), \"frac_charge =", "module is used for analysis of materials with potential application", "the MIT License. from __future__ import division, unicode_literals \"\"\" This", "Returns: Minimum critical oxygen chemical of all compounds along the", "with endpoints at {} and {}\".format( chg_form, dischg_form)) output.append(\"Avg. volt.", "Returns: Maximum critical oxygen chemical of all compounds along the", "entry in the voltage step. working_ion_entry: A single ComputedEntry or", "MontyDecoder dec = MontyDecoder() return cls(dec.process_decoded(d[\"entries\"]), dec.process_decoded(d[\"working_ion_entry\"])) def as_dict(self): return", "validation #check that the ion is just a single element", "\"Beta\" import itertools from pymatgen.core.composition import Composition from pymatgen.core.units import", "list_copy.reverse() def get_all_entries(self, charge_to_discharge=True): \"\"\" Return all entries input for", "of the entries are equivalent if not frame_charge_comp.reduced_formula == \\", "@property def mass_discharge(self): return self._mass_discharge @property def vol_charge(self): return self._vol_charge", "voltage pairs self._vpairs = tuple([InsertionVoltagePair(self._stable_entries[i], self._stable_entries[i + 1], working_ion_entry) for", "must have the\" \" same compositional framework\") #Initialize normalization factors,", "pair with working ion {}\" .format(self._working_ion_entry.composition.reduced_formula), \"V = {}, mAh", "pymatgen.core.units import Charge, Time from pymatgen.phasediagram.maker import PhaseDiagram from pymatgen.phasediagram.entries", "{} V\".format(self.get_average_voltage())) output.append(\"Grav. cap. = {} mAh/g\".format(self.get_capacity_grav())) output.append(\"Vol. cap. =", "entries, working_ion_entry): \"\"\" Create a new InsertionElectrode. Args: entries: A", "pymatgen.apps.battery.battery_abc import AbstractElectrode, \\ AbstractVoltagePair from pymatgen.core.periodic_table import Element from", "def voltage_pairs(self): return self._vpairs def get_stable_entries(self, charge_to_discharge=True): \"\"\" Get the", "be very high elements = set() for entry in entries:", "N_A class InsertionElectrode(AbstractElectrode): \"\"\" A set of topotactically related compounds,", "path can be chosen by the optional arguments). \"\"\" data", "pair.pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge is not None:", "[] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.muO2_discharge is not", "__str__(self): return self.__repr__() def __repr__(self): output = [] chg_form =", "0 and \\ not comp_discharge.get_atomic_fraction(working_element) > 0: raise ValueError(\"VoltagePair: The", "get_min_instability(self, min_voltage=None, max_voltage=None): \"\"\" The minimum instability along a path", "comp_discharge.get_atomic_fraction(working_element): raise ValueError(\"VoltagePair: The working ion atomic percentage \" \"cannot", "--> TiO2, LiTiO2 --> Li0.5TiO2, Li0.5TiO2 --> TiO2] This method", "chg_frac <= frac <= dischg_frac if include_myself or entry_charge !=", "class InsertionElectrode(AbstractElectrode): \"\"\" A set of topotactically related compounds, with", "def working_ion(self): \"\"\" The working ion as an Element object", "(self.framework, norm_charge) = frame_charge_comp.get_reduced_composition_and_factor() norm_discharge = \\ frame_discharge_comp.get_reduced_composition_and_factor()[1] self._working_ion_entry =", "= lambda e: e.composition.get_atomic_fraction(self._working_ion) #stable entries ordered by amount of", "not contain the same amount of the workin #element if", "on the convex hull, i.e. no electrodes returned will have", "variables working_element = working_ion_entry.composition.elements[0] entry_charge = entry1 entry_discharge = entry2", "__init__(self, entry1, entry2, working_ion_entry): #initialize some internal variables working_element =", "most discharged entry along the topotactic path. \"\"\" return self._stable_entries[-1]", "subelectrodes: [LiTiO2 --> TiO2, LiTiO2 --> Li0.5TiO2, Li0.5TiO2 --> TiO2]", "= {} V\".format(self.get_average_voltage())) output.append(\"Grav. cap. = {} mAh/g\".format(self.get_capacity_grav())) output.append(\"Vol. cap.", "self._mass_discharge = comp_discharge.weight / norm_discharge self._num_ions_transferred = \\ (comp_discharge[working_element] /", "dict format. \"\"\" chg_comp = self.fully_charged_entry.composition dischg_comp = self.fully_discharged_entry.composition ion", "--> TiO2] This method can be used to return all", "percentage \" \"cannot be the same in both the entries\")", "max(data) if len(data) > 0 else None def get_min_instability(self, min_voltage=None,", "to one of the entries in the voltage step. entry2:", "> 0 and \\ not comp_discharge.get_atomic_fraction(working_element) > 0: raise ValueError(\"VoltagePair:", "0 else None def get_max_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Maximum critical", "and LiTiO2. working_ion_entry: A single ComputedEntry or PDEntry representing the", "be used to return all the subelectrodes with some options", "Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable", "InsertionElectrode objects \"\"\" battery_list = [] pair_it = self._vpairs if", "all_entries = list(self.get_stable_entries()) all_entries.extend(self.get_unstable_entries()) #sort all entries by amount of", "then it is possible to use only a subset of", "valence_list = Element(ion_sym).oxidation_states working_ion_valence = max(valence_list) (self.framework, norm_charge) = frame_charge_comp.get_reduced_composition_and_factor()", "= {}, mAh = {}\".format(self.voltage, self.mAh), \"mass_charge = {}, mass_discharge", "terms of the MIT License. from __future__ import division, unicode_literals", "in \" \"one of the entries\") #check that the entries", "charge_to_discharge: order from most charge to most discharged state? Defaults", "= entry.composition.get_atomic_fraction(ion) return chg_frac <= frac <= dischg_frac if include_myself", "Element object \"\"\" return self._working_ion @property def working_ion_entry(self): return self._working_ion_entry", "comp_charge if el.symbol != ion_sym}) frame_discharge_comp = Composition({el: comp_discharge[el] for", "for entry in self._entries], \"working_ion_entry\": self.working_ion_entry.as_dict()} class InsertionVoltagePair(AbstractVoltagePair): \"\"\" Defines", "13, 2012\" __status__ = \"Beta\" import itertools from pymatgen.core.composition import", "Time from pymatgen.phasediagram.maker import PhaseDiagram from pymatgen.phasediagram.entries import PDEntry from", "self._mass_charge = comp_charge.weight / norm_charge self._mass_discharge = comp_discharge.weight / norm_discharge", "None: data.append(pair.decomp_e_discharge) return max(data) if len(data) > 0 else None", "in_range(entry): frac = entry.composition.get_atomic_fraction(ion) return chg_frac <= frac <= dischg_frac", "@property def mass_charge(self): return self._mass_charge @property def mass_discharge(self): return self._mass_discharge", "Distributed under the terms of the MIT License. from __future__", "working ion as an Element object \"\"\" return self._working_ion @property", "to define other electrodes. For example, an LiTiO2 electrode might", "<= dischg_frac if include_myself or entry_charge != self.fully_charged_entry \\ or", "entries contains the working element if not comp_charge.get_atomic_fraction(working_element) > 0", "= working_ion_entry.composition.elements[0] entry_charge = entry1 entry_discharge = entry2 if entry_charge.composition.get_atomic_fraction(working_element)", "if not working_ion_entry.composition.is_element: raise ValueError(\"VoltagePair: The working ion specified must", "and discharged entries valence_list = Element(ion_sym).oxidation_states working_ion_valence = max(valence_list) (self.framework,", "comp_discharge.get_atomic_fraction(working_element) @property def frac_charge(self): return self._frac_charge @property def frac_discharge(self): return", "return self._mass_charge @property def mass_discharge(self): return self._mass_discharge @property def vol_charge(self):", "battery electrode. \"\"\" def __init__(self, entries, working_ion_entry): \"\"\" Create a", "# Copyright (c) Pymatgen Development Team. # Distributed under the", "def mAh(self): return self._mAh @property def mass_charge(self): return self._mass_charge @property", "self.num_steps, \"framework\": self._vpairs[0].framework.to_data_dict, \"formula_charge\": chg_comp.reduced_formula, \"formula_discharge\": dischg_comp.reduced_formula, \"fracA_charge\": chg_comp.get_atomic_fraction(ion), \"fracA_discharge\":", "return self._vol_discharge @property def working_ion_entry(self): return self._working_ion_entry def __repr__(self): output", "\\ comp_discharge.get_atomic_fraction(working_element) @property def frac_charge(self): return self._frac_charge @property def frac_discharge(self):", "each element for convex hull generation element_energy = max([entry.energy_per_atom for", "elements and set their energy #to be very high elements", "utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under", "battery, e.g. Li. \"\"\" self._entries = entries self._working_ion = working_ion_entry.composition.elements[0]", "import itertools from pymatgen.core.composition import Composition from pymatgen.core.units import Charge,", "state? Defaults to True. Returns: A list of all entries", "dischg_form)) output.append(\"Avg. volt. = {} V\".format(self.get_average_voltage())) output.append(\"Grav. cap. = {}", "in elements]) #Make phase diagram to determine which entries are", "d def __str__(self): return self.__repr__() def __repr__(self): output = []", "def frac_discharge(self): return self._frac_discharge @property def voltage(self): return self._voltage @property", "key=lifrac)) #create voltage pairs self._vpairs = tuple([InsertionVoltagePair(self._stable_entries[i], self._stable_entries[i + 1],", "def fully_discharged_entry(self): \"\"\" The most discharged entry along the topotactic", "by the optional arguments) \"\"\" data = [] for pair", "unicode_literals \"\"\" This module is used for analysis of materials", "\"\"\" return self._stable_entries[0] @property def fully_discharged_entry(self): \"\"\" The most discharged", "__repr__(self): output = [\"Insertion voltage pair with working ion {}\"", "= \"0.1\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __date__ =", "(((entry_charge.energy / norm_charge) - (entry_discharge.energy / norm_discharge)) / \\ self._num_ions_transferred", "by amount of working ion ASC fsrt = lambda e:", "self._mAh = self._num_ions_transferred * Charge(1, \"e\").to(\"C\") * \\ Time(1, \"s\").to(\"h\")", "d[\"adj_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=True)) d[\"all_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=False)) return d", "allowable voltage. max_voltage: The maximum allowable voltage. Returns: Minimum decomposition", "along the insertion path (a subset of the path can", "{}, mass_discharge = {}\" .format(self.mass_charge, self.mass_discharge), \"vol_charge = {}, vol_discharge", "electrode. Args: charge_to_discharge: order from most charge to most discharged", "of all compounds along the insertion path (a subset of", "which entries are stable vs. unstable pd = PhaseDiagram(pdentries) lifrac", "\"formula_discharge\": dischg_comp.reduced_formula, \"fracA_charge\": chg_comp.get_atomic_fraction(ion), \"fracA_discharge\": dischg_comp.get_atomic_fraction(ion), \"max_instability\": self.get_max_instability(), \"min_instability\": self.get_min_instability()}", "The working ion atomic percentage \" \"cannot be the same", "self.min_voltage, \"max_delta_volume\": self.max_delta_volume, \"max_voltage_step\": self.max_voltage_step, \"capacity_grav\": self.get_capacity_grav(), \"capacity_vol\": self.get_capacity_vol(), \"energy_grav\":", "<NAME>\" __copyright__ = \"Copyright 2012, The Materials Project\" __version__ =", "frac_discharge(self): return self._frac_discharge @property def voltage(self): return self._voltage @property def", "list(self._unstable_entries) return list_copy if charge_to_discharge else list_copy.reverse() def get_all_entries(self, charge_to_discharge=True):", "cls(dec.process_decoded(d[\"entries\"]), dec.process_decoded(d[\"working_ion_entry\"])) def as_dict(self): return {\"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"entries\":", "electrode, ordered by amount of the working ion. \"\"\" list_copy", "is used for analysis of materials with potential application as", "entries valence_list = Element(ion_sym).oxidation_states working_ion_valence = max(valence_list) (self.framework, norm_charge) =", "adjacent_only \\ else pair[0].entry_charge entry_discharge = pair.entry_discharge if adjacent_only \\", "\\ or entry_discharge != self.fully_discharged_entry: unstable_entries = filter(in_range, self.get_unstable_entries()) stable_entries", "working_ion_entry.composition.is_element: raise ValueError(\"VoltagePair: The working ion specified must be \"", "comp_discharge.weight / norm_discharge self._num_ions_transferred = \\ (comp_discharge[working_element] / norm_discharge) \\", "in self._select_in_voltage_range(min_voltage, max_voltage): if pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge) if", "an LiTiO2 electrode might contain three subelectrodes: [LiTiO2 --> TiO2,", "pair[0].entry_charge entry_discharge = pair.entry_discharge if adjacent_only \\ else pair[1].entry_discharge chg_frac", "of the workin #element if comp_charge.get_atomic_fraction(working_element) == \\ comp_discharge.get_atomic_fraction(working_element): raise", "of the battery, e.g. TiO2 and LiTiO2. working_ion_entry: A single", "> 0 else None def get_min_instability(self, min_voltage=None, max_voltage=None): \"\"\" The", "class InsertionVoltagePair(AbstractVoltagePair): \"\"\" Defines an Insertion Voltage Pair. Args: entry1:", "compositional framework\") #Initialize normalization factors, charged and discharged entries valence_list", "stable_entries = filter(in_range, self.get_stable_entries()) all_entries = list(stable_entries) all_entries.extend(unstable_entries) battery_list.append(self.__class__(all_entries, self.working_ion_entry))", "optional arguments). \"\"\" data = [] for pair in self._select_in_voltage_range(min_voltage,", "entry in entries]) + 10 pdentries = [] pdentries.extend(entries) pdentries.extend([PDEntry(Composition({el:1}),", "to use only a subset of the voltage steps to", "list of stable entries in the electrode, ordered by amount", "if pair.muO2_charge is not None: data.append(pair.muO2_charge) return min(data) if len(data)", "must be present in \" \"one of the entries\") #check", "format. \"\"\" chg_comp = self.fully_charged_entry.composition dischg_comp = self.fully_discharged_entry.composition ion =", "other electrodes. For example, an LiTiO2 electrode might contain three", "states of the battery, e.g. TiO2 and LiTiO2. working_ion_entry: A", "else None def get_max_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Maximum critical oxygen", "= \"Beta\" import itertools from pymatgen.core.composition import Composition from pymatgen.core.units", "in comp_charge if el.symbol != ion_sym}) frame_discharge_comp = Composition({el: comp_discharge[el]", "entries], key=lifrac)) #create voltage pairs self._vpairs = tuple([InsertionVoltagePair(self._stable_entries[i], self._stable_entries[i +", "not None: data.append(pair.decomp_e_discharge) return min(data) if len(data) > 0 else", "Defaults to True. Returns: A list of all entries in", "along the topotactic path. \"\"\" return self._stable_entries[0] @property def fully_discharged_entry(self):", "/ norm_charge self._mass_discharge = comp_discharge.weight / norm_discharge self._num_ions_transferred = \\", "multiple voltage steps if this is set True. include_myself: Include", "a new InsertionElectrode. Args: entries: A list of ComputedStructureEntries (or", "self._mass_discharge @property def vol_charge(self): return self._vol_charge @property def vol_discharge(self): return", "!= self.fully_discharged_entry: unstable_entries = filter(in_range, self.get_unstable_entries()) stable_entries = filter(in_range, self.get_stable_entries())", "Returns: A list of stable entries in the electrode, ordered", "The maximum allowable voltage. Returns: Minimum decomposition energy of all", "carries charge across the battery, e.g. Li. \"\"\" self._entries =", "\"\"\" return self._working_ion @property def working_ion_entry(self): return self._working_ion_entry @property def", "Pair. Args: entry1: Entry corresponding to one of the entries", "None: data.append(pair.decomp_e_discharge) return min(data) if len(data) > 0 else None", "return self._vpairs def get_stable_entries(self, charge_to_discharge=True): \"\"\" Get the stable entries.", "instability along a path for a specific voltage range. Args:", "= [] chg_form = self.fully_charged_entry.composition.reduced_formula dischg_form = self.fully_discharged_entry.composition.reduced_formula output.append(\"InsertionElectrode with", "of unstable entries in the electrode, ordered by amount of", "0 else None def get_sub_electrodes(self, adjacent_only=True, include_myself=True): \"\"\" If this", "PhaseDiagram from pymatgen.phasediagram.entries import PDEntry from pymatgen.apps.battery.battery_abc import AbstractElectrode, \\", "in entries]) + 10 pdentries = [] pdentries.extend(entries) pdentries.extend([PDEntry(Composition({el:1}), element_energy)", "for e in pd.stable_entries if e in entries], key=lifrac)) #unstable", "convex hull generation element_energy = max([entry.energy_per_atom for entry in entries])", "in pd.stable_entries if e in entries], key=lifrac)) #unstable entries ordered", "self._working_ion @property def working_ion_entry(self): return self._working_ion_entry @property def voltage_pairs(self): return", "#Initialize normalized properties self._vol_charge = entry_charge.structure.volume / norm_charge self._vol_discharge =", "__author__ = \"<NAME>, <NAME>\" __copyright__ = \"Copyright 2012, The Materials", "the frameworks of the entries are equivalent if not frame_charge_comp.reduced_formula", "pair[1].entry_discharge chg_frac = entry_charge.composition.get_atomic_fraction(ion) dischg_frac = entry_discharge.composition.get_atomic_fraction(ion) def in_range(entry): frac", "entry_discharge.composition self._mass_charge = comp_charge.weight / norm_charge self._mass_discharge = comp_discharge.weight /", "not None: data.append(pair.decomp_e_discharge) return max(data) if len(data) > 0 else", "\"fracA_discharge\": dischg_comp.get_atomic_fraction(ion), \"max_instability\": self.get_max_instability(), \"min_instability\": self.get_min_instability()} if print_subelectrodes: f_dict =", "entry_charge.structure.volume / norm_charge self._vol_discharge = entry_discharge.structure.volume / norm_discharge comp_charge =", "+ working_ion_entry.energy_per_atom) / working_ion_valence self._mAh = self._num_ions_transferred * Charge(1, \"e\").to(\"C\")", "for entry in entries: elements.update(entry.composition.elements) #Set an artificial energy for", "\"\"\" Return all entries input for the electrode. Args: charge_to_discharge:", "\"\"\" def __init__(self, entry1, entry2, working_ion_entry): #initialize some internal variables", "The maximum allowable voltage allowable for a given step Returns:", "make phase diagram: determine elements and set their energy #to", "set their energy #to be very high elements = set()", "maximum allowable voltage. Returns: Minimum decomposition energy of all compounds", "dischg_comp = self.fully_discharged_entry.composition ion = self.working_ion d = {\"average_voltage\": self.get_average_voltage(),", "decomposition energy of all compounds along the insertion path (a", "it is possible to use only a subset of the", "ion. \"\"\" all_entries = list(self.get_stable_entries()) all_entries.extend(self.get_unstable_entries()) #sort all entries by", "entries in the electrode, ordered by amount of the working", "the element that carries charge across the battery, e.g. Li.", "most charged entry along the topotactic path. \"\"\" return self._stable_entries[0]", "element_energy) for el in elements]) #Make phase diagram to determine", "entry_discharge.structure.volume / norm_discharge comp_charge = entry_charge.composition comp_discharge = entry_discharge.composition self._mass_charge", "\"an element\") #check that at least one of the entries", "in entries: elements.update(entry.composition.elements) #Set an artificial energy for each element", "= pair.entry_discharge if adjacent_only \\ else pair[1].entry_discharge chg_frac = entry_charge.composition.get_atomic_fraction(ion)", "for a given step Returns: Minimum critical oxygen chemical of", "get_min_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Minimum critical oxygen chemical potential along", "= comp_discharge.weight / norm_discharge self._num_ions_transferred = \\ (comp_discharge[working_element] / norm_discharge)", "is possible to use only a subset of the voltage", "dischg_frac if include_myself or entry_charge != self.fully_charged_entry \\ or entry_discharge", "voltage. max_voltage: The maximum allowable voltage. Returns: Maximum critical oxygen", "i in range(len(self._stable_entries) - 1)]) @property def working_ion(self): \"\"\" The", "max(data) if len(data) > 0 else None def get_min_muO2(self, min_voltage=None,", "a given step max_voltage: The maximum allowable voltage allowable for", "self.working_ion d = {\"average_voltage\": self.get_average_voltage(), \"max_voltage\": self.max_voltage, \"min_voltage\": self.min_voltage, \"max_delta_volume\":", "- (entry_discharge.energy / norm_discharge)) / \\ self._num_ions_transferred + working_ion_entry.energy_per_atom) /", "\\ (comp_discharge[working_element] / norm_discharge) \\ - (comp_charge[working_element] / norm_charge) self._voltage", "\\ > entry2.composition.get_atomic_fraction(working_element): (entry_charge, entry_discharge) = (entry_discharge, entry_charge) comp_charge =", "max_voltage: The maximum allowable voltage. Returns: Maximum critical oxygen chemical", "None def get_min_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Minimum critical oxygen chemical", "as_dict(self): return {\"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"entries\": [entry.as_dict() for entry", "step Returns: Minimum critical oxygen chemical of all compounds along", "print data on all the possible subelectrodes. Returns: A summary", "for the electrode. Args: charge_to_discharge: Order from most charge to", "self.normalization_discharge = norm_discharge self._frac_charge = comp_charge.get_atomic_fraction(working_element) self._frac_discharge = \\ comp_discharge.get_atomic_fraction(working_element)", "ordered by amount of Li asc self._unstable_entries = tuple(sorted([e for", "steps to define other electrodes. For example, an LiTiO2 electrode", "return {\"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"entries\": [entry.as_dict() for entry in", "with different amounts of a single element, e.g. TiO2 and", "or entry_discharge != self.fully_discharged_entry: unstable_entries = filter(in_range, self.get_unstable_entries()) stable_entries =", "entry_charge = pair.entry_charge if adjacent_only \\ else pair[0].entry_charge entry_discharge =", "a summary dict. Args: print_subelectrodes: Also print data on all", "def mass_charge(self): return self._mass_charge @property def mass_discharge(self): return self._mass_discharge @property", "(c) Pymatgen Development Team. # Distributed under the terms of", "Charge, Time from pymatgen.phasediagram.maker import PhaseDiagram from pymatgen.phasediagram.entries import PDEntry", "electrodes from compounds that are adjacent on the convex hull,", "Maximum critical oxygen chemical potential along path. Args: min_voltage: The", "Li. \"\"\" self._entries = entries self._working_ion = working_ion_entry.composition.elements[0] self._working_ion_entry =", "along a path for a specific voltage range. Args: min_voltage:", "in comp_discharge if el.symbol != ion_sym}) #Data validation #check that", "/ norm_discharge self._num_ions_transferred = \\ (comp_discharge[working_element] / norm_discharge) \\ -", "self.working_ion_entry.as_dict()} class InsertionVoltagePair(AbstractVoltagePair): \"\"\" Defines an Insertion Voltage Pair. Args:", "for each element for convex hull generation element_energy = max([entry.energy_per_atom", "\"frac_charge = {}, frac_discharge = {}\" .format(self.frac_charge, self.frac_discharge)] return \"\\n\".join(output)", "factors, charged and discharged entries valence_list = Element(ion_sym).oxidation_states working_ion_valence =", "chg_form, dischg_form)) output.append(\"Avg. volt. = {} V\".format(self.get_average_voltage())) output.append(\"Grav. cap. =", "= frame_charge_comp.get_reduced_composition_and_factor() norm_discharge = \\ frame_discharge_comp.get_reduced_composition_and_factor()[1] self._working_ion_entry = working_ion_entry #Initialize", "input for the electrode. Args: charge_to_discharge: order from most charge", "intercalation batteries. \"\"\" __author__ = \"<NAME>, <NAME>\" __copyright__ = \"Copyright", "InsertionElectrode. Args: entries: A list of ComputedStructureEntries (or subclasses) representing", "element that carries charge across the battery, e.g. Li. \"\"\"", "the voltage step. working_ion_entry: A single ComputedEntry or PDEntry representing", "MIT License. from __future__ import division, unicode_literals \"\"\" This module", "e.g. Li. \"\"\" self._entries = entries self._working_ion = working_ion_entry.composition.elements[0] self._working_ion_entry", "list_copy if charge_to_discharge else list_copy.reverse() def get_unstable_entries(self, charge_to_discharge=True): \"\"\" Returns", "{}, frac_discharge = {}\" .format(self.frac_charge, self.frac_discharge)] return \"\\n\".join(output) def __str__(self):", "def get_max_muO2(self, min_voltage=None, max_voltage=None): \"\"\" Maximum critical oxygen chemical potential", "Charge(1, \"e\").to(\"C\") * \\ Time(1, \"s\").to(\"h\") * N_A * 1000", "the entries are equivalent if not frame_charge_comp.reduced_formula == \\ frame_discharge_comp.reduced_formula:", "norm_charge) = frame_charge_comp.get_reduced_composition_and_factor() norm_discharge = \\ frame_discharge_comp.get_reduced_composition_and_factor()[1] self._working_ion_entry = working_ion_entry", "pair_it: entry_charge = pair.entry_charge if adjacent_only \\ else pair[0].entry_charge entry_discharge", "subelectrodes. Returns: A summary of this electrode\"s properties in dict", "oxygen chemical potential along path. Args: min_voltage: The minimum allowable", "for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.muO2_discharge is not None:", "= working_element.symbol frame_charge_comp = Composition({el: comp_charge[el] for el in comp_charge", "return battery_list def as_dict_summary(self, print_subelectrodes=True): \"\"\" Generate a summary dict.", "is not None: data.append(pair.decomp_e_discharge) return max(data) if len(data) > 0", "results. Returns: A list of InsertionElectrode objects \"\"\" battery_list =", "stable entries. Args: charge_to_discharge: order from most charge to most", "same in both the entries\") #check that the frameworks of", "working_element.symbol frame_charge_comp = Composition({el: comp_charge[el] for el in comp_charge if", "oxygen chemical of all compounds along the insertion path (a", "self.fully_discharged_entry: unstable_entries = filter(in_range, self.get_unstable_entries()) stable_entries = filter(in_range, self.get_stable_entries()) all_entries", "voltage range. Args: min_voltage: The minimum allowable voltage. max_voltage: The", "\"\"\" The most charged entry along the topotactic path. \"\"\"", "diagram: determine elements and set their energy #to be very", "a subset of the voltage steps to define other electrodes.", "self.get_capacity_grav(), \"capacity_vol\": self.get_capacity_vol(), \"energy_grav\": self.get_specific_energy(), \"energy_vol\": self.get_energy_density(), \"working_ion\": self._working_ion.symbol, \"nsteps\":", "of the MIT License. from __future__ import division, unicode_literals \"\"\"", "vol_discharge(self): return self._vol_discharge @property def working_ion_entry(self): return self._working_ion_entry def __repr__(self):", "{}\".format( chg_form, dischg_form)) output.append(\"Avg. volt. = {} V\".format(self.get_average_voltage())) output.append(\"Grav. cap.", "working_ion_entry.composition.elements[0] self._working_ion_entry = working_ion_entry #Prepare to make phase diagram: determine", "ion ASC fsrt = lambda e: e.composition.get_atomic_fraction(self.working_ion) all_entries = sorted([e", "return cls(dec.process_decoded(d[\"entries\"]), dec.process_decoded(d[\"working_ion_entry\"])) def as_dict(self): return {\"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__,", "step max_voltage: The maximum allowable voltage allowable for a given", "ion_sym = working_element.symbol frame_charge_comp = Composition({el: comp_charge[el] for el in", "working element if not comp_charge.get_atomic_fraction(working_element) > 0 and \\ not", "import N_A class InsertionElectrode(AbstractElectrode): \"\"\" A set of topotactically related", "self.mAh), \"mass_charge = {}, mass_discharge = {}\" .format(self.mass_charge, self.mass_discharge), \"vol_charge", "an Insertion Voltage Pair. Args: entry1: Entry corresponding to one", "monty.json import MontyDecoder dec = MontyDecoder() return cls(dec.process_decoded(d[\"entries\"]), dec.process_decoded(d[\"working_ion_entry\"])) def", "allowable voltage. max_voltage: The maximum allowable voltage. Returns: Maximum decomposition", "is set True. include_myself: Include this identical electrode in the", "along path. Args: min_voltage: The minimum allowable voltage for a", "\\ else pair[1].entry_discharge chg_frac = entry_charge.composition.get_atomic_fraction(ion) dischg_frac = entry_discharge.composition.get_atomic_fraction(ion) def", "can be chosen by the optional arguments). \"\"\" data =", "from pymatgen.phasediagram.entries import PDEntry from pymatgen.apps.battery.battery_abc import AbstractElectrode, \\ AbstractVoltagePair", "Materials Project\" __version__ = \"0.1\" __maintainer__ = \"<NAME>\" __email__ =", "entries]) + 10 pdentries = [] pdentries.extend(entries) pdentries.extend([PDEntry(Composition({el:1}), element_energy) for", "chemical potential along path. Args: min_voltage: The minimum allowable voltage", "can be used to return all the subelectrodes with some", "= \\ (((entry_charge.energy / norm_charge) - (entry_discharge.energy / norm_discharge)) /", "entry_discharge.data.get(\"muO2\", None) self.entry_charge = entry_charge self.entry_discharge = entry_discharge self.normalization_charge =", "all_entries.extend(self.get_unstable_entries()) #sort all entries by amount of working ion ASC", "def working_ion_entry(self): return self._working_ion_entry def __repr__(self): output = [\"Insertion voltage", "allowable voltage. Returns: Maximum decomposition energy of all compounds along", "a given step Returns: Minimum critical oxygen chemical of all", "self._working_ion_entry = working_ion_entry #Prepare to make phase diagram: determine elements", "d): from monty.json import MontyDecoder dec = MontyDecoder() return cls(dec.process_decoded(d[\"entries\"]),", "{}, mAh = {}\".format(self.voltage, self.mAh), \"mass_charge = {}, mass_discharge =", "Team. # Distributed under the terms of the MIT License.", "path can be chosen by the optional arguments) \"\"\" data", "from_dict(cls, d): from monty.json import MontyDecoder dec = MontyDecoder() return", "__copyright__ = \"Copyright 2012, The Materials Project\" __version__ = \"0.1\"", "#create voltage pairs self._vpairs = tuple([InsertionVoltagePair(self._stable_entries[i], self._stable_entries[i + 1], working_ion_entry)", "f_dict = lambda c: c.as_dict_summary(print_subelectrodes=False) d[\"adj_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=True)) d[\"all_pairs\"]", "\"<NAME>\" __email__ = \"<EMAIL>\" __date__ = \"Jan 13, 2012\" __status__", "voltage steps to define other electrodes. For example, an LiTiO2", "Element from scipy.constants import N_A class InsertionElectrode(AbstractElectrode): \"\"\" A set", "must be \" \"an element\") #check that at least one", "voltage allowable for a given step Returns: Minimum critical oxygen", "no electrodes returned will have multiple voltage steps if this", "lambda c: c.as_dict_summary(print_subelectrodes=False) d[\"adj_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=True)) d[\"all_pairs\"] = map(f_dict,", "for i in range(len(self._stable_entries) - 1)]) @property def working_ion(self): \"\"\"", "None def get_min_instability(self, min_voltage=None, max_voltage=None): \"\"\" The minimum instability along", "contains the working element if not comp_charge.get_atomic_fraction(working_element) > 0 and", "= self._vpairs if adjacent_only \\ else itertools.combinations_with_replacement(self._vpairs, 2) ion =", "if pair.decomp_e_charge is not None: data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is not", "Maximum critical oxygen chemical of all compounds along the insertion", "\"\"\" all_entries = list(self.get_stable_entries()) all_entries.extend(self.get_unstable_entries()) #sort all entries by amount", "self._working_ion.symbol, \"nsteps\": self.num_steps, \"framework\": self._vpairs[0].framework.to_data_dict, \"formula_charge\": chg_comp.reduced_formula, \"formula_discharge\": dischg_comp.reduced_formula, \"fracA_charge\":", "electrode might contain three subelectrodes: [LiTiO2 --> TiO2, LiTiO2 -->", "get_stable_entries(self, charge_to_discharge=True): \"\"\" Get the stable entries. Args: charge_to_discharge: order", "output.append(\"Grav. cap. = {} mAh/g\".format(self.get_capacity_grav())) output.append(\"Vol. cap. = {}\".format(self.get_capacity_vol())) return", "to define an insertion battery electrode. \"\"\" def __init__(self, entries,", "ion. \"\"\" list_copy = list(self._stable_entries) return list_copy if charge_to_discharge else", "under the terms of the MIT License. from __future__ import", "entry_discharge self.normalization_charge = norm_charge self.normalization_discharge = norm_discharge self._frac_charge = comp_charge.get_atomic_fraction(working_element)", "entry_charge.data.get(\"decomposition_energy\", None) self.decomp_e_discharge = \\ entry_discharge.data.get(\"decomposition_energy\", None) self.muO2_charge = entry_charge.data.get(\"muO2\",", "battery, e.g. TiO2 and LiTiO2. working_ion_entry: A single ComputedEntry or", "pd.stable_entries if e in entries], key=lifrac)) #unstable entries ordered by", "Args: charge_to_discharge: Order from most charge to most discharged state?", "that carries charge across the battery, e.g. Li. \"\"\" def", "ion specified must be \" \"an element\") #check that at", "electrode in the list of results. Returns: A list of", "comp_charge.get_atomic_fraction(working_element) self._frac_discharge = \\ comp_discharge.get_atomic_fraction(working_element) @property def frac_charge(self): return self._frac_charge", "self._working_ion_entry def __repr__(self): output = [\"Insertion voltage pair with working", "element_energy = max([entry.energy_per_atom for entry in entries]) + 10 pdentries", "unstable entries in the electrode, ordered by amount of the", "allowable for a given step Returns: Minimum critical oxygen chemical", "if comp_charge.get_atomic_fraction(working_element) == \\ comp_discharge.get_atomic_fraction(working_element): raise ValueError(\"VoltagePair: The working ion", "for a specific voltage range. Args: min_voltage: The minimum allowable", "if adjacent_only \\ else pair[1].entry_discharge chg_frac = entry_charge.composition.get_atomic_fraction(ion) dischg_frac =", "the convex hull, i.e. no electrodes returned will have multiple", "\"\"\" Defines an Insertion Voltage Pair. Args: entry1: Entry corresponding", "materials with potential application as intercalation batteries. \"\"\" __author__ =", "self._stable_entries[i + 1], working_ion_entry) for i in range(len(self._stable_entries) - 1)])", "in self._select_in_voltage_range(min_voltage, max_voltage): if pair.decomp_e_charge is not None: data.append(pair.decomp_e_charge) if", "frame_charge_comp = Composition({el: comp_charge[el] for el in comp_charge if el.symbol", "self._working_ion = working_ion_entry.composition.elements[0] self._working_ion_entry = working_ion_entry #Prepare to make phase", "d[\"all_pairs\"] = map(f_dict, self.get_sub_electrodes(adjacent_only=False)) return d def __str__(self): return self.__repr__()", "= {}, frac_discharge = {}\" .format(self.frac_charge, self.frac_discharge)] return \"\\n\".join(output) def", "Default to True. Returns: A list of stable entries in", "potential along path. Args: min_voltage: The minimum allowable voltage. max_voltage:", "at least one of the entries contains the working element", "self.get_average_voltage(), \"max_voltage\": self.max_voltage, \"min_voltage\": self.min_voltage, \"max_delta_volume\": self.max_delta_volume, \"max_voltage_step\": self.max_voltage_step, \"capacity_grav\":", "@property def working_ion_entry(self): return self._working_ion_entry def __repr__(self): output = [\"Insertion", "def as_dict_summary(self, print_subelectrodes=True): \"\"\" Generate a summary dict. Args: print_subelectrodes:", "max_voltage=None): \"\"\" Minimum critical oxygen chemical potential along path. Args:", "None) self.decomp_e_discharge = \\ entry_discharge.data.get(\"decomposition_energy\", None) self.muO2_charge = entry_charge.data.get(\"muO2\", None)", "V\".format(self.get_average_voltage())) output.append(\"Grav. cap. = {} mAh/g\".format(self.get_capacity_grav())) output.append(\"Vol. cap. = {}\".format(self.get_capacity_vol()))", "ion = self.working_ion d = {\"average_voltage\": self.get_average_voltage(), \"max_voltage\": self.max_voltage, \"min_voltage\":", "by amount of the working ion. \"\"\" list_copy = list(self._stable_entries)", "max_voltage): if pair.muO2_discharge is not None: data.append(pair.pair.muO2_discharge) if pair.muO2_charge is", "electrode contains multiple voltage steps, then it is possible to", "e in pd.unstable_entries if e in entries], key=lifrac)) #create voltage", "define other electrodes. For example, an LiTiO2 electrode might contain", "import division, unicode_literals \"\"\" This module is used for analysis", "topotactic path. \"\"\" return self._stable_entries[0] @property def fully_discharged_entry(self): \"\"\" The", "norm_charge self._vol_discharge = entry_discharge.structure.volume / norm_discharge comp_charge = entry_charge.composition comp_discharge", "maximum allowable voltage. Returns: Maximum decomposition energy of all compounds", "= {}\".format(self.get_capacity_vol())) return \"\\n\".join(output) @classmethod def from_dict(cls, d): from monty.json", "(comp_charge[working_element] / norm_charge) self._voltage = \\ (((entry_charge.energy / norm_charge) -", "working_ion_valence #Step 4: add (optional) hull and muO2 data self.decomp_e_charge", "<= frac <= dischg_frac if include_myself or entry_charge != self.fully_charged_entry", "The working ion must be present in \" \"one of", "self._frac_charge @property def frac_discharge(self): return self._frac_discharge @property def voltage(self): return", "multiple voltage steps, then it is possible to use only", "\"one of the entries\") #check that the entries do not", "contains multiple voltage steps, then it is possible to use", "self._stable_entries[-1] def get_max_instability(self, min_voltage=None, max_voltage=None): \"\"\" The maximum instability along", "= entry2 if entry_charge.composition.get_atomic_fraction(working_element) \\ > entry2.composition.get_atomic_fraction(working_element): (entry_charge, entry_discharge) =", "If this electrode contains multiple voltage steps, then it is", "TiO2 and LiTiO2, that can be used to define an", "the subelectrodes with some options Args: adjacent_only: Only return electrodes", "def get_unstable_entries(self, charge_to_discharge=True): \"\"\" Returns the unstable entries for the", "elements = set() for entry in entries: elements.update(entry.composition.elements) #Set an", "the stable entries. Args: charge_to_discharge: order from most charge to", "the same in both the entries\") #check that the frameworks", "battery_list.append(self.__class__(all_entries, self.working_ion_entry)) return battery_list def as_dict_summary(self, print_subelectrodes=True): \"\"\" Generate a", "one of the entries in the voltage step. entry2: Entry", "Order from most charge to most discharged state? Defaults to", "the optional arguments). \"\"\" data = [] for pair in", "e.composition.get_atomic_fraction(self.working_ion) all_entries = sorted([e for e in all_entries], key=fsrt) return", "if this is set True. include_myself: Include this identical electrode" ]
[ "self.__swatch = GafferUI.ColorSwatch() GafferUI.PlugValueWidget.__init__( self, self.__swatch, plugs, **kw ) ##", "scoped = False ) self._updateFromPlugs() def setHighlighted( self, highlighted )", ") def __colorChanged( self, colorChooser, reason ) : if not", "def __buttonRelease( self, widget, event ) : if event.button !=", "__init__( self, plugs, **kw ) : self.__swatch = GafferUI.ColorSwatch() GafferUI.PlugValueWidget.__init__(", "False def __dragBegin( self, widget, event ) : GafferUI.Pointer.setCurrent( \"rgba\"", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,", "# the best we can do is take an average.", "GafferUI.Pointer.setCurrent( \"rgba\" ) return self.__swatch.getColor() def __dragEnd( self, widget, event", "reproduce the above # copyright notice, this list of conditions", "self.__swatch._qtWidget().setMaximumHeight( 20 ) self._addPopupMenu( self.__swatch ) self.__swatch.buttonPressSignal().connect( Gaffer.WeakMethod( self.__buttonPress ),", "False ) self.cancelButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped = False )", "True ) return window window = _ColorPlugValueDialogue( plugs, scriptWindow )", "colour, and doesn't have # an \"indeterminate\" state, so when", "next( iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode ), mergeGroup = \"ColorPlugValueDialogue%d%d\"", "# # Redistribution and use in source and binary forms,", "Redistributions of source code must retain the above # copyright", "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,", "rights reserved. # Copyright (c) 2013, Image Engine Design Inc.", ": if not len( plugs ) : return imath.Color4f( 0", "API? Perhaps we could also make a # PlugValueDialogue base", "window, cls ) and window.__plugs == plugs : window.setVisible( True", "GafferUI.ScriptWindow.acquire( script ) for window in scriptWindow.childWindows() : if isinstance(", "plugs ) : return imath.Color4f( 0 ) # ColorSwatch only", "have multiple plugs # the best we can do is", "binary form must reproduce the above # copyright notice, this", "True return False def __dragBegin( self, widget, event ) :", ") if len( self.__plugs ) == 1 : self.setTitle( plug.relativeName(", "plug.node().scriptNode() scriptWindow = GafferUI.ScriptWindow.acquire( script ) for window in scriptWindow.childWindows()", "the above # copyright notice, this list of conditions and", "class ColorSwatchPlugValueWidget( GafferUI.PlugValueWidget ) : def __init__( self, plugs, **kw", "_colorFromPlugs( self.__plugs ) ) def __colorChanged( self, colorChooser, reason )", "PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE", "merge into a single undo self.__lastChangedReason = None self.__mergeGroupId =", "p.node() for p in self.__plugs } self.__plugSetConnections = [ n.plugSetSignal().connect(", ") self.cancelButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped = False ) self.__plugs", "= \"ColorPlugValueDialogue%d%d\" % ( id( self, ), self.__mergeGroupId ) )", ") : self.__swatch = GafferUI.ColorSwatch() GafferUI.PlugValueWidget.__init__( self, self.__swatch, plugs, **kw", "GafferUI.ColorChooserDialogue.__init__( self, color = _colorFromPlugs( plugs ) ) # we", "/ len( plugs ) ## \\todo Perhaps we could make", "a # PlugValueDialogue base class to share some of the", "documentation and/or other materials provided with # the distribution. #", "DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND", "GafferUI.ColorSwatch() GafferUI.PlugValueWidget.__init__( self, self.__swatch, plugs, **kw ) ## \\todo How", "contributors to this software may be used to endorse or", ": for plug in self.__plugs : plug.setValue( self.colorChooser().getColor() ) def", "dialogue made by the # SplinePlugValueWidget. Or perhaps the `acquire()`", "conditions are # met: # # * Redistributions of source", "= False ) self.__swatch.buttonReleaseSignal().connect( Gaffer.WeakMethod( self.__buttonRelease ), scoped = False", "above # copyright notice, this list of conditions and the", "EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #", "this list of conditions and the following # disclaimer. #", ") script = plug.node().scriptNode() scriptWindow = GafferUI.ScriptWindow.acquire( script ) for", "= GafferUI.ScriptWindow.acquire( script ) for window in scriptWindow.childWindows() : if", "THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF", "modification, are permitted provided that the following conditions are #", "if event.button != event.Buttons.Left : return False if not self._editable()", "# Copyright (c) 2013, Image Engine Design Inc. All rights", "ColorSwatchPlugValueWidget( GafferUI.PlugValueWidget ) : def __init__( self, plugs, **kw )", "must reproduce the above # copyright notice, this list of", "event ) : if event.buttons == event.Buttons.Left : return True", "GafferUI.PlugValueWidget.setHighlighted( self, highlighted ) self.__swatch.setHighlighted( highlighted ) def _updateFromPlugs( self", "materials provided with # the distribution. # # * Neither", "window window = _ColorPlugValueDialogue( plugs, scriptWindow ) window.setVisible( True )", "), scoped = False ) plug = next( iter( self.__plugs", "OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT", "part of the public API? Perhaps we could also make", "# copyright notice, this list of conditions and the following", "= [ n.plugSetSignal().connect( Gaffer.WeakMethod( self.__plugSet ), scoped = False )", "] for node in nodes : node.parentChangedSignal().connect( Gaffer.WeakMethod( self.__destroy ),", "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR", "in self.__plugs : with Gaffer.BlockedConnection( self.__colorChangedConnection ) : self.colorChooser().setColor( _colorFromPlugs(", "source and binary forms, with or without # modification, are", "iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode ), mergeGroup = \"ColorPlugValueDialogue%d%d\" %", ") self.__swatch.setHighlighted( highlighted ) def _updateFromPlugs( self ) : with", "len( self.__plugs ) == 1 : self.setTitle( plug.relativeName( plug.ancestor( Gaffer.ScriptNode", "value ) def __buttonPress( self, widget, event ) : if", "(c) 2013, <NAME>. All rights reserved. # Copyright (c) 2013,", "self, plugs, **kw ) : self.__swatch = GafferUI.ColorSwatch() GafferUI.PlugValueWidget.__init__( self,", "n in nodes ] for node in nodes : node.parentChangedSignal().connect(", "this list of conditions and the following # disclaimer in", ") : return imath.Color4f( 0 ) # ColorSwatch only supports", "v in self.__initialValues.items() : p.setValue( v ) self.parent().removeChild( self )", "scoped = False ) self.confirmButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped =", "plugs\".format( len( self.__plugs ) ) ) self.__plugSet( plug ) parentWindow.addChildWindow(", "`acquire()` here and `NodeSetEditor.acquire()` should # actually be functionality of", "and/or other materials provided with # the distribution. # #", "IN ANY WAY OUT OF THE USE OF THIS #", "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY,", "def __buttonClicked( self, button ) : if button is self.cancelButton", "False if not self._editable() : return False _ColorPlugValueDialogue.acquire( self.getPlugs() )", "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF", "plug.setValue( self.colorChooser().getColor() ) def __buttonClicked( self, button ) : if", "(c) 2013, Image Engine Design Inc. All rights reserved. #", "self.__plugs } nodes = { p.node() for p in self.__plugs", "of # any other contributors to this software may be", "with # the distribution. # # * Neither the name", "NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE", "1 self.__lastChangedReason = reason with Gaffer.UndoScope( next( iter( self.__plugs )", ": if isinstance( window, cls ) and window.__plugs == plugs", "plugs, parentWindow ) : GafferUI.ColorChooserDialogue.__init__( self, color = _colorFromPlugs( plugs", "in plugs ) / len( plugs ) ## \\todo Perhaps", "NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND", "GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS;", "), scoped = False ) self.__swatch.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd ), scoped", "some of the work with the dialogue made by the", "https://bugreports.qt-project.org/browse/QTBUG-26761. assert( not self.visible() ) GafferUI.WidgetAlgo.keepUntilIdle( self ) def __destroy(", "and binary forms, with or without # modification, are permitted", "the following # disclaimer in the documentation and/or other materials", "_ColorPlugValueDialogue.acquire( self.getPlugs() ) return True def _colorFromPlugs( plugs ) :", "highlighted ) : GafferUI.PlugValueWidget.setHighlighted( self, highlighted ) self.__swatch.setHighlighted( highlighted )", "if len( self.__plugs ) == 1 : self.setTitle( plug.relativeName( plug.ancestor(", "OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY", "base class to share some of the work with the", "make a # PlugValueDialogue base class to share some of", "next( iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode ) ) : for", "a part of the public API? Perhaps we could also", "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR #", "import imath import Gaffer import GafferUI class ColorSwatchPlugValueWidget( GafferUI.PlugValueWidget )", "and the following # disclaimer in the documentation and/or other", "\"AS # IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "**kw ) ## \\todo How do set maximum height with", "plugs ) ) # we use these to decide which", "self.__buttonClicked ), scoped = False ) self.__plugs = plugs self.__initialValues", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE", "do set maximum height with a public API? self.__swatch._qtWidget().setMaximumHeight( 20", "for p, v in self.__initialValues.items() : p.setValue( v ) self.parent().removeChild(", "or # promote products derived from this software without specific", "THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR", ") for window in scriptWindow.childWindows() : if isinstance( window, cls", "__init__( self, plugs, parentWindow ) : GafferUI.ColorChooserDialogue.__init__( self, color =", "CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN", "these to decide which actions to merge into a single", "undo self.__lastChangedReason = None self.__mergeGroupId = 0 self.__colorChangedConnection = self.colorChooser().colorChangedSignal().connect(", "list of conditions and the following # disclaimer in the", ") window.setVisible( True ) return False def __plugSet( self, plug", "return False def __plugSet( self, plug ) : if plug", "return window window = _ColorPlugValueDialogue( plugs, scriptWindow ) window.setVisible( True", "= next( iter( self.__plugs ) ) if len( self.__plugs )", "NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL", "A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL", "written permission. # # THIS SOFTWARE IS PROVIDED BY THE", "= GafferUI.ColorSwatch() GafferUI.PlugValueWidget.__init__( self, self.__swatch, plugs, **kw ) ## \\todo", "next( iter( plugs ) ) script = plug.node().scriptNode() scriptWindow =", "= None self.__mergeGroupId = 0 self.__colorChangedConnection = self.colorChooser().colorChangedSignal().connect( Gaffer.WeakMethod( self.__colorChanged", ") return False def __plugSet( self, plug ) : if", "conditions and the following # disclaimer in the documentation and/or", ": if event.buttons == event.Buttons.Left : return True return False", ") def _updateFromPlugs( self ) : with self.getContext() : value", "with a public API? self.__swatch._qtWidget().setMaximumHeight( 20 ) self._addPopupMenu( self.__swatch )", "OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY", "can do is take an average. return sum( p.getValue() for", "self.__swatch.setColor( value ) def __buttonPress( self, widget, event ) :", "plug ) : if plug in self.__plugs : with Gaffer.BlockedConnection(", "Inc. All rights reserved. # # Redistribution and use in", "INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT", "scoped = False ) self.__swatch.buttonReleaseSignal().connect( Gaffer.WeakMethod( self.__buttonRelease ), scoped =", "isinstance( window, cls ) and window.__plugs == plugs : window.setVisible(", "THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR", "_colorFromPlugs( plugs ) ) # we use these to decide", "return self.__swatch.getColor() def __dragEnd( self, widget, event ) : GafferUI.Pointer.setCurrent(", "in scriptWindow.childWindows() : if isinstance( window, cls ) and window.__plugs", "def __init__( self, plugs, **kw ) : self.__swatch = GafferUI.ColorSwatch()", "OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF", "n.plugSetSignal().connect( Gaffer.WeakMethod( self.__plugSet ), scoped = False ) for n", "False ) self.__plugs = plugs self.__initialValues = { p :", "to share some of the work with the dialogue made", "self.__colorChangedConnection ) : self.colorChooser().setColor( _colorFromPlugs( self.__plugs ) ) def __colorChanged(", "prior # written permission. # # THIS SOFTWARE IS PROVIDED", "self.getPlugs() ) return True def _colorFromPlugs( plugs ) : if", "with self.getContext() : value = _colorFromPlugs( self.getPlugs() ) self.__swatch.setColor( value", "in nodes : node.parentChangedSignal().connect( Gaffer.WeakMethod( self.__destroy ), scoped = False", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", ": p.getValue() for p in self.__plugs } nodes = {", "# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF", ") : GafferUI.Pointer.setCurrent( \"rgba\" ) return self.__swatch.getColor() def __dragEnd( self,", "only supports one colour, and doesn't have # an \"indeterminate\"", "OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF", "self, ), self.__mergeGroupId ) ) : with Gaffer.BlockedConnection( self.__plugSetConnections )", "may be used to endorse or # promote products derived", "a public API? self.__swatch._qtWidget().setMaximumHeight( 20 ) self._addPopupMenu( self.__swatch ) self.__swatch.buttonPressSignal().connect(", "self.colorChooser().setColor( _colorFromPlugs( self.__plugs ) ) def __colorChanged( self, colorChooser, reason", "take an average. return sum( p.getValue() for p in plugs", "name of <NAME> nor the names of # any other", "for p in self.__plugs } nodes = { p.node() for", ") ) : for p, v in self.__initialValues.items() : p.setValue(", "p.getValue() for p in self.__plugs } nodes = { p.node()", "COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT,", "FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT", "__dragBegin( self, widget, event ) : GafferUI.Pointer.setCurrent( \"rgba\" ) return", "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,", "(INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT", "disclaimer. # # * Redistributions in binary form must reproduce", "self.visible() ) GafferUI.WidgetAlgo.keepUntilIdle( self ) def __destroy( self, *unused )", "reserved. # Copyright (c) 2013, Image Engine Design Inc. All", "assert( not self.visible() ) GafferUI.WidgetAlgo.keepUntilIdle( self ) def __destroy( self,", "# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT", "SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR", "without specific prior # written permission. # # THIS SOFTWARE", "supports one colour, and doesn't have # an \"indeterminate\" state,", "script ) for window in scriptWindow.childWindows() : if isinstance( window,", "# PlugValueDialogue base class to share some of the work", "CompoundEditor? class _ColorPlugValueDialogue( GafferUI.ColorChooserDialogue ) : def __init__( self, plugs,", "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, #", "########################################################################## import weakref import imath import Gaffer import GafferUI class", "self.__plugSet ), scoped = False ) for n in nodes", "HOLDERS AND CONTRIBUTORS \"AS # IS\" AND ANY EXPRESS OR", "functionality of CompoundEditor? class _ColorPlugValueDialogue( GafferUI.ColorChooserDialogue ) : def __init__(", "= 0 self.__colorChangedConnection = self.colorChooser().colorChangedSignal().connect( Gaffer.WeakMethod( self.__colorChanged ), scoped =", "} nodes = { p.node() for p in self.__plugs }", "to merge into a single undo self.__lastChangedReason = None self.__mergeGroupId", "other materials provided with # the distribution. # # *", "self.__dragEnd ), scoped = False ) self.__swatch.buttonReleaseSignal().connect( Gaffer.WeakMethod( self.__buttonRelease ),", "self.__mergeGroupId += 1 self.__lastChangedReason = reason with Gaffer.UndoScope( next( iter(", "specific prior # written permission. # # THIS SOFTWARE IS", ") : def __init__( self, plugs, **kw ) : self.__swatch", "following # disclaimer in the documentation and/or other materials provided", "MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED.", "plugs ) ) script = plug.node().scriptNode() scriptWindow = GafferUI.ScriptWindow.acquire( script", "Gaffer.WeakMethod( self.__buttonClicked ), scoped = False ) self.cancelButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked", ") ) ) else : self.setTitle( \"{} plugs\".format( len( self.__plugs", "with Gaffer.BlockedConnection( self.__plugSetConnections ) : for plug in self.__plugs :", "), scoped = False ) self.__plugs = plugs self.__initialValues =", "self.__plugs : with Gaffer.BlockedConnection( self.__colorChangedConnection ) : self.colorChooser().setColor( _colorFromPlugs( self.__plugs", "# promote products derived from this software without specific prior", "self.__plugs = plugs self.__initialValues = { p : p.getValue() for", "+= 1 self.__lastChangedReason = reason with Gaffer.UndoScope( next( iter( self.__plugs", "OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "maximum height with a public API? self.__swatch._qtWidget().setMaximumHeight( 20 ) self._addPopupMenu(", "# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "import GafferUI class ColorSwatchPlugValueWidget( GafferUI.PlugValueWidget ) : def __init__( self,", "or without # modification, are permitted provided that the following", "and `NodeSetEditor.acquire()` should # actually be functionality of CompoundEditor? class", "Redistribution and use in source and binary forms, with or", "# SplinePlugValueWidget. Or perhaps the `acquire()` here and `NodeSetEditor.acquire()` should", ": node.parentChangedSignal().connect( Gaffer.WeakMethod( self.__destroy ), scoped = False ) plug", "True def _colorFromPlugs( plugs ) : if not len( plugs", "source code must retain the above # copyright notice, this", ") : GafferUI.Pointer.setCurrent( None ) def __buttonRelease( self, widget, event", "return sum( p.getValue() for p in plugs ) / len(", "def _updateFromPlugs( self ) : with self.getContext() : value =", ") ) if len( self.__plugs ) == 1 : self.setTitle(", "provided that the following conditions are # met: # #", "endorse or # promote products derived from this software without", "# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,", ": with Gaffer.BlockedConnection( self.__colorChangedConnection ) : self.colorChooser().setColor( _colorFromPlugs( self.__plugs )", "a single undo self.__lastChangedReason = None self.__mergeGroupId = 0 self.__colorChangedConnection", "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE", "for p in plugs ) / len( plugs ) ##", "# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A", "INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT", "Gaffer.WeakMethod( self.__buttonRelease ), scoped = False ) self._updateFromPlugs() def setHighlighted(", "self.__plugs ) ) if len( self.__plugs ) == 1 :", "USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE", "OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,", "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "p in self.__plugs } nodes = { p.node() for p", "imath.Color4f( 0 ) # ColorSwatch only supports one colour, and", "here and `NodeSetEditor.acquire()` should # actually be functionality of CompoundEditor?", "All rights reserved. # Copyright (c) 2013, Image Engine Design", "made by the # SplinePlugValueWidget. Or perhaps the `acquire()` here", "rights reserved. # # Redistribution and use in source and", "False ) plug = next( iter( self.__plugs ) ) if", ": if event.button != event.Buttons.Left : return False if not", "state, so when we have multiple plugs # the best", "plug.ancestor( Gaffer.ScriptNode ) ) ) else : self.setTitle( \"{} plugs\".format(", "self, highlighted ) : GafferUI.PlugValueWidget.setHighlighted( self, highlighted ) self.__swatch.setHighlighted( highlighted", "# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY", "= False ) self.cancelButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped = False", "GafferUI.PlugValueWidget.__init__( self, self.__swatch, plugs, **kw ) ## \\todo How do", "that the following conditions are # met: # # *", "# * Neither the name of <NAME> nor the names", "Engine Design Inc. All rights reserved. # # Redistribution and", "weakref import imath import Gaffer import GafferUI class ColorSwatchPlugValueWidget( GafferUI.PlugValueWidget", "plugs ) : plug = next( iter( plugs ) )", "* Redistributions in binary form must reproduce the above #", "scoped = False ) self.__swatch.dragBeginSignal().connect( Gaffer.WeakMethod( self.__dragBegin ), scoped =", "plug.relativeName( plug.ancestor( Gaffer.ScriptNode ) ) ) else : self.setTitle( \"{}", "), self.__mergeGroupId ) ) : with Gaffer.BlockedConnection( self.__plugSetConnections ) :", "# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,", "# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING", "not self._editable() : return False _ColorPlugValueDialogue.acquire( self.getPlugs() ) return True", "False _ColorPlugValueDialogue.acquire( self.getPlugs() ) return True def _colorFromPlugs( plugs )", "def acquire( cls, plugs ) : plug = next( iter(", "def __colorChanged( self, colorChooser, reason ) : if not GafferUI.ColorChooser.changesShouldBeMerged(", "the following conditions are # met: # # * Redistributions", "iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode ) ) : for p,", "following conditions are # met: # # * Redistributions of", ") : GafferUI.PlugValueWidget.setHighlighted( self, highlighted ) self.__swatch.setHighlighted( highlighted ) def", "Design Inc. All rights reserved. # # Redistribution and use", "self._addPopupMenu( self.__swatch ) self.__swatch.buttonPressSignal().connect( Gaffer.WeakMethod( self.__buttonPress ), scoped = False", "plugs, **kw ) ## \\todo How do set maximum height", "p.getValue() for p in plugs ) / len( plugs )", "do is take an average. return sum( p.getValue() for p", "widget, event ) : if event.buttons == event.Buttons.Left : return", "GafferUI.PlugValueWidget ) : def __init__( self, plugs, **kw ) :", "} self.__plugSetConnections = [ n.plugSetSignal().connect( Gaffer.WeakMethod( self.__plugSet ), scoped =", "True ) @classmethod def acquire( cls, plugs ) : plug", "self._updateFromPlugs() def setHighlighted( self, highlighted ) : GafferUI.PlugValueWidget.setHighlighted( self, highlighted", ") plug = next( iter( self.__plugs ) ) if len(", ") : with Gaffer.BlockedConnection( self.__plugSetConnections ) : for plug in", ") GafferUI.WidgetAlgo.keepUntilIdle( self ) def __destroy( self, *unused ) :", "self, widget, event ) : if event.buttons == event.Buttons.Left :", "parentWindow ) : GafferUI.ColorChooserDialogue.__init__( self, color = _colorFromPlugs( plugs )", "in source and binary forms, with or without # modification,", "for p in self.__plugs } self.__plugSetConnections = [ n.plugSetSignal().connect( Gaffer.WeakMethod(", "OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER", ": return False _ColorPlugValueDialogue.acquire( self.getPlugs() ) return True def _colorFromPlugs(", ") : if event.button != event.Buttons.Left : return False if", "False def __plugSet( self, plug ) : if plug in", "scoped = False ) self.__swatch.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd ), scoped =", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS # IS\"", "retain the above # copyright notice, this list of conditions", ") / len( plugs ) ## \\todo Perhaps we could", "THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import weakref import", "color = _colorFromPlugs( plugs ) ) # we use these", ": value = _colorFromPlugs( self.getPlugs() ) self.__swatch.setColor( value ) def", "self.__colorChangedConnection = self.colorChooser().colorChangedSignal().connect( Gaffer.WeakMethod( self.__colorChanged ), scoped = False )", "self.__swatch, plugs, **kw ) ## \\todo How do set maximum", "self.__swatch.getColor() def __dragEnd( self, widget, event ) : GafferUI.Pointer.setCurrent( None", "self.getContext() : value = _colorFromPlugs( self.getPlugs() ) self.__swatch.setColor( value )", "self.__buttonClicked ), scoped = False ) self.cancelButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ),", "OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR", "CONTRIBUTORS \"AS # IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,", "with Gaffer.UndoScope( next( iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode ) )", "return True return False def __dragBegin( self, widget, event )", ": def __init__( self, plugs, **kw ) : self.__swatch =", "in self.__plugs } self.__plugSetConnections = [ n.plugSetSignal().connect( Gaffer.WeakMethod( self.__plugSet ),", "the name of <NAME> nor the names of # any", ").ancestor( Gaffer.ScriptNode ) ) : for p, v in self.__initialValues.items()", "Copyright (c) 2013, Image Engine Design Inc. All rights reserved.", "use in source and binary forms, with or without #", "cls ) and window.__plugs == plugs : window.setVisible( True )", "next( iter( self.__plugs ) ) if len( self.__plugs ) ==", "Perhaps we could also make a # PlugValueDialogue base class", "## \\todo How do set maximum height with a public", "__buttonRelease( self, widget, event ) : if event.button != event.Buttons.Left", "self.__swatch ) self.__swatch.buttonPressSignal().connect( Gaffer.WeakMethod( self.__buttonPress ), scoped = False )", "None ) def __buttonRelease( self, widget, event ) : if", "this software may be used to endorse or # promote", "self.__swatch.buttonPressSignal().connect( Gaffer.WeakMethod( self.__buttonPress ), scoped = False ) self.__swatch.dragBeginSignal().connect( Gaffer.WeakMethod(", "ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES", "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE)", "\\todo Perhaps we could make this a part of the", ": if not GafferUI.ColorChooser.changesShouldBeMerged( self.__lastChangedReason, reason ) : self.__mergeGroupId +=", "to this software may be used to endorse or #", "following # disclaimer. # # * Redistributions in binary form", "self, button ) : if button is self.cancelButton : with", "len( plugs ) ## \\todo Perhaps we could make this", "disclaimer in the documentation and/or other materials provided with #", "# Workaround for https://bugreports.qt-project.org/browse/QTBUG-26761. assert( not self.visible() ) GafferUI.WidgetAlgo.keepUntilIdle( self", "########################################################################## # # Copyright (c) 2013, <NAME>. All rights reserved.", "should # actually be functionality of CompoundEditor? class _ColorPlugValueDialogue( GafferUI.ColorChooserDialogue", "False ) self.__swatch.dragBeginSignal().connect( Gaffer.WeakMethod( self.__dragBegin ), scoped = False )", "Neither the name of <NAME> nor the names of #", "POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import weakref import imath", ": self.__mergeGroupId += 1 self.__lastChangedReason = reason with Gaffer.UndoScope( next(", "# the distribution. # # * Neither the name of", ") def __buttonClicked( self, button ) : if button is", "Gaffer.ScriptNode ) ) : for p, v in self.__initialValues.items() :", ") : GafferUI.ColorChooserDialogue.__init__( self, color = _colorFromPlugs( plugs ) )", "permitted provided that the following conditions are # met: #", "WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN", "of the work with the dialogue made by the #", ") return window window = _ColorPlugValueDialogue( plugs, scriptWindow ) window.setVisible(", "the documentation and/or other materials provided with # the distribution.", ": self.colorChooser().setColor( _colorFromPlugs( self.__plugs ) ) def __colorChanged( self, colorChooser,", "Image Engine Design Inc. All rights reserved. # # Redistribution", ") # we use these to decide which actions to", "True ) return False def __plugSet( self, plug ) :", "self.__initialValues = { p : p.getValue() for p in self.__plugs", "GafferUI.ColorChooser.changesShouldBeMerged( self.__lastChangedReason, reason ) : self.__mergeGroupId += 1 self.__lastChangedReason =", "% ( id( self, ), self.__mergeGroupId ) ) : with", "AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT,", ") ## \\todo Perhaps we could make this a part", ": return True return False def __dragBegin( self, widget, event", ") def __buttonPress( self, widget, event ) : if event.buttons", "Gaffer.WeakMethod( self.__buttonClicked ), scoped = False ) self.__plugs = plugs", "self.__mergeGroupId = 0 self.__colorChangedConnection = self.colorChooser().colorChangedSignal().connect( Gaffer.WeakMethod( self.__colorChanged ), scoped", ") : self.colorChooser().setColor( _colorFromPlugs( self.__plugs ) ) def __colorChanged( self,", "Workaround for https://bugreports.qt-project.org/browse/QTBUG-26761. assert( not self.visible() ) GafferUI.WidgetAlgo.keepUntilIdle( self )", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS # IS\" AND", "# # * Redistributions of source code must retain the", "an \"indeterminate\" state, so when we have multiple plugs #", "# any other contributors to this software may be used", "self.__plugs ) ) def __colorChanged( self, colorChooser, reason ) :", "_colorFromPlugs( plugs ) : if not len( plugs ) :", "## \\todo Perhaps we could make this a part of", "{ p : p.getValue() for p in self.__plugs } nodes", "scoped = False ) for n in nodes ] for", "self.__buttonRelease ), scoped = False ) self._updateFromPlugs() def setHighlighted( self,", "with or without # modification, are permitted provided that the", "False ) for n in nodes ] for node in", "self.__mergeGroupId ) ) : with Gaffer.BlockedConnection( self.__plugSetConnections ) : for", "SplinePlugValueWidget. Or perhaps the `acquire()` here and `NodeSetEditor.acquire()` should #", "window.__plugs == plugs : window.setVisible( True ) return window window", "parentWindow.addChildWindow( self, removeOnClose = True ) @classmethod def acquire( cls,", "{ p.node() for p in self.__plugs } self.__plugSetConnections = [", "False ) self.confirmButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped = False )", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE", "self, plugs, parentWindow ) : GafferUI.ColorChooserDialogue.__init__( self, color = _colorFromPlugs(", "Gaffer.WeakMethod( self.__dragBegin ), scoped = False ) self.__swatch.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd", ") self.__swatch.setColor( value ) def __buttonPress( self, widget, event )", "# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH", "self.__lastChangedReason, reason ) : self.__mergeGroupId += 1 self.__lastChangedReason = reason", "be functionality of CompoundEditor? class _ColorPlugValueDialogue( GafferUI.ColorChooserDialogue ) : def", "self.cancelButton : with Gaffer.UndoScope( next( iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode", "\"indeterminate\" state, so when we have multiple plugs # the", "this software without specific prior # written permission. # #", "TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY", "Perhaps we could make this a part of the public", "is take an average. return sum( p.getValue() for p in", ") self.__swatch.buttonPressSignal().connect( Gaffer.WeakMethod( self.__buttonPress ), scoped = False ) self.__swatch.dragBeginSignal().connect(", "_updateFromPlugs( self ) : with self.getContext() : value = _colorFromPlugs(", "plugs, scriptWindow ) window.setVisible( True ) return False def __plugSet(", "IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "distribution. # # * Neither the name of <NAME> nor", "self, widget, event ) : if event.button != event.Buttons.Left :", ") : self.__mergeGroupId += 1 self.__lastChangedReason = reason with Gaffer.UndoScope(", "self.__swatch.dragBeginSignal().connect( Gaffer.WeakMethod( self.__dragBegin ), scoped = False ) self.__swatch.dragEndSignal().connect( Gaffer.WeakMethod(", "plugs ) : if not len( plugs ) : return", "could also make a # PlugValueDialogue base class to share", ") for n in nodes ] for node in nodes", "\"ColorPlugValueDialogue%d%d\" % ( id( self, ), self.__mergeGroupId ) ) :", "decide which actions to merge into a single undo self.__lastChangedReason", "the # SplinePlugValueWidget. Or perhaps the `acquire()` here and `NodeSetEditor.acquire()`", "Gaffer.ScriptNode ), mergeGroup = \"ColorPlugValueDialogue%d%d\" % ( id( self, ),", "_ColorPlugValueDialogue( plugs, scriptWindow ) window.setVisible( True ) return False def", "THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY", "work with the dialogue made by the # SplinePlugValueWidget. Or", "cls, plugs ) : plug = next( iter( plugs )", "if not GafferUI.ColorChooser.changesShouldBeMerged( self.__lastChangedReason, reason ) : self.__mergeGroupId += 1", "met: # # * Redistributions of source code must retain", "reason ) : self.__mergeGroupId += 1 self.__lastChangedReason = reason with", "the `acquire()` here and `NodeSetEditor.acquire()` should # actually be functionality", ") self._addPopupMenu( self.__swatch ) self.__swatch.buttonPressSignal().connect( Gaffer.WeakMethod( self.__buttonPress ), scoped =", "actions to merge into a single undo self.__lastChangedReason = None", ": self.setTitle( \"{} plugs\".format( len( self.__plugs ) ) ) self.__plugSet(", "with the dialogue made by the # SplinePlugValueWidget. Or perhaps", ") ) # we use these to decide which actions", "used to endorse or # promote products derived from this", "SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED", "BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR", "reason ) : if not GafferUI.ColorChooser.changesShouldBeMerged( self.__lastChangedReason, reason ) :", "with Gaffer.UndoScope( next( iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode ), mergeGroup", "# * Redistributions in binary form must reproduce the above", "and use in source and binary forms, with or without", "def __buttonPress( self, widget, event ) : if event.buttons ==", "OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import weakref", "PlugValueDialogue base class to share some of the work with", "API? self.__swatch._qtWidget().setMaximumHeight( 20 ) self._addPopupMenu( self.__swatch ) self.__swatch.buttonPressSignal().connect( Gaffer.WeakMethod( self.__buttonPress", "class _ColorPlugValueDialogue( GafferUI.ColorChooserDialogue ) : def __init__( self, plugs, parentWindow", "[ n.plugSetSignal().connect( Gaffer.WeakMethod( self.__plugSet ), scoped = False ) for", "and doesn't have # an \"indeterminate\" state, so when we", "return False if not self._editable() : return False _ColorPlugValueDialogue.acquire( self.getPlugs()", "window.setVisible( True ) return window window = _ColorPlugValueDialogue( plugs, scriptWindow", "Gaffer import GafferUI class ColorSwatchPlugValueWidget( GafferUI.PlugValueWidget ) : def __init__(", "__plugSet( self, plug ) : if plug in self.__plugs :", "code must retain the above # copyright notice, this list", ") return True def _colorFromPlugs( plugs ) : if not", ") : if not len( plugs ) : return imath.Color4f(", "of conditions and the following # disclaimer. # # *", "are # met: # # * Redistributions of source code", "the dialogue made by the # SplinePlugValueWidget. Or perhaps the", "# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,", "event.button != event.Buttons.Left : return False if not self._editable() :", ": plug = next( iter( plugs ) ) script =", "promote products derived from this software without specific prior #", ": with Gaffer.UndoScope( next( iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode )", "self.__plugs : plug.setValue( self.colorChooser().getColor() ) def __buttonClicked( self, button )", "AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN", "else : self.setTitle( \"{} plugs\".format( len( self.__plugs ) ) )", "sum( p.getValue() for p in plugs ) / len( plugs", "self ) # Workaround for https://bugreports.qt-project.org/browse/QTBUG-26761. assert( not self.visible() )", "is self.cancelButton : with Gaffer.UndoScope( next( iter( self.__plugs ) ).ancestor(", "use these to decide which actions to merge into a", "self.__initialValues.items() : p.setValue( v ) self.parent().removeChild( self ) # Workaround", "forms, with or without # modification, are permitted provided that", "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR #", "plugs : window.setVisible( True ) return window window = _ColorPlugValueDialogue(", "TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "binary forms, with or without # modification, are permitted provided", ") def __destroy( self, *unused ) : self.parent().removeChild( self )", "if plug in self.__plugs : with Gaffer.BlockedConnection( self.__colorChangedConnection ) :", "colorChooser, reason ) : if not GafferUI.ColorChooser.changesShouldBeMerged( self.__lastChangedReason, reason )", "software may be used to endorse or # promote products", "How do set maximum height with a public API? self.__swatch._qtWidget().setMaximumHeight(", "= self.colorChooser().colorChangedSignal().connect( Gaffer.WeakMethod( self.__colorChanged ), scoped = False ) self.confirmButton.clickedSignal().connect(", "EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE", ") self.__plugs = plugs self.__initialValues = { p : p.getValue()", "OF SUCH DAMAGE. # ########################################################################## import weakref import imath import", "height with a public API? self.__swatch._qtWidget().setMaximumHeight( 20 ) self._addPopupMenu( self.__swatch", "== plugs : window.setVisible( True ) return window window =", "False ) self.__swatch.buttonReleaseSignal().connect( Gaffer.WeakMethod( self.__buttonRelease ), scoped = False )", "event.Buttons.Left : return True return False def __dragBegin( self, widget,", "node in nodes : node.parentChangedSignal().connect( Gaffer.WeakMethod( self.__destroy ), scoped =", "return True def _colorFromPlugs( plugs ) : if not len(", "len( plugs ) : return imath.Color4f( 0 ) # ColorSwatch", "scriptWindow = GafferUI.ScriptWindow.acquire( script ) for window in scriptWindow.childWindows() :", "@classmethod def acquire( cls, plugs ) : plug = next(", "we can do is take an average. return sum( p.getValue()", "for node in nodes : node.parentChangedSignal().connect( Gaffer.WeakMethod( self.__destroy ), scoped", "# met: # # * Redistributions of source code must", "have # an \"indeterminate\" state, so when we have multiple", "GafferUI class ColorSwatchPlugValueWidget( GafferUI.PlugValueWidget ) : def __init__( self, plugs,", "), scoped = False ) self.cancelButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped", "2013, Image Engine Design Inc. All rights reserved. # #", ": p.setValue( v ) self.parent().removeChild( self ) # Workaround for", "plugs, **kw ) : self.__swatch = GafferUI.ColorSwatch() GafferUI.PlugValueWidget.__init__( self, self.__swatch,", "Gaffer.BlockedConnection( self.__colorChangedConnection ) : self.colorChooser().setColor( _colorFromPlugs( self.__plugs ) ) def", "= reason with Gaffer.UndoScope( next( iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode", "= False ) self._updateFromPlugs() def setHighlighted( self, highlighted ) :", "__buttonPress( self, widget, event ) : if event.buttons == event.Buttons.Left", "= False ) self.confirmButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped = False", "nor the names of # any other contributors to this", "USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED", "Gaffer.WeakMethod( self.__buttonPress ), scoped = False ) self.__swatch.dragBeginSignal().connect( Gaffer.WeakMethod( self.__dragBegin", "average. return sum( p.getValue() for p in plugs ) /", "the public API? Perhaps we could also make a #", "we could also make a # PlugValueDialogue base class to", "= False ) self.__swatch.dragBeginSignal().connect( Gaffer.WeakMethod( self.__dragBegin ), scoped = False", "Gaffer.UndoScope( next( iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode ) ) :", "iter( self.__plugs ) ) if len( self.__plugs ) == 1", "an average. return sum( p.getValue() for p in plugs )", "1 : self.setTitle( plug.relativeName( plug.ancestor( Gaffer.ScriptNode ) ) ) else", "ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT", "self.__buttonPress ), scoped = False ) self.__swatch.dragBeginSignal().connect( Gaffer.WeakMethod( self.__dragBegin ),", "self, self.__swatch, plugs, **kw ) ## \\todo How do set", ": with self.getContext() : value = _colorFromPlugs( self.getPlugs() ) self.__swatch.setColor(", "in self.__plugs : plug.setValue( self.colorChooser().getColor() ) def __buttonClicked( self, button", "value = _colorFromPlugs( self.getPlugs() ) self.__swatch.setColor( value ) def __buttonPress(", "TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF", "FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO", "ARISING IN ANY WAY OUT OF THE USE OF THIS", "def __dragBegin( self, widget, event ) : GafferUI.Pointer.setCurrent( \"rgba\" )", "scriptWindow ) window.setVisible( True ) return False def __plugSet( self,", ": def __init__( self, plugs, parentWindow ) : GafferUI.ColorChooserDialogue.__init__( self,", "event ) : if event.button != event.Buttons.Left : return False", "if button is self.cancelButton : with Gaffer.UndoScope( next( iter( self.__plugs", "# written permission. # # THIS SOFTWARE IS PROVIDED BY", "event.buttons == event.Buttons.Left : return True return False def __dragBegin(", "self, color = _colorFromPlugs( plugs ) ) # we use", "set maximum height with a public API? self.__swatch._qtWidget().setMaximumHeight( 20 )", "other contributors to this software may be used to endorse", "p, v in self.__initialValues.items() : p.setValue( v ) self.parent().removeChild( self", "# disclaimer. # # * Redistributions in binary form must", "of <NAME> nor the names of # any other contributors", "# an \"indeterminate\" state, so when we have multiple plugs", "_colorFromPlugs( self.getPlugs() ) self.__swatch.setColor( value ) def __buttonPress( self, widget,", "self.__plugs } self.__plugSetConnections = [ n.plugSetSignal().connect( Gaffer.WeakMethod( self.__plugSet ), scoped", "highlighted ) def _updateFromPlugs( self ) : with self.getContext() :", ") ) self.__plugSet( plug ) parentWindow.addChildWindow( self, removeOnClose = True", "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY", "plug ) parentWindow.addChildWindow( self, removeOnClose = True ) @classmethod def", "self, colorChooser, reason ) : if not GafferUI.ColorChooser.changesShouldBeMerged( self.__lastChangedReason, reason", "make this a part of the public API? Perhaps we", "# Redistribution and use in source and binary forms, with", "# ColorSwatch only supports one colour, and doesn't have #", "mergeGroup = \"ColorPlugValueDialogue%d%d\" % ( id( self, ), self.__mergeGroupId )", "from this software without specific prior # written permission. #", "and window.__plugs == plugs : window.setVisible( True ) return window", ") : for plug in self.__plugs : plug.setValue( self.colorChooser().getColor() )", "which actions to merge into a single undo self.__lastChangedReason =", "= _colorFromPlugs( self.getPlugs() ) self.__swatch.setColor( value ) def __buttonPress( self,", "THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF", "= True ) @classmethod def acquire( cls, plugs ) :", "__colorChanged( self, colorChooser, reason ) : if not GafferUI.ColorChooser.changesShouldBeMerged( self.__lastChangedReason,", ": GafferUI.Pointer.setCurrent( \"rgba\" ) return self.__swatch.getColor() def __dragEnd( self, widget,", "return False _ColorPlugValueDialogue.acquire( self.getPlugs() ) return True def _colorFromPlugs( plugs", "and the following # disclaimer. # # * Redistributions in", "highlighted ) self.__swatch.setHighlighted( highlighted ) def _updateFromPlugs( self ) :", "best we can do is take an average. return sum(", "self.__colorChanged ), scoped = False ) self.confirmButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ),", ": self.setTitle( plug.relativeName( plug.ancestor( Gaffer.ScriptNode ) ) ) else :", ") self._updateFromPlugs() def setHighlighted( self, highlighted ) : GafferUI.PlugValueWidget.setHighlighted( self,", "* Neither the name of <NAME> nor the names of", "if isinstance( window, cls ) and window.__plugs == plugs :", "\"rgba\" ) return self.__swatch.getColor() def __dragEnd( self, widget, event )", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR #", "# modification, are permitted provided that the following conditions are", ") parentWindow.addChildWindow( self, removeOnClose = True ) @classmethod def acquire(", "self.__lastChangedReason = reason with Gaffer.UndoScope( next( iter( self.__plugs ) ).ancestor(", "OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT", ") : if event.buttons == event.Buttons.Left : return True return", "IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR", "self, plug ) : if plug in self.__plugs : with", ") ).ancestor( Gaffer.ScriptNode ), mergeGroup = \"ColorPlugValueDialogue%d%d\" % ( id(", "STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING", "), scoped = False ) self.__swatch.dragBeginSignal().connect( Gaffer.WeakMethod( self.__dragBegin ), scoped", "False ) self._updateFromPlugs() def setHighlighted( self, highlighted ) : GafferUI.PlugValueWidget.setHighlighted(", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS # IS\" AND ANY", "OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR", "scoped = False ) plug = next( iter( self.__plugs )", "widget, event ) : if event.button != event.Buttons.Left : return", "nodes = { p.node() for p in self.__plugs } self.__plugSetConnections", "if not len( plugs ) : return imath.Color4f( 0 )", ") ) else : self.setTitle( \"{} plugs\".format( len( self.__plugs )", "single undo self.__lastChangedReason = None self.__mergeGroupId = 0 self.__colorChangedConnection =", "p in self.__plugs } self.__plugSetConnections = [ n.plugSetSignal().connect( Gaffer.WeakMethod( self.__plugSet", ": plug.setValue( self.colorChooser().getColor() ) def __buttonClicked( self, button ) :", ": if button is self.cancelButton : with Gaffer.UndoScope( next( iter(", "widget, event ) : GafferUI.Pointer.setCurrent( \"rgba\" ) return self.__swatch.getColor() def", "return False def __dragBegin( self, widget, event ) : GafferUI.Pointer.setCurrent(", ") self.__swatch.dragBeginSignal().connect( Gaffer.WeakMethod( self.__dragBegin ), scoped = False ) self.__swatch.dragEndSignal().connect(", "# # * Redistributions in binary form must reproduce the", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS #", "AND CONTRIBUTORS \"AS # IS\" AND ANY EXPRESS OR IMPLIED", "we could make this a part of the public API?", "plug = next( iter( plugs ) ) script = plug.node().scriptNode()", "`NodeSetEditor.acquire()` should # actually be functionality of CompoundEditor? class _ColorPlugValueDialogue(", "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE", ") ) ) self.__plugSet( plug ) parentWindow.addChildWindow( self, removeOnClose =", "form must reproduce the above # copyright notice, this list", "OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE", "Gaffer.ScriptNode ) ) ) else : self.setTitle( \"{} plugs\".format( len(", "GafferUI.WidgetAlgo.keepUntilIdle( self ) def __destroy( self, *unused ) : self.parent().removeChild(", "# disclaimer in the documentation and/or other materials provided with", "def setHighlighted( self, highlighted ) : GafferUI.PlugValueWidget.setHighlighted( self, highlighted )", ") and window.__plugs == plugs : window.setVisible( True ) return", "SUCH DAMAGE. # ########################################################################## import weakref import imath import Gaffer", "notice, this list of conditions and the following # disclaimer", ": window.setVisible( True ) return window window = _ColorPlugValueDialogue( plugs,", "# # Copyright (c) 2013, <NAME>. All rights reserved. #", "if not self._editable() : return False _ColorPlugValueDialogue.acquire( self.getPlugs() ) return", "one colour, and doesn't have # an \"indeterminate\" state, so", "Gaffer.BlockedConnection( self.__plugSetConnections ) : for plug in self.__plugs : plug.setValue(", "* Redistributions of source code must retain the above #", "LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS", "import Gaffer import GafferUI class ColorSwatchPlugValueWidget( GafferUI.PlugValueWidget ) : def", "notice, this list of conditions and the following # disclaimer.", "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED", "GafferUI.Pointer.setCurrent( None ) def __buttonRelease( self, widget, event ) :", ") # ColorSwatch only supports one colour, and doesn't have", ") @classmethod def acquire( cls, plugs ) : plug =", ": if plug in self.__plugs : with Gaffer.BlockedConnection( self.__colorChangedConnection )", "into a single undo self.__lastChangedReason = None self.__mergeGroupId = 0", "nodes ] for node in nodes : node.parentChangedSignal().connect( Gaffer.WeakMethod( self.__destroy", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "in self.__plugs } nodes = { p.node() for p in", "), mergeGroup = \"ColorPlugValueDialogue%d%d\" % ( id( self, ), self.__mergeGroupId", "removeOnClose = True ) @classmethod def acquire( cls, plugs )", ") self.__swatch.buttonReleaseSignal().connect( Gaffer.WeakMethod( self.__buttonRelease ), scoped = False ) self._updateFromPlugs()", "INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF", "2013, <NAME>. All rights reserved. # Copyright (c) 2013, Image", "self.__lastChangedReason = None self.__mergeGroupId = 0 self.__colorChangedConnection = self.colorChooser().colorChangedSignal().connect( Gaffer.WeakMethod(", "OUT OF THE USE OF THIS # SOFTWARE, EVEN IF", ") : plug = next( iter( plugs ) ) script", "= False ) self.__plugs = plugs self.__initialValues = { p", "BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY,", "Gaffer.UndoScope( next( iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode ), mergeGroup =", "self.__plugs ) ) ) self.__plugSet( plug ) parentWindow.addChildWindow( self, removeOnClose", "to endorse or # promote products derived from this software", ").ancestor( Gaffer.ScriptNode ), mergeGroup = \"ColorPlugValueDialogue%d%d\" % ( id( self,", "BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF #", "in nodes ] for node in nodes : node.parentChangedSignal().connect( Gaffer.WeakMethod(", "copyright notice, this list of conditions and the following #", ") ).ancestor( Gaffer.ScriptNode ) ) : for p, v in", "widget, event ) : GafferUI.Pointer.setCurrent( None ) def __buttonRelease( self,", "multiple plugs # the best we can do is take", "== 1 : self.setTitle( plug.relativeName( plug.ancestor( Gaffer.ScriptNode ) ) )", "self.__plugSetConnections = [ n.plugSetSignal().connect( Gaffer.WeakMethod( self.__plugSet ), scoped = False", "of source code must retain the above # copyright notice,", "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES", "this a part of the public API? Perhaps we could", "we use these to decide which actions to merge into", "script = plug.node().scriptNode() scriptWindow = GafferUI.ScriptWindow.acquire( script ) for window", "def __dragEnd( self, widget, event ) : GafferUI.Pointer.setCurrent( None )", "not self.visible() ) GafferUI.WidgetAlgo.keepUntilIdle( self ) def __destroy( self, *unused", "All rights reserved. # # Redistribution and use in source", "self, widget, event ) : GafferUI.Pointer.setCurrent( None ) def __buttonRelease(", "without # modification, are permitted provided that the following conditions", "provided with # the distribution. # # * Neither the", "acquire( cls, plugs ) : plug = next( iter( plugs", "= plug.node().scriptNode() scriptWindow = GafferUI.ScriptWindow.acquire( script ) for window in", "event.Buttons.Left : return False if not self._editable() : return False", "0 ) # ColorSwatch only supports one colour, and doesn't", "also make a # PlugValueDialogue base class to share some", "for window in scriptWindow.childWindows() : if isinstance( window, cls )", "not GafferUI.ColorChooser.changesShouldBeMerged( self.__lastChangedReason, reason ) : self.__mergeGroupId += 1 self.__lastChangedReason", "), scoped = False ) for n in nodes ]", "self.__plugs ) ).ancestor( Gaffer.ScriptNode ), mergeGroup = \"ColorPlugValueDialogue%d%d\" % (", ": with Gaffer.BlockedConnection( self.__plugSetConnections ) : for plug in self.__plugs", "return imath.Color4f( 0 ) # ColorSwatch only supports one colour,", "self.parent().removeChild( self ) # Workaround for https://bugreports.qt-project.org/browse/QTBUG-26761. assert( not self.visible()", "ColorSwatch only supports one colour, and doesn't have # an", ") : if plug in self.__plugs : with Gaffer.BlockedConnection( self.__colorChangedConnection", "Gaffer.WeakMethod( self.__destroy ), scoped = False ) plug = next(", "nodes : node.parentChangedSignal().connect( Gaffer.WeakMethod( self.__destroy ), scoped = False )", ": for p, v in self.__initialValues.items() : p.setValue( v )", "v ) self.parent().removeChild( self ) # Workaround for https://bugreports.qt-project.org/browse/QTBUG-26761. assert(", "HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, #", "LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN", "), scoped = False ) self._updateFromPlugs() def setHighlighted( self, highlighted", "names of # any other contributors to this software may", "# we use these to decide which actions to merge", "to decide which actions to merge into a single undo", "p : p.getValue() for p in self.__plugs } nodes =", "the distribution. # # * Neither the name of <NAME>", "= _colorFromPlugs( plugs ) ) # we use these to", ") self.__plugSet( plug ) parentWindow.addChildWindow( self, removeOnClose = True )", "of CompoundEditor? class _ColorPlugValueDialogue( GafferUI.ColorChooserDialogue ) : def __init__( self,", "public API? Perhaps we could also make a # PlugValueDialogue", "self.cancelButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped = False ) self.__plugs =", "setHighlighted( self, highlighted ) : GafferUI.PlugValueWidget.setHighlighted( self, highlighted ) self.__swatch.setHighlighted(", "= False ) plug = next( iter( self.__plugs ) )", "reserved. # # Redistribution and use in source and binary", "actually be functionality of CompoundEditor? class _ColorPlugValueDialogue( GafferUI.ColorChooserDialogue ) :", "plug in self.__plugs : plug.setValue( self.colorChooser().getColor() ) def __buttonClicked( self,", ") self.__swatch.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd ), scoped = False ) self.__swatch.buttonReleaseSignal().connect(", "by the # SplinePlugValueWidget. Or perhaps the `acquire()` here and", "of conditions and the following # disclaimer in the documentation", "self.__plugSet( plug ) parentWindow.addChildWindow( self, removeOnClose = True ) @classmethod", "\"{} plugs\".format( len( self.__plugs ) ) ) self.__plugSet( plug )", ") return self.__swatch.getColor() def __dragEnd( self, widget, event ) :", "BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY", "ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,", "LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING #", "self.__plugs ) ).ancestor( Gaffer.ScriptNode ) ) : for p, v", "plug = next( iter( self.__plugs ) ) if len( self.__plugs", ") : for p, v in self.__initialValues.items() : p.setValue( v", "**kw ) : self.__swatch = GafferUI.ColorSwatch() GafferUI.PlugValueWidget.__init__( self, self.__swatch, plugs,", ") : with self.getContext() : value = _colorFromPlugs( self.getPlugs() )", "the names of # any other contributors to this software", "Redistributions in binary form must reproduce the above # copyright", "self.__swatch.buttonReleaseSignal().connect( Gaffer.WeakMethod( self.__buttonRelease ), scoped = False ) self._updateFromPlugs() def", "event ) : GafferUI.Pointer.setCurrent( \"rgba\" ) return self.__swatch.getColor() def __dragEnd(", ") ) def __colorChanged( self, colorChooser, reason ) : if", "def _colorFromPlugs( plugs ) : if not len( plugs )", "= { p.node() for p in self.__plugs } self.__plugSetConnections =", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "ANY WAY OUT OF THE USE OF THIS # SOFTWARE,", "for https://bugreports.qt-project.org/browse/QTBUG-26761. assert( not self.visible() ) GafferUI.WidgetAlgo.keepUntilIdle( self ) def", "0 self.__colorChangedConnection = self.colorChooser().colorChangedSignal().connect( Gaffer.WeakMethod( self.__colorChanged ), scoped = False", ": self.__swatch = GafferUI.ColorSwatch() GafferUI.PlugValueWidget.__init__( self, self.__swatch, plugs, **kw )", "# * Redistributions of source code must retain the above", "self.confirmButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped = False ) self.cancelButton.clickedSignal().connect( Gaffer.WeakMethod(", "plugs # the best we can do is take an", "Copyright (c) 2013, <NAME>. All rights reserved. # Copyright (c)", "LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION)", "p in plugs ) / len( plugs ) ## \\todo", "button ) : if button is self.cancelButton : with Gaffer.UndoScope(", "# ########################################################################## import weakref import imath import Gaffer import GafferUI", "Gaffer.WeakMethod( self.__plugSet ), scoped = False ) for n in", "in binary form must reproduce the above # copyright notice,", "self.__swatch.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd ), scoped = False ) self.__swatch.buttonReleaseSignal().connect( Gaffer.WeakMethod(", "\\todo How do set maximum height with a public API?", ") : if button is self.cancelButton : with Gaffer.UndoScope( next(", "self, highlighted ) self.__swatch.setHighlighted( highlighted ) def _updateFromPlugs( self )", "perhaps the `acquire()` here and `NodeSetEditor.acquire()` should # actually be", ") == 1 : self.setTitle( plug.relativeName( plug.ancestor( Gaffer.ScriptNode ) )", "# Copyright (c) 2013, <NAME>. All rights reserved. # Copyright", "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE", "self._editable() : return False _ColorPlugValueDialogue.acquire( self.getPlugs() ) return True def", "must retain the above # copyright notice, this list of", "20 ) self._addPopupMenu( self.__swatch ) self.__swatch.buttonPressSignal().connect( Gaffer.WeakMethod( self.__buttonPress ), scoped", "iter( plugs ) ) script = plug.node().scriptNode() scriptWindow = GafferUI.ScriptWindow.acquire(", "id( self, ), self.__mergeGroupId ) ) : with Gaffer.BlockedConnection( self.__plugSetConnections", "= plugs self.__initialValues = { p : p.getValue() for p", ") else : self.setTitle( \"{} plugs\".format( len( self.__plugs ) )", "plugs ) / len( plugs ) ## \\todo Perhaps we", "OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON", "GafferUI.ColorChooserDialogue ) : def __init__( self, plugs, parentWindow ) :", ": GafferUI.PlugValueWidget.setHighlighted( self, highlighted ) self.__swatch.setHighlighted( highlighted ) def _updateFromPlugs(", "= { p : p.getValue() for p in self.__plugs }", "for n in nodes ] for node in nodes :", "class to share some of the work with the dialogue", "scoped = False ) self.cancelButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped =", "permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "in self.__initialValues.items() : p.setValue( v ) self.parent().removeChild( self ) #", "= _ColorPlugValueDialogue( plugs, scriptWindow ) window.setVisible( True ) return False", "self.setTitle( \"{} plugs\".format( len( self.__plugs ) ) ) self.__plugSet( plug", "are permitted provided that the following conditions are # met:", "DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE", ") self.confirmButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped = False ) self.cancelButton.clickedSignal().connect(", ") ) : with Gaffer.BlockedConnection( self.__plugSetConnections ) : for plug", "if event.buttons == event.Buttons.Left : return True return False def", "any other contributors to this software may be used to", "plugs self.__initialValues = { p : p.getValue() for p in", "COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS # IS\" AND ANY EXPRESS", "Gaffer.WeakMethod( self.__dragEnd ), scoped = False ) self.__swatch.buttonReleaseSignal().connect( Gaffer.WeakMethod( self.__buttonRelease", "None self.__mergeGroupId = 0 self.__colorChangedConnection = self.colorChooser().colorChangedSignal().connect( Gaffer.WeakMethod( self.__colorChanged ),", "Gaffer.WeakMethod( self.__colorChanged ), scoped = False ) self.confirmButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked", ": GafferUI.Pointer.setCurrent( None ) def __buttonRelease( self, widget, event )", "def __init__( self, plugs, parentWindow ) : GafferUI.ColorChooserDialogue.__init__( self, color", "self.__destroy ), scoped = False ) plug = next( iter(", "share some of the work with the dialogue made by", "__dragEnd( self, widget, event ) : GafferUI.Pointer.setCurrent( None ) def", "reason with Gaffer.UndoScope( next( iter( self.__plugs ) ).ancestor( Gaffer.ScriptNode ),", ": return imath.Color4f( 0 ) # ColorSwatch only supports one", "with Gaffer.BlockedConnection( self.__colorChangedConnection ) : self.colorChooser().setColor( _colorFromPlugs( self.__plugs ) )", "self.__dragBegin ), scoped = False ) self.__swatch.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd ),", "doesn't have # an \"indeterminate\" state, so when we have", "self.getPlugs() ) self.__swatch.setColor( value ) def __buttonPress( self, widget, event", ") def __buttonRelease( self, widget, event ) : if event.button", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS", "p.setValue( v ) self.parent().removeChild( self ) # Workaround for https://bugreports.qt-project.org/browse/QTBUG-26761.", ": GafferUI.ColorChooserDialogue.__init__( self, color = _colorFromPlugs( plugs ) ) #", "public API? self.__swatch._qtWidget().setMaximumHeight( 20 ) self._addPopupMenu( self.__swatch ) self.__swatch.buttonPressSignal().connect( Gaffer.WeakMethod(", "self.__swatch.setHighlighted( highlighted ) def _updateFromPlugs( self ) : with self.getContext()", ": return False if not self._editable() : return False _ColorPlugValueDialogue.acquire(", "), scoped = False ) self.confirmButton.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ), scoped", "!= event.Buttons.Left : return False if not self._editable() : return", "when we have multiple plugs # the best we can", "self.__plugs ) == 1 : self.setTitle( plug.relativeName( plug.ancestor( Gaffer.ScriptNode )", ") : if not GafferUI.ColorChooser.changesShouldBeMerged( self.__lastChangedReason, reason ) : self.__mergeGroupId", "= False ) self.__swatch.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd ), scoped = False", "derived from this software without specific prior # written permission.", "window.setVisible( True ) return False def __plugSet( self, plug )", "software without specific prior # written permission. # # THIS", "== event.Buttons.Left : return True return False def __dragBegin( self,", "PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER", "of the public API? Perhaps we could also make a", "self.setTitle( plug.relativeName( plug.ancestor( Gaffer.ScriptNode ) ) ) else : self.setTitle(", "list of conditions and the following # disclaimer. # #", "DAMAGE. # ########################################################################## import weakref import imath import Gaffer import", "plugs ) ## \\todo Perhaps we could make this a", "so when we have multiple plugs # the best we", "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, #", "self.colorChooser().getColor() ) def __buttonClicked( self, button ) : if button", "# actually be functionality of CompoundEditor? class _ColorPlugValueDialogue( GafferUI.ColorChooserDialogue )", "def __plugSet( self, plug ) : if plug in self.__plugs", "OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED", "plug in self.__plugs : with Gaffer.BlockedConnection( self.__colorChangedConnection ) : self.colorChooser().setColor(", "the following # disclaimer. # # * Redistributions in binary", "window = _ColorPlugValueDialogue( plugs, scriptWindow ) window.setVisible( True ) return", "), scoped = False ) self.__swatch.buttonReleaseSignal().connect( Gaffer.WeakMethod( self.__buttonRelease ), scoped", "be used to endorse or # promote products derived from", "IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ##########################################################################", "the best we can do is take an average. return", "self, removeOnClose = True ) @classmethod def acquire( cls, plugs", "in the documentation and/or other materials provided with # the", "<NAME> nor the names of # any other contributors to", "# # * Neither the name of <NAME> nor the", "imath import Gaffer import GafferUI class ColorSwatchPlugValueWidget( GafferUI.PlugValueWidget ) :", "event ) : GafferUI.Pointer.setCurrent( None ) def __buttonRelease( self, widget,", "import weakref import imath import Gaffer import GafferUI class ColorSwatchPlugValueWidget(", "SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS", "we have multiple plugs # the best we can do", "len( self.__plugs ) ) ) self.__plugSet( plug ) parentWindow.addChildWindow( self,", "= next( iter( plugs ) ) script = plug.node().scriptNode() scriptWindow", "self ) def __destroy( self, *unused ) : self.parent().removeChild( self", "not len( plugs ) : return imath.Color4f( 0 ) #", "Or perhaps the `acquire()` here and `NodeSetEditor.acquire()` should # actually", "( id( self, ), self.__mergeGroupId ) ) : with Gaffer.BlockedConnection(", "self, widget, event ) : GafferUI.Pointer.setCurrent( \"rgba\" ) return self.__swatch.getColor()", "scriptWindow.childWindows() : if isinstance( window, cls ) and window.__plugs ==", "could make this a part of the public API? Perhaps", ") ## \\todo How do set maximum height with a", "= False ) for n in nodes ] for node", "__buttonClicked( self, button ) : if button is self.cancelButton :", "self ) : with self.getContext() : value = _colorFromPlugs( self.getPlugs()", "ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import", "_ColorPlugValueDialogue( GafferUI.ColorChooserDialogue ) : def __init__( self, plugs, parentWindow )", ") : def __init__( self, plugs, parentWindow ) : GafferUI.ColorChooserDialogue.__init__(", "(INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS", "conditions and the following # disclaimer. # # * Redistributions", "products derived from this software without specific prior # written", "self.colorChooser().colorChangedSignal().connect( Gaffer.WeakMethod( self.__colorChanged ), scoped = False ) self.confirmButton.clickedSignal().connect( Gaffer.WeakMethod(", "the work with the dialogue made by the # SplinePlugValueWidget.", ") self.parent().removeChild( self ) # Workaround for https://bugreports.qt-project.org/browse/QTBUG-26761. assert( not", "scoped = False ) self.__plugs = plugs self.__initialValues = {", "window in scriptWindow.childWindows() : if isinstance( window, cls ) and", "button is self.cancelButton : with Gaffer.UndoScope( next( iter( self.__plugs )", "node.parentChangedSignal().connect( Gaffer.WeakMethod( self.__destroy ), scoped = False ) plug =", "IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS", "for plug in self.__plugs : plug.setValue( self.colorChooser().getColor() ) def __buttonClicked(", ") # Workaround for https://bugreports.qt-project.org/browse/QTBUG-26761. assert( not self.visible() ) GafferUI.WidgetAlgo.keepUntilIdle(", "self.__plugSetConnections ) : for plug in self.__plugs : plug.setValue( self.colorChooser().getColor()", ") ) script = plug.node().scriptNode() scriptWindow = GafferUI.ScriptWindow.acquire( script )", "False ) self.__swatch.dragEndSignal().connect( Gaffer.WeakMethod( self.__dragEnd ), scoped = False )", "<NAME>. All rights reserved. # Copyright (c) 2013, Image Engine", "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR" ]
[ "models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('choosing', models.BooleanField(default=False)), ('time_in', models.DateTimeField(auto_now_add=True)), ('title', models.CharField(max_length=255,", "Generated by Django 3.2 on 2021-04-15 18:05 from django.conf import", "django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL),", "('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category', models.CharField(default='select category', max_length=255, unique=True)),", "verbose_name='ID')), ('author', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Category', fields=[ ('id',", "18:05 from django.conf import settings from django.db import migrations, models", "= True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [", "max_length=255, unique=True)), ('subscriber', models.ManyToManyField(related_name='subscriber', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Post', fields=[", "Django 3.2 on 2021-04-15 18:05 from django.conf import settings from", "migrations.CreateModel( name='Post', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('choosing', models.BooleanField(default=False)),", "('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('choosing', models.BooleanField(default=False)), ('time_in', models.DateTimeField(auto_now_add=True)), ('title',", "name='Post', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('choosing', models.BooleanField(default=False)), ('time_in',", "migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Author', fields=[ ('id', models.BigAutoField(auto_created=True,", "dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Author',", "('text', models.TextField(max_length=255)), ('rating', models.FloatField(default=0.0)), ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='News.author', verbose_name='User')),", "= [ migrations.CreateModel( name='Author', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Category', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True,", "3.2 on 2021-04-15 18:05 from django.conf import settings from django.db", "import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [", "import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True", "[ migrations.CreateModel( name='Author', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('author',", "('choosing', models.BooleanField(default=False)), ('time_in', models.DateTimeField(auto_now_add=True)), ('title', models.CharField(max_length=255, unique=True)), ('text', models.TextField(max_length=255)), ('rating',", "), migrations.CreateModel( name='Post', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('choosing',", "] operations = [ migrations.CreateModel( name='Author', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True,", "by Django 3.2 on 2021-04-15 18:05 from django.conf import settings", "migrations.CreateModel( name='Author', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('author', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE,", "], ), migrations.CreateModel( name='Category', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "primary_key=True, serialize=False, verbose_name='ID')), ('category', models.CharField(default='select category', max_length=255, unique=True)), ('subscriber', models.ManyToManyField(related_name='subscriber',", "('category', models.CharField(default='select category', max_length=255, unique=True)), ('subscriber', models.ManyToManyField(related_name='subscriber', to=settings.AUTH_USER_MODEL)), ], ),", "models.CharField(default='select category', max_length=255, unique=True)), ('subscriber', models.ManyToManyField(related_name='subscriber', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel(", "serialize=False, verbose_name='ID')), ('choosing', models.BooleanField(default=False)), ('time_in', models.DateTimeField(auto_now_add=True)), ('title', models.CharField(max_length=255, unique=True)), ('text',", "import settings from django.db import migrations, models import django.db.models.deletion class", "models.BooleanField(default=False)), ('time_in', models.DateTimeField(auto_now_add=True)), ('title', models.CharField(max_length=255, unique=True)), ('text', models.TextField(max_length=255)), ('rating', models.FloatField(default=0.0)),", "('author', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Category', fields=[ ('id', models.BigAutoField(auto_created=True,", "models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies =", "django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =", "models.CharField(max_length=255, unique=True)), ('text', models.TextField(max_length=255)), ('rating', models.FloatField(default=0.0)), ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,", "initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations =", "2021-04-15 18:05 from django.conf import settings from django.db import migrations,", "), migrations.CreateModel( name='Category', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category',", "models.ManyToManyField(related_name='subscriber', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Post', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True,", "name='Category', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category', models.CharField(default='select category',", "('subscriber', models.ManyToManyField(related_name='subscriber', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Post', fields=[ ('id', models.BigAutoField(auto_created=True,", "name='Author', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('author', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),", "from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial", "('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('author', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ),", "[ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Author', fields=[ ('id',", "class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ]", "primary_key=True, serialize=False, verbose_name='ID')), ('author', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Category',", "migrations.CreateModel( name='Category', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category', models.CharField(default='select", "unique=True)), ('subscriber', models.ManyToManyField(related_name='subscriber', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Post', fields=[ ('id',", "models.TextField(max_length=255)), ('rating', models.FloatField(default=0.0)), ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='News.author', verbose_name='User')), ('category',", "verbose_name='ID')), ('choosing', models.BooleanField(default=False)), ('time_in', models.DateTimeField(auto_now_add=True)), ('title', models.CharField(max_length=255, unique=True)), ('text', models.TextField(max_length=255)),", "on 2021-04-15 18:05 from django.conf import settings from django.db import", "True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel(", "verbose_name='ID')), ('category', models.CharField(default='select category', max_length=255, unique=True)), ('subscriber', models.ManyToManyField(related_name='subscriber', to=settings.AUTH_USER_MODEL)), ],", "migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies", "Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations", "to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Category', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,", "<reponame>GregTMJ/django-files<gh_stars>1-10 # Generated by Django 3.2 on 2021-04-15 18:05 from", "('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='News.author', verbose_name='User')), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='News.category')), ],", "to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Post', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,", "serialize=False, verbose_name='ID')), ('category', models.CharField(default='select category', max_length=255, unique=True)), ('subscriber', models.ManyToManyField(related_name='subscriber', to=settings.AUTH_USER_MODEL)),", "unique=True)), ('text', models.TextField(max_length=255)), ('rating', models.FloatField(default=0.0)), ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='News.author',", "# Generated by Django 3.2 on 2021-04-15 18:05 from django.conf", "('time_in', models.DateTimeField(auto_now_add=True)), ('title', models.CharField(max_length=255, unique=True)), ('text', models.TextField(max_length=255)), ('rating', models.FloatField(default=0.0)), ('author',", "('title', models.CharField(max_length=255, unique=True)), ('text', models.TextField(max_length=255)), ('rating', models.FloatField(default=0.0)), ('author', models.ForeignKey(blank=True, null=True,", "], ), migrations.CreateModel( name='Post', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "models.FloatField(default=0.0)), ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='News.author', verbose_name='User')), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='News.category')),", "fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('author', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ],", "models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('author', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel(", "models.DateTimeField(auto_now_add=True)), ('title', models.CharField(max_length=255, unique=True)), ('text', models.TextField(max_length=255)), ('rating', models.FloatField(default=0.0)), ('author', models.ForeignKey(blank=True,", "models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category', models.CharField(default='select category', max_length=255, unique=True)), ('subscriber',", "models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='News.author', verbose_name='User')), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='News.category')), ], ),", "category', max_length=255, unique=True)), ('subscriber', models.ManyToManyField(related_name='subscriber', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Post',", "('rating', models.FloatField(default=0.0)), ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='News.author', verbose_name='User')), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "from django.conf import settings from django.db import migrations, models import", "operations = [ migrations.CreateModel( name='Author', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,", "= [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Author', fields=[", "serialize=False, verbose_name='ID')), ('author', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Category', fields=[", "settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):", "django.conf import settings from django.db import migrations, models import django.db.models.deletion", "primary_key=True, serialize=False, verbose_name='ID')), ('choosing', models.BooleanField(default=False)), ('time_in', models.DateTimeField(auto_now_add=True)), ('title', models.CharField(max_length=255, unique=True)),", "null=True, on_delete=django.db.models.deletion.CASCADE, to='News.author', verbose_name='User')), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='News.category')), ], ), ]", "fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category', models.CharField(default='select category', max_length=255,", "fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('choosing', models.BooleanField(default=False)), ('time_in', models.DateTimeField(auto_now_add=True))," ]
[ "ev._EvalWordPart(unset_sub, part_vals) print(part_vals) part_vals = [] ev._EvalWordPart(set_sub, part_vals) print(part_vals) if", "compliance with the License. # You may obtain a copy", "2.0 (the \"License\"); # you may not use this file", "file except in compliance with the License. # You may", "from core.meta import syntax_asdl, Id from osh import state suffix_op", "Copyright 2016 <NAME>. All rights reserved. # Licensed under the", "= test_lib.MakeTestEvaluator() state.SetLocalString(word_ev.mem, 'x', 'xxx') state.SetLocalString(word_ev.mem, 'y', 'yyy') return word_ev", "# http://www.apache.org/licenses/LICENSE-2.0 \"\"\" cmd_exec_test.py: Tests for cmd_exec.py \"\"\" import unittest", "# initializes x=xxx and y=yyy unset_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'unset')) part_vals", "set_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'x')) part_vals = [] ev._EvalWordPart(set_sub, part_vals) print(part_vals)", "test_lib.MakeArena('<cmd_exec_test.py>') c_parser = test_lib.InitCommandParser('echo _{a,b}_', arena=arena) node = c_parser._ParseCommandLine() print(node)", "syntax_asdl, Id from osh import state suffix_op = syntax_asdl.suffix_op osh_word", "core import test_lib from core.meta import syntax_asdl, Id from osh", "# Now add some ops part = word_part.LiteralPart(syntax_asdl.token(Id.Lit_Chars, 'default')) arg_word", "from osh import state suffix_op = syntax_asdl.suffix_op osh_word = syntax_asdl.word", "'x', 'xxx') state.SetLocalString(word_ev.mem, 'y', 'yyy') return word_ev class ExpansionTest(unittest.TestCase): def", "\"\"\" cmd_exec_test.py: Tests for cmd_exec.py \"\"\" import unittest from core", "except in compliance with the License. # You may obtain", "c_parser = test_lib.InitCommandParser('echo _{a,b}_', arena=arena) node = c_parser._ParseCommandLine() print(node) ex", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "= [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) part_vals = [] ev._EvalWordPart(set_sub, part_vals)", "not use this file except in compliance with the License.", "part_vals = [] ev._EvalWordPart(set_sub, part_vals) print(part_vals) # Now add some", "testVarOps(self): ev = InitEvaluator() # initializes x=xxx and y=yyy unset_sub", "set_sub.suffix_op = test_op part_vals = [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) part_vals", "part_vals) print(part_vals) set_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'x')) part_vals = [] ev._EvalWordPart(set_sub,", "unset_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'unset')) part_vals = [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals)", "'xxx') state.SetLocalString(word_ev.mem, 'y', 'yyy') return word_ev class ExpansionTest(unittest.TestCase): def testBraceExpand(self):", "you may not use this file except in compliance with", "'default')) arg_word = osh_word.CompoundWord([part]) test_op = suffix_op.StringUnary(Id.VTest_ColonHyphen, arg_word) unset_sub.suffix_op =", "class ExpansionTest(unittest.TestCase): def testBraceExpand(self): arena = test_lib.MakeArena('<cmd_exec_test.py>') c_parser = test_lib.InitCommandParser('echo", "testBraceExpand(self): arena = test_lib.MakeArena('<cmd_exec_test.py>') c_parser = test_lib.InitCommandParser('echo _{a,b}_', arena=arena) node", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "part_vals = [] ev._EvalWordPart(set_sub, part_vals) print(part_vals) if __name__ == '__main__':", "Now add some ops part = word_part.LiteralPart(syntax_asdl.token(Id.Lit_Chars, 'default')) arg_word =", "ops part = word_part.LiteralPart(syntax_asdl.token(Id.Lit_Chars, 'default')) arg_word = osh_word.CompoundWord([part]) test_op =", "def testBraceExpand(self): arena = test_lib.MakeArena('<cmd_exec_test.py>') c_parser = test_lib.InitCommandParser('echo _{a,b}_', arena=arena)", "use this file except in compliance with the License. #", "syntax_asdl.suffix_op osh_word = syntax_asdl.word word_part = syntax_asdl.word_part def InitEvaluator(): word_ev", "c_parser._ParseCommandLine() print(node) ex = test_lib.InitExecutor(arena=arena) #print(ex.Execute(node)) #print(ex._ExpandWords(node.words)) class VarOpTest(unittest.TestCase): def", "print(part_vals) set_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'x')) part_vals = [] ev._EvalWordPart(set_sub, part_vals)", "= word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'x')) part_vals = [] ev._EvalWordPart(set_sub, part_vals) print(part_vals) #", "part_vals = [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) part_vals = [] ev._EvalWordPart(set_sub,", "#print(ex.Execute(node)) #print(ex._ExpandWords(node.words)) class VarOpTest(unittest.TestCase): def testVarOps(self): ev = InitEvaluator() #", "= word_part.LiteralPart(syntax_asdl.token(Id.Lit_Chars, 'default')) arg_word = osh_word.CompoundWord([part]) test_op = suffix_op.StringUnary(Id.VTest_ColonHyphen, arg_word)", "state.SetLocalString(word_ev.mem, 'x', 'xxx') state.SetLocalString(word_ev.mem, 'y', 'yyy') return word_ev class ExpansionTest(unittest.TestCase):", "ev._EvalWordPart(unset_sub, part_vals) print(part_vals) set_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'x')) part_vals = []", "word_part = syntax_asdl.word_part def InitEvaluator(): word_ev = test_lib.MakeTestEvaluator() state.SetLocalString(word_ev.mem, 'x',", "= suffix_op.StringUnary(Id.VTest_ColonHyphen, arg_word) unset_sub.suffix_op = test_op set_sub.suffix_op = test_op part_vals", "License. # You may obtain a copy of the License", "License, Version 2.0 (the \"License\"); # you may not use", "# # http://www.apache.org/licenses/LICENSE-2.0 \"\"\" cmd_exec_test.py: Tests for cmd_exec.py \"\"\" import", "osh_word.CompoundWord([part]) test_op = suffix_op.StringUnary(Id.VTest_ColonHyphen, arg_word) unset_sub.suffix_op = test_op set_sub.suffix_op =", "# You may obtain a copy of the License at", "syntax_asdl.word_part def InitEvaluator(): word_ev = test_lib.MakeTestEvaluator() state.SetLocalString(word_ev.mem, 'x', 'xxx') state.SetLocalString(word_ev.mem,", "cmd_exec_test.py: Tests for cmd_exec.py \"\"\" import unittest from core import", "and y=yyy unset_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'unset')) part_vals = [] ev._EvalWordPart(unset_sub,", "#!/usr/bin/env python # Copyright 2016 <NAME>. All rights reserved. #", "import test_lib from core.meta import syntax_asdl, Id from osh import", "cmd_exec.py \"\"\" import unittest from core import test_lib from core.meta", "= InitEvaluator() # initializes x=xxx and y=yyy unset_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name,", "word_ev class ExpansionTest(unittest.TestCase): def testBraceExpand(self): arena = test_lib.MakeArena('<cmd_exec_test.py>') c_parser =", "test_lib.MakeTestEvaluator() state.SetLocalString(word_ev.mem, 'x', 'xxx') state.SetLocalString(word_ev.mem, 'y', 'yyy') return word_ev class", "= c_parser._ParseCommandLine() print(node) ex = test_lib.InitExecutor(arena=arena) #print(ex.Execute(node)) #print(ex._ExpandWords(node.words)) class VarOpTest(unittest.TestCase):", "import unittest from core import test_lib from core.meta import syntax_asdl,", "'unset')) part_vals = [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) set_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name,", "InitEvaluator(): word_ev = test_lib.MakeTestEvaluator() state.SetLocalString(word_ev.mem, 'x', 'xxx') state.SetLocalString(word_ev.mem, 'y', 'yyy')", "state.SetLocalString(word_ev.mem, 'y', 'yyy') return word_ev class ExpansionTest(unittest.TestCase): def testBraceExpand(self): arena", "part = word_part.LiteralPart(syntax_asdl.token(Id.Lit_Chars, 'default')) arg_word = osh_word.CompoundWord([part]) test_op = suffix_op.StringUnary(Id.VTest_ColonHyphen,", "part_vals) print(part_vals) # Now add some ops part = word_part.LiteralPart(syntax_asdl.token(Id.Lit_Chars,", "unset_sub.suffix_op = test_op set_sub.suffix_op = test_op part_vals = [] ev._EvalWordPart(unset_sub,", "word_part.LiteralPart(syntax_asdl.token(Id.Lit_Chars, 'default')) arg_word = osh_word.CompoundWord([part]) test_op = suffix_op.StringUnary(Id.VTest_ColonHyphen, arg_word) unset_sub.suffix_op", "InitEvaluator() # initializes x=xxx and y=yyy unset_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'unset'))", "return word_ev class ExpansionTest(unittest.TestCase): def testBraceExpand(self): arena = test_lib.MakeArena('<cmd_exec_test.py>') c_parser", "suffix_op = syntax_asdl.suffix_op osh_word = syntax_asdl.word word_part = syntax_asdl.word_part def", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 \"\"\" cmd_exec_test.py: Tests", "x=xxx and y=yyy unset_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'unset')) part_vals = []", "(the \"License\"); # you may not use this file except", "'x')) part_vals = [] ev._EvalWordPart(set_sub, part_vals) print(part_vals) # Now add", "test_lib.InitExecutor(arena=arena) #print(ex.Execute(node)) #print(ex._ExpandWords(node.words)) class VarOpTest(unittest.TestCase): def testVarOps(self): ev = InitEvaluator()", "Apache License, Version 2.0 (the \"License\"); # you may not", "ex = test_lib.InitExecutor(arena=arena) #print(ex.Execute(node)) #print(ex._ExpandWords(node.words)) class VarOpTest(unittest.TestCase): def testVarOps(self): ev", "word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'unset')) part_vals = [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) set_sub =", "# you may not use this file except in compliance", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 \"\"\" cmd_exec_test.py: Tests for", "at # # http://www.apache.org/licenses/LICENSE-2.0 \"\"\" cmd_exec_test.py: Tests for cmd_exec.py \"\"\"", "ev._EvalWordPart(set_sub, part_vals) print(part_vals) # Now add some ops part =", "All rights reserved. # Licensed under the Apache License, Version", "part_vals) print(part_vals) part_vals = [] ev._EvalWordPart(set_sub, part_vals) print(part_vals) if __name__", "# Copyright 2016 <NAME>. All rights reserved. # Licensed under", "suffix_op.StringUnary(Id.VTest_ColonHyphen, arg_word) unset_sub.suffix_op = test_op set_sub.suffix_op = test_op part_vals =", "[] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) part_vals = [] ev._EvalWordPart(set_sub, part_vals) print(part_vals)", "= test_lib.MakeArena('<cmd_exec_test.py>') c_parser = test_lib.InitCommandParser('echo _{a,b}_', arena=arena) node = c_parser._ParseCommandLine()", "in compliance with the License. # You may obtain a", "http://www.apache.org/licenses/LICENSE-2.0 \"\"\" cmd_exec_test.py: Tests for cmd_exec.py \"\"\" import unittest from", "#print(ex._ExpandWords(node.words)) class VarOpTest(unittest.TestCase): def testVarOps(self): ev = InitEvaluator() # initializes", "test_op part_vals = [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) part_vals = []", "initializes x=xxx and y=yyy unset_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'unset')) part_vals =", "test_op set_sub.suffix_op = test_op part_vals = [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals)", "= osh_word.CompoundWord([part]) test_op = suffix_op.StringUnary(Id.VTest_ColonHyphen, arg_word) unset_sub.suffix_op = test_op set_sub.suffix_op", "2016 <NAME>. All rights reserved. # Licensed under the Apache", "add some ops part = word_part.LiteralPart(syntax_asdl.token(Id.Lit_Chars, 'default')) arg_word = osh_word.CompoundWord([part])", "arg_word = osh_word.CompoundWord([part]) test_op = suffix_op.StringUnary(Id.VTest_ColonHyphen, arg_word) unset_sub.suffix_op = test_op", "License at # # http://www.apache.org/licenses/LICENSE-2.0 \"\"\" cmd_exec_test.py: Tests for cmd_exec.py", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "arena = test_lib.MakeArena('<cmd_exec_test.py>') c_parser = test_lib.InitCommandParser('echo _{a,b}_', arena=arena) node =", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 \"\"\"", "reserved. # Licensed under the Apache License, Version 2.0 (the", "for cmd_exec.py \"\"\" import unittest from core import test_lib from", "Version 2.0 (the \"License\"); # you may not use this", "Tests for cmd_exec.py \"\"\" import unittest from core import test_lib", "core.meta import syntax_asdl, Id from osh import state suffix_op =", "y=yyy unset_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'unset')) part_vals = [] ev._EvalWordPart(unset_sub, part_vals)", "from core import test_lib from core.meta import syntax_asdl, Id from", "'yyy') return word_ev class ExpansionTest(unittest.TestCase): def testBraceExpand(self): arena = test_lib.MakeArena('<cmd_exec_test.py>')", "ExpansionTest(unittest.TestCase): def testBraceExpand(self): arena = test_lib.MakeArena('<cmd_exec_test.py>') c_parser = test_lib.InitCommandParser('echo _{a,b}_',", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 \"\"\" cmd_exec_test.py:", "test_lib.InitCommandParser('echo _{a,b}_', arena=arena) node = c_parser._ParseCommandLine() print(node) ex = test_lib.InitExecutor(arena=arena)", "unittest from core import test_lib from core.meta import syntax_asdl, Id", "= syntax_asdl.word word_part = syntax_asdl.word_part def InitEvaluator(): word_ev = test_lib.MakeTestEvaluator()", "python # Copyright 2016 <NAME>. All rights reserved. # Licensed", "syntax_asdl.word word_part = syntax_asdl.word_part def InitEvaluator(): word_ev = test_lib.MakeTestEvaluator() state.SetLocalString(word_ev.mem,", "under the Apache License, Version 2.0 (the \"License\"); # you", "= [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) set_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'x')) part_vals", "\"License\"); # you may not use this file except in", "'y', 'yyy') return word_ev class ExpansionTest(unittest.TestCase): def testBraceExpand(self): arena =", "def InitEvaluator(): word_ev = test_lib.MakeTestEvaluator() state.SetLocalString(word_ev.mem, 'x', 'xxx') state.SetLocalString(word_ev.mem, 'y',", "= syntax_asdl.word_part def InitEvaluator(): word_ev = test_lib.MakeTestEvaluator() state.SetLocalString(word_ev.mem, 'x', 'xxx')", "= test_lib.InitExecutor(arena=arena) #print(ex.Execute(node)) #print(ex._ExpandWords(node.words)) class VarOpTest(unittest.TestCase): def testVarOps(self): ev =", "may obtain a copy of the License at # #", "some ops part = word_part.LiteralPart(syntax_asdl.token(Id.Lit_Chars, 'default')) arg_word = osh_word.CompoundWord([part]) test_op", "= test_lib.InitCommandParser('echo _{a,b}_', arena=arena) node = c_parser._ParseCommandLine() print(node) ex =", "word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'x')) part_vals = [] ev._EvalWordPart(set_sub, part_vals) print(part_vals) # Now", "[] ev._EvalWordPart(set_sub, part_vals) print(part_vals) # Now add some ops part", "word_ev = test_lib.MakeTestEvaluator() state.SetLocalString(word_ev.mem, 'x', 'xxx') state.SetLocalString(word_ev.mem, 'y', 'yyy') return", "= word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'unset')) part_vals = [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) set_sub", "the License. # You may obtain a copy of the", "<NAME>. All rights reserved. # Licensed under the Apache License,", "import syntax_asdl, Id from osh import state suffix_op = syntax_asdl.suffix_op", "= [] ev._EvalWordPart(set_sub, part_vals) print(part_vals) # Now add some ops", "test_op = suffix_op.StringUnary(Id.VTest_ColonHyphen, arg_word) unset_sub.suffix_op = test_op set_sub.suffix_op = test_op", "import state suffix_op = syntax_asdl.suffix_op osh_word = syntax_asdl.word word_part =", "ev = InitEvaluator() # initializes x=xxx and y=yyy unset_sub =", "test_lib from core.meta import syntax_asdl, Id from osh import state", "_{a,b}_', arena=arena) node = c_parser._ParseCommandLine() print(node) ex = test_lib.InitExecutor(arena=arena) #print(ex.Execute(node))", "print(part_vals) part_vals = [] ev._EvalWordPart(set_sub, part_vals) print(part_vals) if __name__ ==", "osh_word = syntax_asdl.word word_part = syntax_asdl.word_part def InitEvaluator(): word_ev =", "arena=arena) node = c_parser._ParseCommandLine() print(node) ex = test_lib.InitExecutor(arena=arena) #print(ex.Execute(node)) #print(ex._ExpandWords(node.words))", "You may obtain a copy of the License at #", "= test_op part_vals = [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) part_vals =", "state suffix_op = syntax_asdl.suffix_op osh_word = syntax_asdl.word word_part = syntax_asdl.word_part", "class VarOpTest(unittest.TestCase): def testVarOps(self): ev = InitEvaluator() # initializes x=xxx", "may not use this file except in compliance with the", "= [] ev._EvalWordPart(set_sub, part_vals) print(part_vals) if __name__ == '__main__': unittest.main()", "[] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) set_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'x')) part_vals =", "rights reserved. # Licensed under the Apache License, Version 2.0", "part_vals = [] ev._EvalWordPart(unset_sub, part_vals) print(part_vals) set_sub = word_part.BracedVarSub(syntax_asdl.token(Id.VSub_Name, 'x'))", "print(part_vals) # Now add some ops part = word_part.LiteralPart(syntax_asdl.token(Id.Lit_Chars, 'default'))", "def testVarOps(self): ev = InitEvaluator() # initializes x=xxx and y=yyy", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "osh import state suffix_op = syntax_asdl.suffix_op osh_word = syntax_asdl.word word_part", "= syntax_asdl.suffix_op osh_word = syntax_asdl.word word_part = syntax_asdl.word_part def InitEvaluator():", "the Apache License, Version 2.0 (the \"License\"); # you may", "\"\"\" import unittest from core import test_lib from core.meta import", "print(node) ex = test_lib.InitExecutor(arena=arena) #print(ex.Execute(node)) #print(ex._ExpandWords(node.words)) class VarOpTest(unittest.TestCase): def testVarOps(self):", "arg_word) unset_sub.suffix_op = test_op set_sub.suffix_op = test_op part_vals = []", "= test_op set_sub.suffix_op = test_op part_vals = [] ev._EvalWordPart(unset_sub, part_vals)", "VarOpTest(unittest.TestCase): def testVarOps(self): ev = InitEvaluator() # initializes x=xxx and", "node = c_parser._ParseCommandLine() print(node) ex = test_lib.InitExecutor(arena=arena) #print(ex.Execute(node)) #print(ex._ExpandWords(node.words)) class", "Id from osh import state suffix_op = syntax_asdl.suffix_op osh_word =" ]
[ "'0019_merge_20190524_1719'), ] operations = [ migrations.AlterField( model_name='exportmedia', name='file', field=models.FileField(upload_to='export/%Y/%m/', verbose_name='file'),", "= [ ('blitz_api', '0019_merge_20190524_1719'), ] operations = [ migrations.AlterField( model_name='exportmedia',", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('blitz_api', '0019_merge_20190524_1719'),", "migrations, models class Migration(migrations.Migration): dependencies = [ ('blitz_api', '0019_merge_20190524_1719'), ]", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blitz_api',", "on 2019-05-29 16:00 from django.db import migrations, models class Migration(migrations.Migration):", "[ ('blitz_api', '0019_merge_20190524_1719'), ] operations = [ migrations.AlterField( model_name='exportmedia', name='file',", "Django 2.0.8 on 2019-05-29 16:00 from django.db import migrations, models", "16:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "2.0.8 on 2019-05-29 16:00 from django.db import migrations, models class", "2019-05-29 16:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "Migration(migrations.Migration): dependencies = [ ('blitz_api', '0019_merge_20190524_1719'), ] operations = [", "dependencies = [ ('blitz_api', '0019_merge_20190524_1719'), ] operations = [ migrations.AlterField(", "('blitz_api', '0019_merge_20190524_1719'), ] operations = [ migrations.AlterField( model_name='exportmedia', name='file', field=models.FileField(upload_to='export/%Y/%m/',", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "] operations = [ migrations.AlterField( model_name='exportmedia', name='file', field=models.FileField(upload_to='export/%Y/%m/', verbose_name='file'), ),", "class Migration(migrations.Migration): dependencies = [ ('blitz_api', '0019_merge_20190524_1719'), ] operations =", "by Django 2.0.8 on 2019-05-29 16:00 from django.db import migrations,", "operations = [ migrations.AlterField( model_name='exportmedia', name='file', field=models.FileField(upload_to='export/%Y/%m/', verbose_name='file'), ), ]", "Generated by Django 2.0.8 on 2019-05-29 16:00 from django.db import", "models class Migration(migrations.Migration): dependencies = [ ('blitz_api', '0019_merge_20190524_1719'), ] operations", "# Generated by Django 2.0.8 on 2019-05-29 16:00 from django.db" ]
[ "python from .api import capture __version__ = \"0.0.7\" __all__ =", "from .api import capture __version__ = \"0.0.7\" __all__ = (\"capture\",)", "#!/usr/bin/env python from .api import capture __version__ = \"0.0.7\" __all__" ]
[ "* log_pi_v).sum(dim=1).mean() loss_entropy_v = -1.0 * self.params.ENTROPY_LOSS_WEIGHT * entropy_v #", "= \"AgentDiscreteA2C\" self.worker_id = worker_id self.model = rl_utils.get_rl_model( worker_id=worker_id, input_shape=input_shape,", "input_shape, num_outputs, train_action_selector, test_and_play_action_selector, params, device ): assert isinstance(train_action_selector, ProbabilityActionSelector)", "loss_entropy_v loss_actor_and_entropy_v.backward() #nn_utils.clip_grad_norm_(self.model.base.actor.parameters(), self.params.CLIP_GRAD) self.actor_optimizer.step() gradients = self.model.get_gradients_for_current_parameters() return gradients,", "self.critic_optimizer = rl_utils.get_optimizer( parameters=self.model.base.critic.parameters(), learning_rate=self.params.LEARNING_RATE, params=params ) elif self.params.DEEP_LEARNING_MODEL ==", "raise ValueError() self.buffer = replay_buffer.ExperienceReplayBuffer( experience_source=None, buffer_size=self.params.BATCH_SIZE ) def __call__(self,", "3) # actions_v.shape: (32, 1) # target_action_values_v.shape: (32,) states_v, actions_v,", "# 서로 다른 방향으로 반복적으로 휩쓸려가듯이 학습이 됨 --> Gradients의", "torch import torch.nn.functional as F from codes.d_agents.a0_base_agent import float32_preprocessor from", "= advantage_v * log_pi_action_v #print(actions_v.size(), advantage_v.size(), log_pi_v.size(), log_pi_action_v.size(), reinforced_log_pi_action_v.size()) loss_actor_v", "+ loss_entropy_v loss_actor_and_entropy_v.backward() #nn_utils.clip_grad_norm_(self.model.base.actor.parameters(), self.params.CLIP_GRAD) self.actor_optimizer.step() gradients = self.model.get_gradients_for_current_parameters() return", "codes.e_utils import rl_utils, replay_buffer from codes.d_agents.actions import ProbabilityActionSelector from codes.e_utils.names", "codes.e_utils.names import DeepLearningModelName, AgentMode class AgentDiscreteA2C(OnPolicyAgent): \"\"\" \"\"\" def __init__(", "self.actor_optimizer.step() gradients = self.model.get_gradients_for_current_parameters() return gradients, loss_critic_v.item(), loss_actor_v.item() * -1.0", "= F.log_softmax(logits_v, dim=1) log_pi_action_v = log_pi_v.gather(dim=1, index=actions_v.unsqueeze(-1)).squeeze(-1) reinforced_log_pi_action_v = advantage_v", "- value_v.squeeze(-1).detach() log_pi_v = F.log_softmax(logits_v, dim=1) log_pi_action_v = log_pi_v.gather(dim=1, index=actions_v.unsqueeze(-1)).squeeze(-1)", "learning_rate=self.params.LEARNING_RATE, params=params ) else: raise ValueError() self.buffer = replay_buffer.ExperienceReplayBuffer( experience_source=None,", "train(self, step_idx): # Lucky Episode에서 얻어낸 batch를 통해 학습할 때와,", "train_action_selector, test_and_play_action_selector, params, device ): assert isinstance(train_action_selector, ProbabilityActionSelector) assert isinstance(test_and_play_action_selector,", "= rl_utils.get_rl_model( worker_id=worker_id, input_shape=input_shape, num_outputs=num_outputs, params=params, device=self.device ) if self.params.DEEP_LEARNING_MODEL", ") logits_v, value_v = self.model(states_v) # Critic Optimization self.critic_optimizer.zero_grad() loss_critic_v", "log_pi_v = F.log_softmax(logits_v, dim=1) log_pi_action_v = log_pi_v.gather(dim=1, index=actions_v.unsqueeze(-1)).squeeze(-1) reinforced_log_pi_action_v =", "params, device) self.__name__ = \"AgentDiscreteA2C\" self.worker_id = worker_id self.model =", "from codes.e_utils.names import DeepLearningModelName, AgentMode class AgentDiscreteA2C(OnPolicyAgent): \"\"\" \"\"\" def", "파라미터들이 # 서로 다른 방향으로 반복적으로 휩쓸려가듯이 학습이 됨 -->", "entropy_v # loss_actor_v를 작아지도록 만듦 --> log_pi_v.mean()가 커지도록 만듦 #", "states_v, actions_v, target_action_values_v = self.unpack_batch_for_actor_critic( batch=batch, target_model=self.model, params=self.params ) logits_v,", "= log_pi_v.gather(dim=1, index=actions_v.unsqueeze(-1)).squeeze(-1) reinforced_log_pi_action_v = advantage_v * log_pi_action_v #print(actions_v.size(), advantage_v.size(),", "reinforced_log_pi_action_v.mean() prob_v = F.softmax(logits_v, dim=1) entropy_v = -1.0 * (prob_v", "rl_utils.get_optimizer( parameters=list(self.model.base.common_conv.parameters()) + list(self.model.base.critic_fc.parameters()), learning_rate=self.params.LEARNING_RATE, params=params ) else: raise ValueError()", "= np.array(self.train_action_selector(probs)) else: actions = np.array(self.test_and_play_action_selector(probs)) critics = torch.zeros(size=probs_v.size()) return", "#print(actions_v.size(), advantage_v.size(), log_pi_v.size(), log_pi_action_v.size(), reinforced_log_pi_action_v.size()) loss_actor_v = -1.0 * reinforced_log_pi_action_v.mean()", "F.softmax(logits_v, dim=1) probs = probs_v.data.cpu().numpy() if self.agent_mode == AgentMode.TRAIN: actions", "actions_v, target_action_values_v = self.unpack_batch_for_actor_critic( batch=batch, target_model=self.model, params=self.params ) logits_v, value_v", "= worker_id self.model = rl_utils.get_rl_model( worker_id=worker_id, input_shape=input_shape, num_outputs=num_outputs, params=params, device=self.device", "Gradients의 Variance가 매우 큼 batch = self.buffer.sample(batch_size=None) # states_v.shape: (32,", "# loss_actor_v를 작아지도록 만듦 --> log_pi_v.mean()가 커지도록 만듦 # loss_entropy_v를", "서로 다른 방향으로 반복적으로 휩쓸려가듯이 학습이 됨 --> Gradients의 Variance가", "--> entropy_v가 커지도록 만듦 loss_actor_and_entropy_v = loss_actor_v + loss_entropy_v loss_actor_and_entropy_v.backward()", "target_action_values_v.shape: (32,) states_v, actions_v, target_action_values_v = self.unpack_batch_for_actor_critic( batch=batch, target_model=self.model, params=self.params", "loss_entropy_v를 작아지도록 만듦 --> entropy_v가 커지도록 만듦 loss_actor_and_entropy_v = loss_actor_v", "logits_v = self.model.base.forward_actor(states) probs_v = F.softmax(logits_v, dim=1) probs = probs_v.data.cpu().numpy()", "in [ DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP, DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN ] super(AgentDiscreteA2C, self).__init__(train_action_selector, test_and_play_action_selector, params, device)", "rl_utils.get_optimizer( parameters=self.model.base.critic.parameters(), learning_rate=self.params.LEARNING_RATE, params=params ) elif self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN: self.optimizer", "states = float32_preprocessor(states).to(self.device) logits_v = self.model.base.forward_actor(states) probs_v = F.softmax(logits_v, dim=1)", "actions = np.array(self.train_action_selector(probs)) else: actions = np.array(self.test_and_play_action_selector(probs)) critics = torch.zeros(size=probs_v.size())", "Episode에서 얻어낸 batch를 통해 학습할 때마다 NN의 파라미터들이 # 서로", "# Actor Optimization self.actor_optimizer.zero_grad() # advantage_v.shape: (32,) advantage_v = target_action_values_v", "--> log_pi_v.mean()가 커지도록 만듦 # loss_entropy_v를 작아지도록 만듦 --> entropy_v가", "rl_utils, replay_buffer from codes.d_agents.actions import ProbabilityActionSelector from codes.e_utils.names import DeepLearningModelName,", "log_pi_action_v #print(actions_v.size(), advantage_v.size(), log_pi_v.size(), log_pi_action_v.size(), reinforced_log_pi_action_v.size()) loss_actor_v = -1.0 *", "= F.softmax(logits_v, dim=1) entropy_v = -1.0 * (prob_v * log_pi_v).sum(dim=1).mean()", "probs_v.data.cpu().numpy() if self.agent_mode == AgentMode.TRAIN: actions = np.array(self.train_action_selector(probs)) else: actions", "reinforced_log_pi_action_v = advantage_v * log_pi_action_v #print(actions_v.size(), advantage_v.size(), log_pi_v.size(), log_pi_action_v.size(), reinforced_log_pi_action_v.size())", "* log_pi_action_v #print(actions_v.size(), advantage_v.size(), log_pi_v.size(), log_pi_action_v.size(), reinforced_log_pi_action_v.size()) loss_actor_v = -1.0", "target_action_values_v - value_v.squeeze(-1).detach() log_pi_v = F.log_softmax(logits_v, dim=1) log_pi_action_v = log_pi_v.gather(dim=1,", "= rl_utils.get_optimizer( parameters=list(self.model.base.common_conv.parameters()) + list(self.model.base.critic_fc.parameters()), learning_rate=self.params.LEARNING_RATE, params=params ) else: raise", "learning_rate=self.params.LEARNING_RATE, params=params ) elif self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN: self.optimizer = rl_utils.get_optimizer(", "DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP, DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN ] super(AgentDiscreteA2C, self).__init__(train_action_selector, test_and_play_action_selector, params, device) self.__name__ =", "DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN: self.optimizer = rl_utils.get_optimizer( parameters=list(self.model.base.common_conv.parameters()) + list(self.model.base.critic_fc.parameters()), learning_rate=self.params.LEARNING_RATE, params=params )", "\"\"\" def __init__( self, worker_id, input_shape, num_outputs, train_action_selector, test_and_play_action_selector, params,", "worker_id, input_shape, num_outputs, train_action_selector, test_and_play_action_selector, params, device ): assert isinstance(train_action_selector,", "if self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP: self.actor_optimizer = rl_utils.get_optimizer( parameters=self.model.base.actor.parameters(), learning_rate=self.params.ACTOR_LEARNING_RATE, params=params", "probs = probs_v.data.cpu().numpy() if self.agent_mode == AgentMode.TRAIN: actions = np.array(self.train_action_selector(probs))", "# Lucky Episode에서 얻어낸 batch를 통해 학습할 때와, Unlucky Episode에서", "actions_v.shape: (32, 1) # target_action_values_v.shape: (32,) states_v, actions_v, target_action_values_v =", "experience_source=None, buffer_size=self.params.BATCH_SIZE ) def __call__(self, states, critics=None): if not isinstance(states,", "codes.d_agents.a0_base_agent import float32_preprocessor from codes.d_agents.on_policy.on_policy_agent import OnPolicyAgent from codes.e_utils import", "= F.mse_loss(input=value_v.squeeze(-1), target=target_action_values_v) loss_critic_v.backward(retain_graph=True) #nn_utils.clip_grad_norm_(self.model.base.critic.parameters(), self.params.CLIP_GRAD) self.critic_optimizer.step() # Actor Optimization", "loss_entropy_v = -1.0 * self.params.ENTROPY_LOSS_WEIGHT * entropy_v # loss_actor_v를 작아지도록", "Episode에서 얻어낸 batch를 통해 학습할 때와, Unlucky Episode에서 얻어낸 batch를", "self.buffer.sample(batch_size=None) # states_v.shape: (32, 3) # actions_v.shape: (32, 1) #", "(32,) advantage_v = target_action_values_v - value_v.squeeze(-1).detach() log_pi_v = F.log_softmax(logits_v, dim=1)", "import torch.nn.functional as F from codes.d_agents.a0_base_agent import float32_preprocessor from codes.d_agents.on_policy.on_policy_agent", "= F.softmax(logits_v, dim=1) probs = probs_v.data.cpu().numpy() if self.agent_mode == AgentMode.TRAIN:", "return actions, critics def train(self, step_idx): # Lucky Episode에서 얻어낸", "학습이 됨 --> Gradients의 Variance가 매우 큼 batch = self.buffer.sample(batch_size=None)", "self.optimizer = rl_utils.get_optimizer( parameters=list(self.model.base.common_conv.parameters()) + list(self.model.base.critic_fc.parameters()), learning_rate=self.params.LEARNING_RATE, params=params ) else:", "self.model.base.forward_actor(states) probs_v = F.softmax(logits_v, dim=1) probs = probs_v.data.cpu().numpy() if self.agent_mode", "worker_id=worker_id, input_shape=input_shape, num_outputs=num_outputs, params=params, device=self.device ) if self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP:", "device ): assert isinstance(train_action_selector, ProbabilityActionSelector) assert isinstance(test_and_play_action_selector, ProbabilityActionSelector) assert params.DEEP_LEARNING_MODEL", "ValueError() self.buffer = replay_buffer.ExperienceReplayBuffer( experience_source=None, buffer_size=self.params.BATCH_SIZE ) def __call__(self, states,", "actions, critics def train(self, step_idx): # Lucky Episode에서 얻어낸 batch를", ") else: raise ValueError() self.buffer = replay_buffer.ExperienceReplayBuffer( experience_source=None, buffer_size=self.params.BATCH_SIZE )", "dim=1) probs = probs_v.data.cpu().numpy() if self.agent_mode == AgentMode.TRAIN: actions =", "params=params, device=self.device ) if self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP: self.actor_optimizer = rl_utils.get_optimizer(", "device) self.__name__ = \"AgentDiscreteA2C\" self.worker_id = worker_id self.model = rl_utils.get_rl_model(", "= torch.zeros(size=probs_v.size()) return actions, critics def train(self, step_idx): # Lucky", "rl_utils.get_optimizer( parameters=self.model.base.actor.parameters(), learning_rate=self.params.ACTOR_LEARNING_RATE, params=params ) self.critic_optimizer = rl_utils.get_optimizer( parameters=self.model.base.critic.parameters(), learning_rate=self.params.LEARNING_RATE,", "advantage_v * log_pi_action_v #print(actions_v.size(), advantage_v.size(), log_pi_v.size(), log_pi_action_v.size(), reinforced_log_pi_action_v.size()) loss_actor_v =", "만듦 # loss_entropy_v를 작아지도록 만듦 --> entropy_v가 커지도록 만듦 loss_actor_and_entropy_v", "loss_critic_v.backward(retain_graph=True) #nn_utils.clip_grad_norm_(self.model.base.critic.parameters(), self.params.CLIP_GRAD) self.critic_optimizer.step() # Actor Optimization self.actor_optimizer.zero_grad() # advantage_v.shape:", "critics=None): if not isinstance(states, torch.FloatTensor): states = float32_preprocessor(states).to(self.device) logits_v =", "replay_buffer from codes.d_agents.actions import ProbabilityActionSelector from codes.e_utils.names import DeepLearningModelName, AgentMode", "device=self.device ) if self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP: self.actor_optimizer = rl_utils.get_optimizer( parameters=self.model.base.actor.parameters(),", "reinforced_log_pi_action_v.size()) loss_actor_v = -1.0 * reinforced_log_pi_action_v.mean() prob_v = F.softmax(logits_v, dim=1)", "때와, Unlucky Episode에서 얻어낸 batch를 통해 학습할 때마다 NN의 파라미터들이", "* self.params.ENTROPY_LOSS_WEIGHT * entropy_v # loss_actor_v를 작아지도록 만듦 --> log_pi_v.mean()가", "worker_id self.model = rl_utils.get_rl_model( worker_id=worker_id, input_shape=input_shape, num_outputs=num_outputs, params=params, device=self.device )", "== DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP: self.actor_optimizer = rl_utils.get_optimizer( parameters=self.model.base.actor.parameters(), learning_rate=self.params.ACTOR_LEARNING_RATE, params=params ) self.critic_optimizer", "import torch import torch.nn.functional as F from codes.d_agents.a0_base_agent import float32_preprocessor", "1) # target_action_values_v.shape: (32,) states_v, actions_v, target_action_values_v = self.unpack_batch_for_actor_critic( batch=batch,", "작아지도록 만듦 --> log_pi_v.mean()가 커지도록 만듦 # loss_entropy_v를 작아지도록 만듦", "(32, 3) # actions_v.shape: (32, 1) # target_action_values_v.shape: (32,) states_v,", "됨 --> Gradients의 Variance가 매우 큼 batch = self.buffer.sample(batch_size=None) #", "Unlucky Episode에서 얻어낸 batch를 통해 학습할 때마다 NN의 파라미터들이 #", "OnPolicyAgent from codes.e_utils import rl_utils, replay_buffer from codes.d_agents.actions import ProbabilityActionSelector", "# states_v.shape: (32, 3) # actions_v.shape: (32, 1) # target_action_values_v.shape:", "#nn_utils.clip_grad_norm_(self.model.base.critic.parameters(), self.params.CLIP_GRAD) self.critic_optimizer.step() # Actor Optimization self.actor_optimizer.zero_grad() # advantage_v.shape: (32,)", "def train(self, step_idx): # Lucky Episode에서 얻어낸 batch를 통해 학습할", "만듦 loss_actor_and_entropy_v = loss_actor_v + loss_entropy_v loss_actor_and_entropy_v.backward() #nn_utils.clip_grad_norm_(self.model.base.actor.parameters(), self.params.CLIP_GRAD) self.actor_optimizer.step()", "= self.model(states_v) # Critic Optimization self.critic_optimizer.zero_grad() loss_critic_v = F.mse_loss(input=value_v.squeeze(-1), target=target_action_values_v)", "list(self.model.base.critic_fc.parameters()), learning_rate=self.params.LEARNING_RATE, params=params ) else: raise ValueError() self.buffer = replay_buffer.ExperienceReplayBuffer(", "replay_buffer.ExperienceReplayBuffer( experience_source=None, buffer_size=self.params.BATCH_SIZE ) def __call__(self, states, critics=None): if not", "rl_utils.get_rl_model( worker_id=worker_id, input_shape=input_shape, num_outputs=num_outputs, params=params, device=self.device ) if self.params.DEEP_LEARNING_MODEL ==", "<filename>temp/discrete_a2c_agent.py import numpy as np import torch import torch.nn.functional as", "test_and_play_action_selector, params, device ): assert isinstance(train_action_selector, ProbabilityActionSelector) assert isinstance(test_and_play_action_selector, ProbabilityActionSelector)", "#nn_utils.clip_grad_norm_(self.model.base.actor.parameters(), self.params.CLIP_GRAD) self.actor_optimizer.step() gradients = self.model.get_gradients_for_current_parameters() return gradients, loss_critic_v.item(), loss_actor_v.item()", "float32_preprocessor(states).to(self.device) logits_v = self.model.base.forward_actor(states) probs_v = F.softmax(logits_v, dim=1) probs =", "params, device ): assert isinstance(train_action_selector, ProbabilityActionSelector) assert isinstance(test_and_play_action_selector, ProbabilityActionSelector) assert", "codes.d_agents.actions import ProbabilityActionSelector from codes.e_utils.names import DeepLearningModelName, AgentMode class AgentDiscreteA2C(OnPolicyAgent):", "states, critics=None): if not isinstance(states, torch.FloatTensor): states = float32_preprocessor(states).to(self.device) logits_v", "target=target_action_values_v) loss_critic_v.backward(retain_graph=True) #nn_utils.clip_grad_norm_(self.model.base.critic.parameters(), self.params.CLIP_GRAD) self.critic_optimizer.step() # Actor Optimization self.actor_optimizer.zero_grad() #", "= -1.0 * reinforced_log_pi_action_v.mean() prob_v = F.softmax(logits_v, dim=1) entropy_v =", "buffer_size=self.params.BATCH_SIZE ) def __call__(self, states, critics=None): if not isinstance(states, torch.FloatTensor):", "batch를 통해 학습할 때마다 NN의 파라미터들이 # 서로 다른 방향으로", "isinstance(test_and_play_action_selector, ProbabilityActionSelector) assert params.DEEP_LEARNING_MODEL in [ DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP, DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN ] super(AgentDiscreteA2C,", "= rl_utils.get_optimizer( parameters=self.model.base.actor.parameters(), learning_rate=self.params.ACTOR_LEARNING_RATE, params=params ) self.critic_optimizer = rl_utils.get_optimizer( parameters=self.model.base.critic.parameters(),", "advantage_v.size(), log_pi_v.size(), log_pi_action_v.size(), reinforced_log_pi_action_v.size()) loss_actor_v = -1.0 * reinforced_log_pi_action_v.mean() prob_v", "parameters=list(self.model.base.common_conv.parameters()) + list(self.model.base.critic_fc.parameters()), learning_rate=self.params.LEARNING_RATE, params=params ) else: raise ValueError() self.buffer", "self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN: self.optimizer = rl_utils.get_optimizer( parameters=list(self.model.base.common_conv.parameters()) + list(self.model.base.critic_fc.parameters()), learning_rate=self.params.LEARNING_RATE,", "= replay_buffer.ExperienceReplayBuffer( experience_source=None, buffer_size=self.params.BATCH_SIZE ) def __call__(self, states, critics=None): if", "큼 batch = self.buffer.sample(batch_size=None) # states_v.shape: (32, 3) # actions_v.shape:", "import DeepLearningModelName, AgentMode class AgentDiscreteA2C(OnPolicyAgent): \"\"\" \"\"\" def __init__( self,", "Critic Optimization self.critic_optimizer.zero_grad() loss_critic_v = F.mse_loss(input=value_v.squeeze(-1), target=target_action_values_v) loss_critic_v.backward(retain_graph=True) #nn_utils.clip_grad_norm_(self.model.base.critic.parameters(), self.params.CLIP_GRAD)", "self.actor_optimizer.zero_grad() # advantage_v.shape: (32,) advantage_v = target_action_values_v - value_v.squeeze(-1).detach() log_pi_v", "elif self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN: self.optimizer = rl_utils.get_optimizer( parameters=list(self.model.base.common_conv.parameters()) + list(self.model.base.critic_fc.parameters()),", "만듦 --> log_pi_v.mean()가 커지도록 만듦 # loss_entropy_v를 작아지도록 만듦 -->", "Optimization self.actor_optimizer.zero_grad() # advantage_v.shape: (32,) advantage_v = target_action_values_v - value_v.squeeze(-1).detach()", "batch=batch, target_model=self.model, params=self.params ) logits_v, value_v = self.model(states_v) # Critic", "== DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN: self.optimizer = rl_utils.get_optimizer( parameters=list(self.model.base.common_conv.parameters()) + list(self.model.base.critic_fc.parameters()), learning_rate=self.params.LEARNING_RATE, params=params", "value_v.squeeze(-1).detach() log_pi_v = F.log_softmax(logits_v, dim=1) log_pi_action_v = log_pi_v.gather(dim=1, index=actions_v.unsqueeze(-1)).squeeze(-1) reinforced_log_pi_action_v", "import rl_utils, replay_buffer from codes.d_agents.actions import ProbabilityActionSelector from codes.e_utils.names import", "if not isinstance(states, torch.FloatTensor): states = float32_preprocessor(states).to(self.device) logits_v = self.model.base.forward_actor(states)", "통해 학습할 때마다 NN의 파라미터들이 # 서로 다른 방향으로 반복적으로", "log_pi_v.gather(dim=1, index=actions_v.unsqueeze(-1)).squeeze(-1) reinforced_log_pi_action_v = advantage_v * log_pi_action_v #print(actions_v.size(), advantage_v.size(), log_pi_v.size(),", "DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP: self.actor_optimizer = rl_utils.get_optimizer( parameters=self.model.base.actor.parameters(), learning_rate=self.params.ACTOR_LEARNING_RATE, params=params ) self.critic_optimizer =", "num_outputs=num_outputs, params=params, device=self.device ) if self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP: self.actor_optimizer =", "params.DEEP_LEARNING_MODEL in [ DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP, DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN ] super(AgentDiscreteA2C, self).__init__(train_action_selector, test_and_play_action_selector, params,", "batch를 통해 학습할 때와, Unlucky Episode에서 얻어낸 batch를 통해 학습할", "codes.d_agents.on_policy.on_policy_agent import OnPolicyAgent from codes.e_utils import rl_utils, replay_buffer from codes.d_agents.actions", "self.critic_optimizer.zero_grad() loss_critic_v = F.mse_loss(input=value_v.squeeze(-1), target=target_action_values_v) loss_critic_v.backward(retain_graph=True) #nn_utils.clip_grad_norm_(self.model.base.critic.parameters(), self.params.CLIP_GRAD) self.critic_optimizer.step() #", "통해 학습할 때와, Unlucky Episode에서 얻어낸 batch를 통해 학습할 때마다", "else: actions = np.array(self.test_and_play_action_selector(probs)) critics = torch.zeros(size=probs_v.size()) return actions, critics", "target_model=self.model, params=self.params ) logits_v, value_v = self.model(states_v) # Critic Optimization", "test_and_play_action_selector, params, device) self.__name__ = \"AgentDiscreteA2C\" self.worker_id = worker_id self.model", ") self.critic_optimizer = rl_utils.get_optimizer( parameters=self.model.base.critic.parameters(), learning_rate=self.params.LEARNING_RATE, params=params ) elif self.params.DEEP_LEARNING_MODEL", "Actor Optimization self.actor_optimizer.zero_grad() # advantage_v.shape: (32,) advantage_v = target_action_values_v -", "self.worker_id = worker_id self.model = rl_utils.get_rl_model( worker_id=worker_id, input_shape=input_shape, num_outputs=num_outputs, params=params,", "(prob_v * log_pi_v).sum(dim=1).mean() loss_entropy_v = -1.0 * self.params.ENTROPY_LOSS_WEIGHT * entropy_v", "isinstance(states, torch.FloatTensor): states = float32_preprocessor(states).to(self.device) logits_v = self.model.base.forward_actor(states) probs_v =", "ProbabilityActionSelector) assert params.DEEP_LEARNING_MODEL in [ DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP, DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN ] super(AgentDiscreteA2C, self).__init__(train_action_selector,", "F from codes.d_agents.a0_base_agent import float32_preprocessor from codes.d_agents.on_policy.on_policy_agent import OnPolicyAgent from", "학습할 때와, Unlucky Episode에서 얻어낸 batch를 통해 학습할 때마다 NN의", "= self.unpack_batch_for_actor_critic( batch=batch, target_model=self.model, params=self.params ) logits_v, value_v = self.model(states_v)", "휩쓸려가듯이 학습이 됨 --> Gradients의 Variance가 매우 큼 batch =", "advantage_v = target_action_values_v - value_v.squeeze(-1).detach() log_pi_v = F.log_softmax(logits_v, dim=1) log_pi_action_v", "log_pi_v.mean()가 커지도록 만듦 # loss_entropy_v를 작아지도록 만듦 --> entropy_v가 커지도록", "= float32_preprocessor(states).to(self.device) logits_v = self.model.base.forward_actor(states) probs_v = F.softmax(logits_v, dim=1) probs", "loss_actor_v = -1.0 * reinforced_log_pi_action_v.mean() prob_v = F.softmax(logits_v, dim=1) entropy_v", "assert isinstance(test_and_play_action_selector, ProbabilityActionSelector) assert params.DEEP_LEARNING_MODEL in [ DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP, DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN ]", "actions = np.array(self.test_and_play_action_selector(probs)) critics = torch.zeros(size=probs_v.size()) return actions, critics def", "target_action_values_v = self.unpack_batch_for_actor_critic( batch=batch, target_model=self.model, params=self.params ) logits_v, value_v =", "from codes.d_agents.on_policy.on_policy_agent import OnPolicyAgent from codes.e_utils import rl_utils, replay_buffer from", "from codes.e_utils import rl_utils, replay_buffer from codes.d_agents.actions import ProbabilityActionSelector from", "log_pi_v.size(), log_pi_action_v.size(), reinforced_log_pi_action_v.size()) loss_actor_v = -1.0 * reinforced_log_pi_action_v.mean() prob_v =", "self.actor_optimizer = rl_utils.get_optimizer( parameters=self.model.base.actor.parameters(), learning_rate=self.params.ACTOR_LEARNING_RATE, params=params ) self.critic_optimizer = rl_utils.get_optimizer(", "얻어낸 batch를 통해 학습할 때와, Unlucky Episode에서 얻어낸 batch를 통해", "매우 큼 batch = self.buffer.sample(batch_size=None) # states_v.shape: (32, 3) #", "# target_action_values_v.shape: (32,) states_v, actions_v, target_action_values_v = self.unpack_batch_for_actor_critic( batch=batch, target_model=self.model,", ") if self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP: self.actor_optimizer = rl_utils.get_optimizer( parameters=self.model.base.actor.parameters(), learning_rate=self.params.ACTOR_LEARNING_RATE,", "(32, 1) # target_action_values_v.shape: (32,) states_v, actions_v, target_action_values_v = self.unpack_batch_for_actor_critic(", "-1.0 * reinforced_log_pi_action_v.mean() prob_v = F.softmax(logits_v, dim=1) entropy_v = -1.0", "def __call__(self, states, critics=None): if not isinstance(states, torch.FloatTensor): states =", "* entropy_v # loss_actor_v를 작아지도록 만듦 --> log_pi_v.mean()가 커지도록 만듦", "log_pi_action_v.size(), reinforced_log_pi_action_v.size()) loss_actor_v = -1.0 * reinforced_log_pi_action_v.mean() prob_v = F.softmax(logits_v,", "parameters=self.model.base.critic.parameters(), learning_rate=self.params.LEARNING_RATE, params=params ) elif self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN: self.optimizer =", "import numpy as np import torch import torch.nn.functional as F", "advantage_v.shape: (32,) advantage_v = target_action_values_v - value_v.squeeze(-1).detach() log_pi_v = F.log_softmax(logits_v,", "# actions_v.shape: (32, 1) # target_action_values_v.shape: (32,) states_v, actions_v, target_action_values_v", "self.critic_optimizer.step() # Actor Optimization self.actor_optimizer.zero_grad() # advantage_v.shape: (32,) advantage_v =", "\"\"\" \"\"\" def __init__( self, worker_id, input_shape, num_outputs, train_action_selector, test_and_play_action_selector,", "얻어낸 batch를 통해 학습할 때마다 NN의 파라미터들이 # 서로 다른", "# advantage_v.shape: (32,) advantage_v = target_action_values_v - value_v.squeeze(-1).detach() log_pi_v =", "dim=1) entropy_v = -1.0 * (prob_v * log_pi_v).sum(dim=1).mean() loss_entropy_v =", "float32_preprocessor from codes.d_agents.on_policy.on_policy_agent import OnPolicyAgent from codes.e_utils import rl_utils, replay_buffer", "= rl_utils.get_optimizer( parameters=self.model.base.critic.parameters(), learning_rate=self.params.LEARNING_RATE, params=params ) elif self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN:", "만듦 --> entropy_v가 커지도록 만듦 loss_actor_and_entropy_v = loss_actor_v + loss_entropy_v", "= np.array(self.test_and_play_action_selector(probs)) critics = torch.zeros(size=probs_v.size()) return actions, critics def train(self,", "작아지도록 만듦 --> entropy_v가 커지도록 만듦 loss_actor_and_entropy_v = loss_actor_v +", "-1.0 * self.params.ENTROPY_LOSS_WEIGHT * entropy_v # loss_actor_v를 작아지도록 만듦 -->", "self.unpack_batch_for_actor_critic( batch=batch, target_model=self.model, params=self.params ) logits_v, value_v = self.model(states_v) #", "np import torch import torch.nn.functional as F from codes.d_agents.a0_base_agent import", "batch = self.buffer.sample(batch_size=None) # states_v.shape: (32, 3) # actions_v.shape: (32,", "self, worker_id, input_shape, num_outputs, train_action_selector, test_and_play_action_selector, params, device ): assert", "ProbabilityActionSelector) assert isinstance(test_and_play_action_selector, ProbabilityActionSelector) assert params.DEEP_LEARNING_MODEL in [ DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP, DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN", "states_v.shape: (32, 3) # actions_v.shape: (32, 1) # target_action_values_v.shape: (32,)", "* (prob_v * log_pi_v).sum(dim=1).mean() loss_entropy_v = -1.0 * self.params.ENTROPY_LOSS_WEIGHT *", "assert params.DEEP_LEARNING_MODEL in [ DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP, DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN ] super(AgentDiscreteA2C, self).__init__(train_action_selector, test_and_play_action_selector,", "torch.nn.functional as F from codes.d_agents.a0_base_agent import float32_preprocessor from codes.d_agents.on_policy.on_policy_agent import", "NN의 파라미터들이 # 서로 다른 방향으로 반복적으로 휩쓸려가듯이 학습이 됨", "else: raise ValueError() self.buffer = replay_buffer.ExperienceReplayBuffer( experience_source=None, buffer_size=self.params.BATCH_SIZE ) def", "AgentDiscreteA2C(OnPolicyAgent): \"\"\" \"\"\" def __init__( self, worker_id, input_shape, num_outputs, train_action_selector,", "num_outputs, train_action_selector, test_and_play_action_selector, params, device ): assert isinstance(train_action_selector, ProbabilityActionSelector) assert", "Variance가 매우 큼 batch = self.buffer.sample(batch_size=None) # states_v.shape: (32, 3)", "def __init__( self, worker_id, input_shape, num_outputs, train_action_selector, test_and_play_action_selector, params, device", "not isinstance(states, torch.FloatTensor): states = float32_preprocessor(states).to(self.device) logits_v = self.model.base.forward_actor(states) probs_v", "다른 방향으로 반복적으로 휩쓸려가듯이 학습이 됨 --> Gradients의 Variance가 매우", "= -1.0 * (prob_v * log_pi_v).sum(dim=1).mean() loss_entropy_v = -1.0 *", "* reinforced_log_pi_action_v.mean() prob_v = F.softmax(logits_v, dim=1) entropy_v = -1.0 *", "--> Gradients의 Variance가 매우 큼 batch = self.buffer.sample(batch_size=None) # states_v.shape:", "= probs_v.data.cpu().numpy() if self.agent_mode == AgentMode.TRAIN: actions = np.array(self.train_action_selector(probs)) else:", "반복적으로 휩쓸려가듯이 학습이 됨 --> Gradients의 Variance가 매우 큼 batch", "때마다 NN의 파라미터들이 # 서로 다른 방향으로 반복적으로 휩쓸려가듯이 학습이", "loss_critic_v = F.mse_loss(input=value_v.squeeze(-1), target=target_action_values_v) loss_critic_v.backward(retain_graph=True) #nn_utils.clip_grad_norm_(self.model.base.critic.parameters(), self.params.CLIP_GRAD) self.critic_optimizer.step() # Actor", "DeepLearningModelName, AgentMode class AgentDiscreteA2C(OnPolicyAgent): \"\"\" \"\"\" def __init__( self, worker_id,", "loss_actor_v + loss_entropy_v loss_actor_and_entropy_v.backward() #nn_utils.clip_grad_norm_(self.model.base.actor.parameters(), self.params.CLIP_GRAD) self.actor_optimizer.step() gradients = self.model.get_gradients_for_current_parameters()", "F.softmax(logits_v, dim=1) entropy_v = -1.0 * (prob_v * log_pi_v).sum(dim=1).mean() loss_entropy_v", ") elif self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN: self.optimizer = rl_utils.get_optimizer( parameters=list(self.model.base.common_conv.parameters()) +", "= loss_actor_v + loss_entropy_v loss_actor_and_entropy_v.backward() #nn_utils.clip_grad_norm_(self.model.base.actor.parameters(), self.params.CLIP_GRAD) self.actor_optimizer.step() gradients =", "loss_actor_v를 작아지도록 만듦 --> log_pi_v.mean()가 커지도록 만듦 # loss_entropy_v를 작아지도록", "커지도록 만듦 loss_actor_and_entropy_v = loss_actor_v + loss_entropy_v loss_actor_and_entropy_v.backward() #nn_utils.clip_grad_norm_(self.model.base.actor.parameters(), self.params.CLIP_GRAD)", "] super(AgentDiscreteA2C, self).__init__(train_action_selector, test_and_play_action_selector, params, device) self.__name__ = \"AgentDiscreteA2C\" self.worker_id", "== AgentMode.TRAIN: actions = np.array(self.train_action_selector(probs)) else: actions = np.array(self.test_and_play_action_selector(probs)) critics", "__init__( self, worker_id, input_shape, num_outputs, train_action_selector, test_and_play_action_selector, params, device ):", "critics def train(self, step_idx): # Lucky Episode에서 얻어낸 batch를 통해", "= self.model.base.forward_actor(states) probs_v = F.softmax(logits_v, dim=1) probs = probs_v.data.cpu().numpy() if", "self.model(states_v) # Critic Optimization self.critic_optimizer.zero_grad() loss_critic_v = F.mse_loss(input=value_v.squeeze(-1), target=target_action_values_v) loss_critic_v.backward(retain_graph=True)", "params=self.params ) logits_v, value_v = self.model(states_v) # Critic Optimization self.critic_optimizer.zero_grad()", "np.array(self.train_action_selector(probs)) else: actions = np.array(self.test_and_play_action_selector(probs)) critics = torch.zeros(size=probs_v.size()) return actions,", "F.log_softmax(logits_v, dim=1) log_pi_action_v = log_pi_v.gather(dim=1, index=actions_v.unsqueeze(-1)).squeeze(-1) reinforced_log_pi_action_v = advantage_v *", "= -1.0 * self.params.ENTROPY_LOSS_WEIGHT * entropy_v # loss_actor_v를 작아지도록 만듦", "-1.0 * (prob_v * log_pi_v).sum(dim=1).mean() loss_entropy_v = -1.0 * self.params.ENTROPY_LOSS_WEIGHT", "= target_action_values_v - value_v.squeeze(-1).detach() log_pi_v = F.log_softmax(logits_v, dim=1) log_pi_action_v =", "numpy as np import torch import torch.nn.functional as F from", "import ProbabilityActionSelector from codes.e_utils.names import DeepLearningModelName, AgentMode class AgentDiscreteA2C(OnPolicyAgent): \"\"\"", "value_v = self.model(states_v) # Critic Optimization self.critic_optimizer.zero_grad() loss_critic_v = F.mse_loss(input=value_v.squeeze(-1),", "if self.agent_mode == AgentMode.TRAIN: actions = np.array(self.train_action_selector(probs)) else: actions =", "isinstance(train_action_selector, ProbabilityActionSelector) assert isinstance(test_and_play_action_selector, ProbabilityActionSelector) assert params.DEEP_LEARNING_MODEL in [ DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP,", "__call__(self, states, critics=None): if not isinstance(states, torch.FloatTensor): states = float32_preprocessor(states).to(self.device)", "AgentMode class AgentDiscreteA2C(OnPolicyAgent): \"\"\" \"\"\" def __init__( self, worker_id, input_shape,", "as np import torch import torch.nn.functional as F from codes.d_agents.a0_base_agent", "Lucky Episode에서 얻어낸 batch를 통해 학습할 때와, Unlucky Episode에서 얻어낸", "self.__name__ = \"AgentDiscreteA2C\" self.worker_id = worker_id self.model = rl_utils.get_rl_model( worker_id=worker_id,", "self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP: self.actor_optimizer = rl_utils.get_optimizer( parameters=self.model.base.actor.parameters(), learning_rate=self.params.ACTOR_LEARNING_RATE, params=params )", "as F from codes.d_agents.a0_base_agent import float32_preprocessor from codes.d_agents.on_policy.on_policy_agent import OnPolicyAgent", ") def __call__(self, states, critics=None): if not isinstance(states, torch.FloatTensor): states", "params=params ) else: raise ValueError() self.buffer = replay_buffer.ExperienceReplayBuffer( experience_source=None, buffer_size=self.params.BATCH_SIZE", "loss_actor_and_entropy_v = loss_actor_v + loss_entropy_v loss_actor_and_entropy_v.backward() #nn_utils.clip_grad_norm_(self.model.base.actor.parameters(), self.params.CLIP_GRAD) self.actor_optimizer.step() gradients", "self).__init__(train_action_selector, test_and_play_action_selector, params, device) self.__name__ = \"AgentDiscreteA2C\" self.worker_id = worker_id", "= self.buffer.sample(batch_size=None) # states_v.shape: (32, 3) # actions_v.shape: (32, 1)", "index=actions_v.unsqueeze(-1)).squeeze(-1) reinforced_log_pi_action_v = advantage_v * log_pi_action_v #print(actions_v.size(), advantage_v.size(), log_pi_v.size(), log_pi_action_v.size(),", "np.array(self.test_and_play_action_selector(probs)) critics = torch.zeros(size=probs_v.size()) return actions, critics def train(self, step_idx):", "critics = torch.zeros(size=probs_v.size()) return actions, critics def train(self, step_idx): #", "import float32_preprocessor from codes.d_agents.on_policy.on_policy_agent import OnPolicyAgent from codes.e_utils import rl_utils,", "+ list(self.model.base.critic_fc.parameters()), learning_rate=self.params.LEARNING_RATE, params=params ) else: raise ValueError() self.buffer =", "# Critic Optimization self.critic_optimizer.zero_grad() loss_critic_v = F.mse_loss(input=value_v.squeeze(-1), target=target_action_values_v) loss_critic_v.backward(retain_graph=True) #nn_utils.clip_grad_norm_(self.model.base.critic.parameters(),", "Optimization self.critic_optimizer.zero_grad() loss_critic_v = F.mse_loss(input=value_v.squeeze(-1), target=target_action_values_v) loss_critic_v.backward(retain_graph=True) #nn_utils.clip_grad_norm_(self.model.base.critic.parameters(), self.params.CLIP_GRAD) self.critic_optimizer.step()", "torch.zeros(size=probs_v.size()) return actions, critics def train(self, step_idx): # Lucky Episode에서", "loss_actor_and_entropy_v.backward() #nn_utils.clip_grad_norm_(self.model.base.actor.parameters(), self.params.CLIP_GRAD) self.actor_optimizer.step() gradients = self.model.get_gradients_for_current_parameters() return gradients, loss_critic_v.item(),", "self.agent_mode == AgentMode.TRAIN: actions = np.array(self.train_action_selector(probs)) else: actions = np.array(self.test_and_play_action_selector(probs))", "logits_v, value_v = self.model(states_v) # Critic Optimization self.critic_optimizer.zero_grad() loss_critic_v =", "log_pi_action_v = log_pi_v.gather(dim=1, index=actions_v.unsqueeze(-1)).squeeze(-1) reinforced_log_pi_action_v = advantage_v * log_pi_action_v #print(actions_v.size(),", "방향으로 반복적으로 휩쓸려가듯이 학습이 됨 --> Gradients의 Variance가 매우 큼", "): assert isinstance(train_action_selector, ProbabilityActionSelector) assert isinstance(test_and_play_action_selector, ProbabilityActionSelector) assert params.DEEP_LEARNING_MODEL in", "class AgentDiscreteA2C(OnPolicyAgent): \"\"\" \"\"\" def __init__( self, worker_id, input_shape, num_outputs,", "params=params ) elif self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN: self.optimizer = rl_utils.get_optimizer( parameters=list(self.model.base.common_conv.parameters())", "prob_v = F.softmax(logits_v, dim=1) entropy_v = -1.0 * (prob_v *", "super(AgentDiscreteA2C, self).__init__(train_action_selector, test_and_play_action_selector, params, device) self.__name__ = \"AgentDiscreteA2C\" self.worker_id =", "(32,) states_v, actions_v, target_action_values_v = self.unpack_batch_for_actor_critic( batch=batch, target_model=self.model, params=self.params )", "params=params ) self.critic_optimizer = rl_utils.get_optimizer( parameters=self.model.base.critic.parameters(), learning_rate=self.params.LEARNING_RATE, params=params ) elif", "self.params.ENTROPY_LOSS_WEIGHT * entropy_v # loss_actor_v를 작아지도록 만듦 --> log_pi_v.mean()가 커지도록", "self.params.CLIP_GRAD) self.critic_optimizer.step() # Actor Optimization self.actor_optimizer.zero_grad() # advantage_v.shape: (32,) advantage_v", "from codes.d_agents.a0_base_agent import float32_preprocessor from codes.d_agents.on_policy.on_policy_agent import OnPolicyAgent from codes.e_utils", "entropy_v가 커지도록 만듦 loss_actor_and_entropy_v = loss_actor_v + loss_entropy_v loss_actor_and_entropy_v.backward() #nn_utils.clip_grad_norm_(self.model.base.actor.parameters(),", "input_shape=input_shape, num_outputs=num_outputs, params=params, device=self.device ) if self.params.DEEP_LEARNING_MODEL == DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP: self.actor_optimizer", "log_pi_v).sum(dim=1).mean() loss_entropy_v = -1.0 * self.params.ENTROPY_LOSS_WEIGHT * entropy_v # loss_actor_v를", "dim=1) log_pi_action_v = log_pi_v.gather(dim=1, index=actions_v.unsqueeze(-1)).squeeze(-1) reinforced_log_pi_action_v = advantage_v * log_pi_action_v", "AgentMode.TRAIN: actions = np.array(self.train_action_selector(probs)) else: actions = np.array(self.test_and_play_action_selector(probs)) critics =", "F.mse_loss(input=value_v.squeeze(-1), target=target_action_values_v) loss_critic_v.backward(retain_graph=True) #nn_utils.clip_grad_norm_(self.model.base.critic.parameters(), self.params.CLIP_GRAD) self.critic_optimizer.step() # Actor Optimization self.actor_optimizer.zero_grad()", "학습할 때마다 NN의 파라미터들이 # 서로 다른 방향으로 반복적으로 휩쓸려가듯이", "커지도록 만듦 # loss_entropy_v를 작아지도록 만듦 --> entropy_v가 커지도록 만듦", "self.buffer = replay_buffer.ExperienceReplayBuffer( experience_source=None, buffer_size=self.params.BATCH_SIZE ) def __call__(self, states, critics=None):", "probs_v = F.softmax(logits_v, dim=1) probs = probs_v.data.cpu().numpy() if self.agent_mode ==", "DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN ] super(AgentDiscreteA2C, self).__init__(train_action_selector, test_and_play_action_selector, params, device) self.__name__ = \"AgentDiscreteA2C\"", "self.model = rl_utils.get_rl_model( worker_id=worker_id, input_shape=input_shape, num_outputs=num_outputs, params=params, device=self.device ) if", "import OnPolicyAgent from codes.e_utils import rl_utils, replay_buffer from codes.d_agents.actions import", "[ DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_MLP, DeepLearningModelName.DISCRETE_STOCHASTIC_ACTOR_CRITIC_CNN ] super(AgentDiscreteA2C, self).__init__(train_action_selector, test_and_play_action_selector, params, device) self.__name__", "from codes.d_agents.actions import ProbabilityActionSelector from codes.e_utils.names import DeepLearningModelName, AgentMode class", "torch.FloatTensor): states = float32_preprocessor(states).to(self.device) logits_v = self.model.base.forward_actor(states) probs_v = F.softmax(logits_v,", "entropy_v = -1.0 * (prob_v * log_pi_v).sum(dim=1).mean() loss_entropy_v = -1.0", "ProbabilityActionSelector from codes.e_utils.names import DeepLearningModelName, AgentMode class AgentDiscreteA2C(OnPolicyAgent): \"\"\" \"\"\"", "\"AgentDiscreteA2C\" self.worker_id = worker_id self.model = rl_utils.get_rl_model( worker_id=worker_id, input_shape=input_shape, num_outputs=num_outputs,", "# loss_entropy_v를 작아지도록 만듦 --> entropy_v가 커지도록 만듦 loss_actor_and_entropy_v =", "assert isinstance(train_action_selector, ProbabilityActionSelector) assert isinstance(test_and_play_action_selector, ProbabilityActionSelector) assert params.DEEP_LEARNING_MODEL in [", "self.params.CLIP_GRAD) self.actor_optimizer.step() gradients = self.model.get_gradients_for_current_parameters() return gradients, loss_critic_v.item(), loss_actor_v.item() *", "step_idx): # Lucky Episode에서 얻어낸 batch를 통해 학습할 때와, Unlucky", "parameters=self.model.base.actor.parameters(), learning_rate=self.params.ACTOR_LEARNING_RATE, params=params ) self.critic_optimizer = rl_utils.get_optimizer( parameters=self.model.base.critic.parameters(), learning_rate=self.params.LEARNING_RATE, params=params", "learning_rate=self.params.ACTOR_LEARNING_RATE, params=params ) self.critic_optimizer = rl_utils.get_optimizer( parameters=self.model.base.critic.parameters(), learning_rate=self.params.LEARNING_RATE, params=params )" ]
[ "functionality \"\"\" def __init__(self, bot: Bot): self.bot = bot def", "import Bot, Cog class Webhook(Cog): \"\"\" Webhook functionality \"\"\" def", "Bot, Cog class Webhook(Cog): \"\"\" Webhook functionality \"\"\" def __init__(self,", "Cog class Webhook(Cog): \"\"\" Webhook functionality \"\"\" def __init__(self, bot:", "\"\"\" def __init__(self, bot: Bot): self.bot = bot def setup(bot):", "\"\"\" Webhook functionality \"\"\" def __init__(self, bot: Bot): self.bot =", "Webhook functionality \"\"\" def __init__(self, bot: Bot): self.bot = bot", "class Webhook(Cog): \"\"\" Webhook functionality \"\"\" def __init__(self, bot: Bot):", "<filename>edmundbotadder/cogs/webhook.py from discord.ext.commands import Bot, Cog class Webhook(Cog): \"\"\" Webhook", "from discord.ext.commands import Bot, Cog class Webhook(Cog): \"\"\" Webhook functionality", "def __init__(self, bot: Bot): self.bot = bot def setup(bot): bot.add_cog(Webhook(bot))", "discord.ext.commands import Bot, Cog class Webhook(Cog): \"\"\" Webhook functionality \"\"\"", "Webhook(Cog): \"\"\" Webhook functionality \"\"\" def __init__(self, bot: Bot): self.bot" ]
[ "self.cleaned_data['name'] email = self.cleaned_data['email'] message = self.cleaned_data['message'] message = 'Nome:", "class ContactForm(forms.Form): name = forms.CharField(label='Nome', required=True) email = forms.EmailField(label='E-mail') message", "<reponame>allexvissoci/djangoecommerce from django import forms from django.core.mail import send_mail from", "message = forms.CharField(label='Mensagem', widget=forms.Textarea(), required=True) def send_mail(self): name = self.cleaned_data['name']", "import send_mail from django.conf import settings class ContactForm(forms.Form): name =", "self.cleaned_data['message'] message = 'Nome: {0}\\nE-mail:{1}\\n{2}'.format(name, email, message) send_mail( 'Contato Django", "import settings class ContactForm(forms.Form): name = forms.CharField(label='Nome', required=True) email =", "settings class ContactForm(forms.Form): name = forms.CharField(label='Nome', required=True) email = forms.EmailField(label='E-mail')", "def send_mail(self): name = self.cleaned_data['name'] email = self.cleaned_data['email'] message =", "email = forms.EmailField(label='E-mail') message = forms.CharField(label='Mensagem', widget=forms.Textarea(), required=True) def send_mail(self):", "= self.cleaned_data['email'] message = self.cleaned_data['message'] message = 'Nome: {0}\\nE-mail:{1}\\n{2}'.format(name, email,", "from django import forms from django.core.mail import send_mail from django.conf", "= 'Nome: {0}\\nE-mail:{1}\\n{2}'.format(name, email, message) send_mail( 'Contato Django E-commerce', message,", "message = 'Nome: {0}\\nE-mail:{1}\\n{2}'.format(name, email, message) send_mail( 'Contato Django E-commerce',", "forms.EmailField(label='E-mail') message = forms.CharField(label='Mensagem', widget=forms.Textarea(), required=True) def send_mail(self): name =", "= self.cleaned_data['name'] email = self.cleaned_data['email'] message = self.cleaned_data['message'] message =", "= forms.CharField(label='Nome', required=True) email = forms.EmailField(label='E-mail') message = forms.CharField(label='Mensagem', widget=forms.Textarea(),", "forms.CharField(label='Nome', required=True) email = forms.EmailField(label='E-mail') message = forms.CharField(label='Mensagem', widget=forms.Textarea(), required=True)", "{0}\\nE-mail:{1}\\n{2}'.format(name, email, message) send_mail( 'Contato Django E-commerce', message, settings.DEFAULT_FROM_EMAIL, [settings.DEFAULT_FROM_EMAIL]", "django.conf import settings class ContactForm(forms.Form): name = forms.CharField(label='Nome', required=True) email", "forms from django.core.mail import send_mail from django.conf import settings class", "name = self.cleaned_data['name'] email = self.cleaned_data['email'] message = self.cleaned_data['message'] message", "required=True) email = forms.EmailField(label='E-mail') message = forms.CharField(label='Mensagem', widget=forms.Textarea(), required=True) def", "email = self.cleaned_data['email'] message = self.cleaned_data['message'] message = 'Nome: {0}\\nE-mail:{1}\\n{2}'.format(name,", "send_mail(self): name = self.cleaned_data['name'] email = self.cleaned_data['email'] message = self.cleaned_data['message']", "send_mail from django.conf import settings class ContactForm(forms.Form): name = forms.CharField(label='Nome',", "from django.conf import settings class ContactForm(forms.Form): name = forms.CharField(label='Nome', required=True)", "message = self.cleaned_data['message'] message = 'Nome: {0}\\nE-mail:{1}\\n{2}'.format(name, email, message) send_mail(", "name = forms.CharField(label='Nome', required=True) email = forms.EmailField(label='E-mail') message = forms.CharField(label='Mensagem',", "= forms.CharField(label='Mensagem', widget=forms.Textarea(), required=True) def send_mail(self): name = self.cleaned_data['name'] email", "ContactForm(forms.Form): name = forms.CharField(label='Nome', required=True) email = forms.EmailField(label='E-mail') message =", "= self.cleaned_data['message'] message = 'Nome: {0}\\nE-mail:{1}\\n{2}'.format(name, email, message) send_mail( 'Contato", "'Nome: {0}\\nE-mail:{1}\\n{2}'.format(name, email, message) send_mail( 'Contato Django E-commerce', message, settings.DEFAULT_FROM_EMAIL,", "= forms.EmailField(label='E-mail') message = forms.CharField(label='Mensagem', widget=forms.Textarea(), required=True) def send_mail(self): name", "widget=forms.Textarea(), required=True) def send_mail(self): name = self.cleaned_data['name'] email = self.cleaned_data['email']", "from django.core.mail import send_mail from django.conf import settings class ContactForm(forms.Form):", "required=True) def send_mail(self): name = self.cleaned_data['name'] email = self.cleaned_data['email'] message", "django.core.mail import send_mail from django.conf import settings class ContactForm(forms.Form): name", "forms.CharField(label='Mensagem', widget=forms.Textarea(), required=True) def send_mail(self): name = self.cleaned_data['name'] email =", "email, message) send_mail( 'Contato Django E-commerce', message, settings.DEFAULT_FROM_EMAIL, [settings.DEFAULT_FROM_EMAIL] )", "django import forms from django.core.mail import send_mail from django.conf import", "import forms from django.core.mail import send_mail from django.conf import settings", "self.cleaned_data['email'] message = self.cleaned_data['message'] message = 'Nome: {0}\\nE-mail:{1}\\n{2}'.format(name, email, message)" ]
[ "self.job = self.fchat_prv.generate_key_for_friend() self.owner_info.set_text(self.pub_info_key) self.on_generate_keys_start() def on_generate_keys_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False)", "False, 7) h_bt.pack_start(self.cancel_bt, True, False, 7) h_bt.pack_start(self.close_bt, True, False, 7)", "self.main_window = main_window self.friend_list = friend_list self.fchat_prv.add_friend_gui = self self.generate_keys_bt", "self.save_bt = Gtk.Button('Save') self.save_bt.connect('clicked', self.on_save) self.cancel_bt = Gtk.Button('Cancel') self.cancel_bt.connect('clicked', self.on_cancel)", "on_generate_keys_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_generate_keys_faild(self,", "True, False, 7) self.pack_start(self.friend_info, True, False, 7) self.pack_start(self.spinner, True, False,", "self.on_copy_clipboard) h_owner = Gtk.Box(spacing=5) h_owner.pack_start(self.owner_info, True, True, 1) h_owner.pack_start(self.copy_clipboard_bt, False,", "False, 7) h_bt.pack_start(self.save_bt, True, False, 7) h_bt.pack_start(self.cancel_bt, True, False, 7)", "self.generate_keys_bt = Gtk.Button('Generate Key') self.generate_keys_bt.connect('clicked', self.on_generate_keys) self.save_bt = Gtk.Button('Save') self.save_bt.connect('clicked',", "= Gtk.Button('Save') self.save_bt.connect('clicked', self.on_save) self.cancel_bt = Gtk.Button('Cancel') self.cancel_bt.connect('clicked', self.on_cancel) self.close_bt", "self.msg_info(text) def on_save_start_faild(self): dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, \"ERROR\")", "self.owner_info.get_text() == '': self.msg_info('You should generate a key that contains", "= self self.generate_keys_bt = Gtk.Button('Generate Key') self.generate_keys_bt.connect('clicked', self.on_generate_keys) self.save_bt =", "def on_cancel(self, button): if self.job: self.job.remove_from_queue_when_finish() def on_close(self, button): self.main_window.application.back_main_window_or_friend_list()", "h_bt = Gtk.Box() h_bt.pack_start(self.generate_keys_bt, True, False, 7) h_bt.pack_start(self.save_bt, True, False,", "button): self.pub, self.prv, self.pub_info_key, self.job = self.fchat_prv.generate_key_for_friend() self.owner_info.set_text(self.pub_info_key) self.on_generate_keys_start() def", "self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_generate_keys_faild(self, text): self.spinner.hide() self.spinner.stop()", "Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) self.copy_clipboard_bt.connect('clicked', self.on_copy_clipboard) h_owner = Gtk.Box(spacing=5) h_owner.pack_start(self.owner_info, True, True, 1)", "7) self.pack_start(self.friend_info, True, False, 7) self.pack_start(self.spinner, True, False, 7) h_bt", "self.copy_clipboard_bt.connect('clicked', self.on_copy_clipboard) h_owner = Gtk.Box(spacing=5) h_owner.pack_start(self.owner_info, True, True, 1) h_owner.pack_start(self.copy_clipboard_bt,", "self.owner_info.set_sensitive(False) self.copy_clipboard_bt = Gtk.Button(label='Copy to clipboard') self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) self.copy_clipboard_bt.connect('clicked',", "self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_save_start_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True)", "self.job: self.job.remove_from_queue_when_finish() def on_close(self, button): self.main_window.application.back_main_window_or_friend_list() def on_save(self, button): if", "h_bt.pack_start(self.close_bt, True, False, 7) self.pack_start(h_bt, True, False, 7) self.job =", "self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_generate_keys_faild(self, text): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True)", "self.pack_start(h_bt, True, False, 7) self.job = None def on_generate_keys(self, button):", "is required') return self.fchat_prv.add_friend(self.pub, self.prv, self.friend_info.get_text()) self.on_save_start() def on_save_start(self): self.spinner.show()", "self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_generate_keys_faild(self, text):", "self.spinner = Gtk.Spinner() self.pack_start(h_owner, True, False, 7) self.pack_start(self.friend_info, True, False,", "self.clipboard.set_text(self.owner_info.get_text(), -1) def msg_info(self, text): dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.INFO,", "contains your info') return if self.friend_info.get_text() == '': self.msg_info('Friend info", "True, 1) h_owner.pack_start(self.copy_clipboard_bt, False, False, 1) self.friend_info = Gtk.Entry() self.friend_info.set_placeholder_text('Key", "a key that contains your info') return if self.friend_info.get_text() ==", "if self.job: self.job.remove_from_queue_when_finish() def on_close(self, button): self.main_window.application.back_main_window_or_friend_list() def on_save(self, button):", "self.friend_info.get_text()) self.on_save_start() def on_save_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False)", "self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) self.friend_list.sync_friends_list() def on_save_start_duplicate(self, text): self.msg_info(text) def", "self.copy_clipboard_bt.set_sensitive(True) def on_copy_clipboard(self, button): self.clipboard.set_text(self.owner_info.get_text(), -1) def msg_info(self, text): dialog", "h_owner = Gtk.Box(spacing=5) h_owner.pack_start(self.owner_info, True, True, 1) h_owner.pack_start(self.copy_clipboard_bt, False, False,", "False, 7) self.pack_start(self.spinner, True, False, 7) h_bt = Gtk.Box() h_bt.pack_start(self.generate_keys_bt,", "self.generate_keys_bt.connect('clicked', self.on_generate_keys) self.save_bt = Gtk.Button('Save') self.save_bt.connect('clicked', self.on_save) self.cancel_bt = Gtk.Button('Cancel')", "7) self.job = None def on_generate_keys(self, button): self.pub, self.prv, self.pub_info_key,", "self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_cancel(self, button): if self.job: self.job.remove_from_queue_when_finish()", "friend_list self.fchat_prv.add_friend_gui = self self.generate_keys_bt = Gtk.Button('Generate Key') self.generate_keys_bt.connect('clicked', self.on_generate_keys)", "button): self.clipboard.set_text(self.owner_info.get_text(), -1) def msg_info(self, text): dialog = Gtk.MessageDialog(self.main_window, 0,", "self.on_close) self.owner_info = Gtk.Entry() self.owner_info.set_sensitive(False) self.copy_clipboard_bt = Gtk.Button(label='Copy to clipboard')", "False, False, 1) self.friend_info = Gtk.Entry() self.friend_info.set_placeholder_text('Key of your friend')", "True, True, 1) h_owner.pack_start(self.copy_clipboard_bt, False, False, 1) self.friend_info = Gtk.Entry()", "True, False, 7) h_bt.pack_start(self.save_bt, True, False, 7) h_bt.pack_start(self.cancel_bt, True, False,", "True, False, 7) h_bt.pack_start(self.close_bt, True, False, 7) self.pack_start(h_bt, True, False,", "False, 7) self.job = None def on_generate_keys(self, button): self.pub, self.prv,", "button): if self.owner_info.get_text() == '': self.msg_info('You should generate a key", "7) self.pack_start(self.spinner, True, False, 7) h_bt = Gtk.Box() h_bt.pack_start(self.generate_keys_bt, True,", "self.fchat_prv.add_friend(self.pub, self.prv, self.friend_info.get_text()) self.on_save_start() def on_save_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False)", "text): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_cancel(self,", "self.on_save_start() def on_save_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False)", "self.copy_clipboard_bt.set_sensitive(True) self.friend_list.sync_friends_list() def on_save_start_duplicate(self, text): self.msg_info(text) def on_save_start_faild(self): dialog =", "self.cancel_bt.connect('clicked', self.on_cancel) self.close_bt = Gtk.Button('Close') self.close_bt.connect('clicked', self.on_close) self.owner_info = Gtk.Entry()", "on_close(self, button): self.main_window.application.back_main_window_or_friend_list() def on_save(self, button): if self.owner_info.get_text() == '':", "info') return if self.friend_info.get_text() == '': self.msg_info('Friend info is required')", "dialog.format_secondary_text(\"Error adding friend please try later\") dialog.run() dialog.destroy() self.spinner.hide() self.spinner.stop()", "gi.require_version('Gtk', '3.0') from gi.repository import Gio, Gtk, Gdk class AddFriendWidget(Gtk.Box):", "self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_cancel(self, button): if", "def on_save(self, button): if self.owner_info.get_text() == '': self.msg_info('You should generate", "if self.friend_info.get_text() == '': self.msg_info('Friend info is required') return self.fchat_prv.add_friend(self.pub,", "from gi.repository import Gio, Gtk, Gdk class AddFriendWidget(Gtk.Box): def __init__(self,", "= Gtk.Button('Close') self.close_bt.connect('clicked', self.on_close) self.owner_info = Gtk.Entry() self.owner_info.set_sensitive(False) self.copy_clipboard_bt =", "self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_generate_keys_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True)", "self.prv, self.friend_info.get_text()) self.on_save_start() def on_save_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False)", "your info') return if self.friend_info.get_text() == '': self.msg_info('Friend info is", "self.pack_start(self.friend_info, True, False, 7) self.pack_start(self.spinner, True, False, 7) h_bt =", "self.job.remove_from_queue_when_finish() def on_close(self, button): self.main_window.application.back_main_window_or_friend_list() def on_save(self, button): if self.owner_info.get_text()", "button): if self.job: self.job.remove_from_queue_when_finish() def on_close(self, button): self.main_window.application.back_main_window_or_friend_list() def on_save(self,", "self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_copy_clipboard(self, button): self.clipboard.set_text(self.owner_info.get_text(),", "orientation = Gtk.Orientation.VERTICAL) self.fchat_prv = fchat_prv self.main_window = main_window self.friend_list", "self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_generate_keys_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True)", "__init__(self, main_window, fchat_prv, friend_list): Gtk.Box.__init__(self, spacing=7, orientation = Gtk.Orientation.VERTICAL) self.fchat_prv", "= Gtk.Button(label='Copy to clipboard') self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) self.copy_clipboard_bt.connect('clicked', self.on_copy_clipboard) h_owner", "should generate a key that contains your info') return if", "False, 7) h_bt = Gtk.Box() h_bt.pack_start(self.generate_keys_bt, True, False, 7) h_bt.pack_start(self.save_bt,", "def on_generate_keys_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def", "= None def on_generate_keys(self, button): self.pub, self.prv, self.pub_info_key, self.job =", "def on_save_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def", "friend_list): Gtk.Box.__init__(self, spacing=7, orientation = Gtk.Orientation.VERTICAL) self.fchat_prv = fchat_prv self.main_window", "main_window self.friend_list = friend_list self.fchat_prv.add_friend_gui = self self.generate_keys_bt = Gtk.Button('Generate", "def on_save_start_faild(self): dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, \"ERROR\") dialog.format_secondary_text(\"Error", "False, 7) self.pack_start(h_bt, True, False, 7) self.job = None def", "on_save_start_faild(self): dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, \"ERROR\") dialog.format_secondary_text(\"Error adding", "7) h_bt = Gtk.Box() h_bt.pack_start(self.generate_keys_bt, True, False, 7) h_bt.pack_start(self.save_bt, True,", "if self.owner_info.get_text() == '': self.msg_info('You should generate a key that", "self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_generate_keys_faild(self, text): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True)", "self.pack_start(h_owner, True, False, 7) self.pack_start(self.friend_info, True, False, 7) self.pack_start(self.spinner, True,", "self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) self.friend_list.sync_friends_list() def on_save_start_duplicate(self,", "self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_cancel(self, button): if self.job: self.job.remove_from_queue_when_finish() def on_close(self,", "= main_window self.friend_list = friend_list self.fchat_prv.add_friend_gui = self self.generate_keys_bt =", "self.fchat_prv.add_friend_gui = self self.generate_keys_bt = Gtk.Button('Generate Key') self.generate_keys_bt.connect('clicked', self.on_generate_keys) self.save_bt", "self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) self.copy_clipboard_bt.connect('clicked', self.on_copy_clipboard) h_owner = Gtk.Box(spacing=5) h_owner.pack_start(self.owner_info, True,", "self.friend_list = friend_list self.fchat_prv.add_friend_gui = self self.generate_keys_bt = Gtk.Button('Generate Key')", "= Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) self.copy_clipboard_bt.connect('clicked', self.on_copy_clipboard) h_owner = Gtk.Box(spacing=5) h_owner.pack_start(self.owner_info, True, True,", "self.close_bt = Gtk.Button('Close') self.close_bt.connect('clicked', self.on_close) self.owner_info = Gtk.Entry() self.owner_info.set_sensitive(False) self.copy_clipboard_bt", "True, False, 7) h_bt = Gtk.Box() h_bt.pack_start(self.generate_keys_bt, True, False, 7)", "on_generate_keys_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_generate_keys_ok(self):", "adding friend please try later\") dialog.run() dialog.destroy() self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True)", "text): dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, \"Info\") dialog.format_secondary_text(text) dialog.run()", "h_bt.pack_start(self.generate_keys_bt, True, False, 7) h_bt.pack_start(self.save_bt, True, False, 7) h_bt.pack_start(self.cancel_bt, True,", "gi.repository import Gio, Gtk, Gdk class AddFriendWidget(Gtk.Box): def __init__(self, main_window,", "def on_close(self, button): self.main_window.application.back_main_window_or_friend_list() def on_save(self, button): if self.owner_info.get_text() ==", "h_bt.pack_start(self.save_bt, True, False, 7) h_bt.pack_start(self.cancel_bt, True, False, 7) h_bt.pack_start(self.close_bt, True,", "dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, \"Info\") dialog.format_secondary_text(text) dialog.run() dialog.destroy()", "True, False, 7) self.job = None def on_generate_keys(self, button): self.pub,", "self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_generate_keys_ok(self): self.spinner.hide() self.spinner.stop()", "True, False, 7) h_bt.pack_start(self.cancel_bt, True, False, 7) h_bt.pack_start(self.close_bt, True, False,", "Gtk.ButtonsType.OK, \"ERROR\") dialog.format_secondary_text(\"Error adding friend please try later\") dialog.run() dialog.destroy()", "import gi gi.require_version('Gtk', '3.0') from gi.repository import Gio, Gtk, Gdk", "self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_save_start_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True)", "self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) self.friend_list.sync_friends_list() def on_save_start_duplicate(self, text): self.msg_info(text)", "= Gtk.Button('Cancel') self.cancel_bt.connect('clicked', self.on_cancel) self.close_bt = Gtk.Button('Close') self.close_bt.connect('clicked', self.on_close) self.owner_info", "self.copy_clipboard_bt.set_sensitive(True) def on_generate_keys_faild(self, text): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True)", "later\") dialog.run() dialog.destroy() self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True)", "self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_copy_clipboard(self, button): self.clipboard.set_text(self.owner_info.get_text(), -1)", "7) h_bt.pack_start(self.close_bt, True, False, 7) self.pack_start(h_bt, True, False, 7) self.job", "= self.fchat_prv.generate_key_for_friend() self.owner_info.set_text(self.pub_info_key) self.on_generate_keys_start() def on_generate_keys_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False)", "self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_cancel(self, button):", "on_copy_clipboard(self, button): self.clipboard.set_text(self.owner_info.get_text(), -1) def msg_info(self, text): dialog = Gtk.MessageDialog(self.main_window,", "Gtk.Button('Generate Key') self.generate_keys_bt.connect('clicked', self.on_generate_keys) self.save_bt = Gtk.Button('Save') self.save_bt.connect('clicked', self.on_save) self.cancel_bt", "7) h_bt.pack_start(self.cancel_bt, True, False, 7) h_bt.pack_start(self.close_bt, True, False, 7) self.pack_start(h_bt,", "to clipboard') self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) self.copy_clipboard_bt.connect('clicked', self.on_copy_clipboard) h_owner = Gtk.Box(spacing=5)", "= fchat_prv self.main_window = main_window self.friend_list = friend_list self.fchat_prv.add_friend_gui =", "def on_generate_keys_faild(self, text): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True)", "class AddFriendWidget(Gtk.Box): def __init__(self, main_window, fchat_prv, friend_list): Gtk.Box.__init__(self, spacing=7, orientation", "Gio, Gtk, Gdk class AddFriendWidget(Gtk.Box): def __init__(self, main_window, fchat_prv, friend_list):", "Gtk.Button('Save') self.save_bt.connect('clicked', self.on_save) self.cancel_bt = Gtk.Button('Cancel') self.cancel_bt.connect('clicked', self.on_cancel) self.close_bt =", "on_save_start_duplicate(self, text): self.msg_info(text) def on_save_start_faild(self): dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.ERROR,", "gi gi.require_version('Gtk', '3.0') from gi.repository import Gio, Gtk, Gdk class", "def on_copy_clipboard(self, button): self.clipboard.set_text(self.owner_info.get_text(), -1) def msg_info(self, text): dialog =", "h_owner.pack_start(self.owner_info, True, True, 1) h_owner.pack_start(self.copy_clipboard_bt, False, False, 1) self.friend_info =", "self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_save_start_ok(self): self.spinner.hide()", "False, 7) self.pack_start(self.friend_info, True, False, 7) self.pack_start(self.spinner, True, False, 7)", "'3.0') from gi.repository import Gio, Gtk, Gdk class AddFriendWidget(Gtk.Box): def", "fchat_prv self.main_window = main_window self.friend_list = friend_list self.fchat_prv.add_friend_gui = self", "= Gtk.Orientation.VERTICAL) self.fchat_prv = fchat_prv self.main_window = main_window self.friend_list =", "that contains your info') return if self.friend_info.get_text() == '': self.msg_info('Friend", "-1) def msg_info(self, text): dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK,", "self.cancel_bt = Gtk.Button('Cancel') self.cancel_bt.connect('clicked', self.on_cancel) self.close_bt = Gtk.Button('Close') self.close_bt.connect('clicked', self.on_close)", "Gtk.Box() h_bt.pack_start(self.generate_keys_bt, True, False, 7) h_bt.pack_start(self.save_bt, True, False, 7) h_bt.pack_start(self.cancel_bt,", "False, 7) h_bt.pack_start(self.close_bt, True, False, 7) self.pack_start(h_bt, True, False, 7)", "dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, \"ERROR\") dialog.format_secondary_text(\"Error adding friend", "self.save_bt.connect('clicked', self.on_save) self.cancel_bt = Gtk.Button('Cancel') self.cancel_bt.connect('clicked', self.on_cancel) self.close_bt = Gtk.Button('Close')", "self.friend_info.get_text() == '': self.msg_info('Friend info is required') return self.fchat_prv.add_friend(self.pub, self.prv,", "self.fchat_prv.generate_key_for_friend() self.owner_info.set_text(self.pub_info_key) self.on_generate_keys_start() def on_generate_keys_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False)", "self.msg_info('You should generate a key that contains your info') return", "self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_save_start_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True)", "Gtk.Button('Cancel') self.cancel_bt.connect('clicked', self.on_cancel) self.close_bt = Gtk.Button('Close') self.close_bt.connect('clicked', self.on_close) self.owner_info =", "try later\") dialog.run() dialog.destroy() self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True)", "self.on_cancel) self.close_bt = Gtk.Button('Close') self.close_bt.connect('clicked', self.on_close) self.owner_info = Gtk.Entry() self.owner_info.set_sensitive(False)", "spacing=7, orientation = Gtk.Orientation.VERTICAL) self.fchat_prv = fchat_prv self.main_window = main_window", "def on_save_start_duplicate(self, text): self.msg_info(text) def on_save_start_faild(self): dialog = Gtk.MessageDialog(self.main_window, 0,", "self.friend_info.set_placeholder_text('Key of your friend') self.spinner = Gtk.Spinner() self.pack_start(h_owner, True, False,", "self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_copy_clipboard(self, button):", "self.owner_info = Gtk.Entry() self.owner_info.set_sensitive(False) self.copy_clipboard_bt = Gtk.Button(label='Copy to clipboard') self.clipboard", "text): self.msg_info(text) def on_save_start_faild(self): dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK,", "friend please try later\") dialog.run() dialog.destroy() self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True)", "Gtk.Orientation.VERTICAL) self.fchat_prv = fchat_prv self.main_window = main_window self.friend_list = friend_list", "None def on_generate_keys(self, button): self.pub, self.prv, self.pub_info_key, self.job = self.fchat_prv.generate_key_for_friend()", "Gdk class AddFriendWidget(Gtk.Box): def __init__(self, main_window, fchat_prv, friend_list): Gtk.Box.__init__(self, spacing=7,", "key that contains your info') return if self.friend_info.get_text() == '':", "return if self.friend_info.get_text() == '': self.msg_info('Friend info is required') return", "def msg_info(self, text): dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, \"Info\")", "\"ERROR\") dialog.format_secondary_text(\"Error adding friend please try later\") dialog.run() dialog.destroy() self.spinner.hide()", "on_save(self, button): if self.owner_info.get_text() == '': self.msg_info('You should generate a", "info is required') return self.fchat_prv.add_friend(self.pub, self.prv, self.friend_info.get_text()) self.on_save_start() def on_save_start(self):", "please try later\") dialog.run() dialog.destroy() self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True)", "Gtk.Entry() self.friend_info.set_placeholder_text('Key of your friend') self.spinner = Gtk.Spinner() self.pack_start(h_owner, True,", "self.on_save) self.cancel_bt = Gtk.Button('Cancel') self.cancel_bt.connect('clicked', self.on_cancel) self.close_bt = Gtk.Button('Close') self.close_bt.connect('clicked',", "1) h_owner.pack_start(self.copy_clipboard_bt, False, False, 1) self.friend_info = Gtk.Entry() self.friend_info.set_placeholder_text('Key of", "main_window, fchat_prv, friend_list): Gtk.Box.__init__(self, spacing=7, orientation = Gtk.Orientation.VERTICAL) self.fchat_prv =", "self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_generate_keys_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True)", "== '': self.msg_info('Friend info is required') return self.fchat_prv.add_friend(self.pub, self.prv, self.friend_info.get_text())", "'': self.msg_info('Friend info is required') return self.fchat_prv.add_friend(self.pub, self.prv, self.friend_info.get_text()) self.on_save_start()", "self.friend_list.sync_friends_list() def on_save_start_duplicate(self, text): self.msg_info(text) def on_save_start_faild(self): dialog = Gtk.MessageDialog(self.main_window,", "import Gio, Gtk, Gdk class AddFriendWidget(Gtk.Box): def __init__(self, main_window, fchat_prv,", "h_owner.pack_start(self.copy_clipboard_bt, False, False, 1) self.friend_info = Gtk.Entry() self.friend_info.set_placeholder_text('Key of your", "self.msg_info('Friend info is required') return self.fchat_prv.add_friend(self.pub, self.prv, self.friend_info.get_text()) self.on_save_start() def", "self.copy_clipboard_bt.set_sensitive(False) def on_generate_keys_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True)", "on_generate_keys_faild(self, text): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def", "on_save_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_save_start_ok(self):", "self.owner_info.set_text(self.pub_info_key) self.on_generate_keys_start() def on_generate_keys_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False)", "self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) self.friend_list.sync_friends_list() def on_save_start_duplicate(self, text): self.msg_info(text) def on_save_start_faild(self): dialog", "= Gtk.Box() h_bt.pack_start(self.generate_keys_bt, True, False, 7) h_bt.pack_start(self.save_bt, True, False, 7)", "self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_generate_keys_ok(self): self.spinner.hide()", "msg_info(self, text): dialog = Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, \"Info\") dialog.format_secondary_text(text)", "AddFriendWidget(Gtk.Box): def __init__(self, main_window, fchat_prv, friend_list): Gtk.Box.__init__(self, spacing=7, orientation =", "self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) self.friend_list.sync_friends_list() def on_save_start_duplicate(self, text):", "dialog.run() dialog.destroy() self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def", "'': self.msg_info('You should generate a key that contains your info')", "on_save_start_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) self.friend_list.sync_friends_list() def", "on_cancel(self, button): if self.job: self.job.remove_from_queue_when_finish() def on_close(self, button): self.main_window.application.back_main_window_or_friend_list() def", "True, False, 7) self.pack_start(self.spinner, True, False, 7) h_bt = Gtk.Box()", "self.copy_clipboard_bt = Gtk.Button(label='Copy to clipboard') self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) self.copy_clipboard_bt.connect('clicked', self.on_copy_clipboard)", "Gtk.Button('Close') self.close_bt.connect('clicked', self.on_close) self.owner_info = Gtk.Entry() self.owner_info.set_sensitive(False) self.copy_clipboard_bt = Gtk.Button(label='Copy", "self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_save_start_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True)", "self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_copy_clipboard(self, button): self.clipboard.set_text(self.owner_info.get_text(), -1) def", "= Gtk.Entry() self.friend_info.set_placeholder_text('Key of your friend') self.spinner = Gtk.Spinner() self.pack_start(h_owner,", "self.pub, self.prv, self.pub_info_key, self.job = self.fchat_prv.generate_key_for_friend() self.owner_info.set_text(self.pub_info_key) self.on_generate_keys_start() def on_generate_keys_start(self):", "0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, \"ERROR\") dialog.format_secondary_text(\"Error adding friend please try later\")", "= Gtk.Spinner() self.pack_start(h_owner, True, False, 7) self.pack_start(self.friend_info, True, False, 7)", "self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_cancel(self, button): if self.job: self.job.remove_from_queue_when_finish() def", "def on_generate_keys_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def", "= friend_list self.fchat_prv.add_friend_gui = self self.generate_keys_bt = Gtk.Button('Generate Key') self.generate_keys_bt.connect('clicked',", "= Gtk.Box(spacing=5) h_owner.pack_start(self.owner_info, True, True, 1) h_owner.pack_start(self.copy_clipboard_bt, False, False, 1)", "self.fchat_prv = fchat_prv self.main_window = main_window self.friend_list = friend_list self.fchat_prv.add_friend_gui", "clipboard') self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) self.copy_clipboard_bt.connect('clicked', self.on_copy_clipboard) h_owner = Gtk.Box(spacing=5) h_owner.pack_start(self.owner_info,", "== '': self.msg_info('You should generate a key that contains your", "Gtk, Gdk class AddFriendWidget(Gtk.Box): def __init__(self, main_window, fchat_prv, friend_list): Gtk.Box.__init__(self,", "7) self.pack_start(h_bt, True, False, 7) self.job = None def on_generate_keys(self,", "self.on_generate_keys) self.save_bt = Gtk.Button('Save') self.save_bt.connect('clicked', self.on_save) self.cancel_bt = Gtk.Button('Cancel') self.cancel_bt.connect('clicked',", "Key') self.generate_keys_bt.connect('clicked', self.on_generate_keys) self.save_bt = Gtk.Button('Save') self.save_bt.connect('clicked', self.on_save) self.cancel_bt =", "def __init__(self, main_window, fchat_prv, friend_list): Gtk.Box.__init__(self, spacing=7, orientation = Gtk.Orientation.VERTICAL)", "self.main_window.application.back_main_window_or_friend_list() def on_save(self, button): if self.owner_info.get_text() == '': self.msg_info('You should", "False, 1) self.friend_info = Gtk.Entry() self.friend_info.set_placeholder_text('Key of your friend') self.spinner", "self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_cancel(self, button): if self.job:", "fchat_prv, friend_list): Gtk.Box.__init__(self, spacing=7, orientation = Gtk.Orientation.VERTICAL) self.fchat_prv = fchat_prv", "= Gtk.Button('Generate Key') self.generate_keys_bt.connect('clicked', self.on_generate_keys) self.save_bt = Gtk.Button('Save') self.save_bt.connect('clicked', self.on_save)", "friend') self.spinner = Gtk.Spinner() self.pack_start(h_owner, True, False, 7) self.pack_start(self.friend_info, True,", "self.copy_clipboard_bt.set_sensitive(False) def on_save_start_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True)", "button): self.main_window.application.back_main_window_or_friend_list() def on_save(self, button): if self.owner_info.get_text() == '': self.msg_info('You", "h_bt.pack_start(self.cancel_bt, True, False, 7) h_bt.pack_start(self.close_bt, True, False, 7) self.pack_start(h_bt, True,", "1) self.friend_info = Gtk.Entry() self.friend_info.set_placeholder_text('Key of your friend') self.spinner =", "self.job = None def on_generate_keys(self, button): self.pub, self.prv, self.pub_info_key, self.job", "self.close_bt.connect('clicked', self.on_close) self.owner_info = Gtk.Entry() self.owner_info.set_sensitive(False) self.copy_clipboard_bt = Gtk.Button(label='Copy to", "Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, \"ERROR\") dialog.format_secondary_text(\"Error adding friend please try", "Gtk.Box(spacing=5) h_owner.pack_start(self.owner_info, True, True, 1) h_owner.pack_start(self.copy_clipboard_bt, False, False, 1) self.friend_info", "self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_copy_clipboard(self, button): self.clipboard.set_text(self.owner_info.get_text(), -1) def msg_info(self, text):", "generate a key that contains your info') return if self.friend_info.get_text()", "Gtk.Box.__init__(self, spacing=7, orientation = Gtk.Orientation.VERTICAL) self.fchat_prv = fchat_prv self.main_window =", "Gtk.Entry() self.owner_info.set_sensitive(False) self.copy_clipboard_bt = Gtk.Button(label='Copy to clipboard') self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)", "self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_generate_keys_faild(self, text): self.spinner.hide()", "Gtk.Spinner() self.pack_start(h_owner, True, False, 7) self.pack_start(self.friend_info, True, False, 7) self.pack_start(self.spinner,", "self.pub_info_key, self.job = self.fchat_prv.generate_key_for_friend() self.owner_info.set_text(self.pub_info_key) self.on_generate_keys_start() def on_generate_keys_start(self): self.spinner.show() self.spinner.start()", "self.pack_start(self.spinner, True, False, 7) h_bt = Gtk.Box() h_bt.pack_start(self.generate_keys_bt, True, False,", "self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_generate_keys_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True)", "self.copy_clipboard_bt.set_sensitive(True) def on_cancel(self, button): if self.job: self.job.remove_from_queue_when_finish() def on_close(self, button):", "self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_copy_clipboard(self, button): self.clipboard.set_text(self.owner_info.get_text(), -1) def msg_info(self,", "self.on_generate_keys_start() def on_generate_keys_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False)", "on_generate_keys(self, button): self.pub, self.prv, self.pub_info_key, self.job = self.fchat_prv.generate_key_for_friend() self.owner_info.set_text(self.pub_info_key) self.on_generate_keys_start()", "self.spinner.start() self.friend_info.set_sensitive(False) self.save_bt.set_sensitive(False) self.close_bt.set_sensitive(False) self.generate_keys_bt.set_sensitive(False) self.copy_clipboard_bt.set_sensitive(False) def on_save_start_ok(self): self.spinner.hide() self.spinner.stop()", "= Gtk.MessageDialog(self.main_window, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, \"ERROR\") dialog.format_secondary_text(\"Error adding friend please", "Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, \"ERROR\") dialog.format_secondary_text(\"Error adding friend please try later\") dialog.run()", "dialog.destroy() self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_copy_clipboard(self,", "return self.fchat_prv.add_friend(self.pub, self.prv, self.friend_info.get_text()) self.on_save_start() def on_save_start(self): self.spinner.show() self.spinner.start() self.friend_info.set_sensitive(False)", "def on_generate_keys(self, button): self.pub, self.prv, self.pub_info_key, self.job = self.fchat_prv.generate_key_for_friend() self.owner_info.set_text(self.pub_info_key)", "self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) self.friend_list.sync_friends_list() def on_save_start_duplicate(self, text): self.msg_info(text) def on_save_start_faild(self):", "= Gtk.Entry() self.owner_info.set_sensitive(False) self.copy_clipboard_bt = Gtk.Button(label='Copy to clipboard') self.clipboard =", "of your friend') self.spinner = Gtk.Spinner() self.pack_start(h_owner, True, False, 7)", "your friend') self.spinner = Gtk.Spinner() self.pack_start(h_owner, True, False, 7) self.pack_start(self.friend_info,", "True, False, 7) self.pack_start(h_bt, True, False, 7) self.job = None", "required') return self.fchat_prv.add_friend(self.pub, self.prv, self.friend_info.get_text()) self.on_save_start() def on_save_start(self): self.spinner.show() self.spinner.start()", "self.friend_info = Gtk.Entry() self.friend_info.set_placeholder_text('Key of your friend') self.spinner = Gtk.Spinner()", "self self.generate_keys_bt = Gtk.Button('Generate Key') self.generate_keys_bt.connect('clicked', self.on_generate_keys) self.save_bt = Gtk.Button('Save')", "def on_save_start_ok(self): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True) self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) self.friend_list.sync_friends_list()", "7) h_bt.pack_start(self.save_bt, True, False, 7) h_bt.pack_start(self.cancel_bt, True, False, 7) h_bt.pack_start(self.close_bt,", "Gtk.Button(label='Copy to clipboard') self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) self.copy_clipboard_bt.connect('clicked', self.on_copy_clipboard) h_owner =", "self.prv, self.pub_info_key, self.job = self.fchat_prv.generate_key_for_friend() self.owner_info.set_text(self.pub_info_key) self.on_generate_keys_start() def on_generate_keys_start(self): self.spinner.show()", "self.close_bt.set_sensitive(True) self.generate_keys_bt.set_sensitive(True) self.copy_clipboard_bt.set_sensitive(True) def on_generate_keys_faild(self, text): self.spinner.hide() self.spinner.stop() self.friend_info.set_sensitive(True) self.save_bt.set_sensitive(True)" ]
[ "# 我的血量 my_hp = 1000 # 敌人的血量 enemy_hp = 1000", "my_hp - random.randint(0, 50) # 敌人收到随机的攻击,减少血量 enemy_hp = enemy_hp -", "我的血量 my_hp = 1000 # 敌人的血量 enemy_hp = 1000 while", "my_hp = 1000 # 敌人的血量 enemy_hp = 1000 while True:", "enemy_hp - random.randint(0, 50) if my_hp <= 0: # 如果我此时的血量<=0,则敌人赢了", "= 1000 while True: # 我受到随机的攻击,减少血量 my_hp = my_hp -", "my_hp = my_hp - random.randint(0, 50) # 敌人收到随机的攻击,减少血量 enemy_hp =", "import random def game(): # 我的血量 my_hp = 1000 #", "= enemy_hp - random.randint(0, 50) if my_hp <= 0: #", "enemy_hp = 1000 while True: # 我受到随机的攻击,减少血量 my_hp = my_hp", "我受到随机的攻击,减少血量 my_hp = my_hp - random.randint(0, 50) # 敌人收到随机的攻击,减少血量 enemy_hp", "<= 0: # 如果敌人此时的血量<=0,则我赢了 print(\"我赢了\") # 跳出循环 break if __name__", "# 如果敌人此时的血量<=0,则我赢了 print(\"我赢了\") # 跳出循环 break if __name__ == '__main__':", "while True: # 我受到随机的攻击,减少血量 my_hp = my_hp - random.randint(0, 50)", "<filename>python01/game.py import random def game(): # 我的血量 my_hp = 1000", "elif enemy_hp <= 0: # 如果敌人此时的血量<=0,则我赢了 print(\"我赢了\") # 跳出循环 break", "敌人的血量 enemy_hp = 1000 while True: # 我受到随机的攻击,减少血量 my_hp =", "def game(): # 我的血量 my_hp = 1000 # 敌人的血量 enemy_hp", "random.randint(0, 50) if my_hp <= 0: # 如果我此时的血量<=0,则敌人赢了 print(\"敌人赢了\") #", "= my_hp - random.randint(0, 50) # 敌人收到随机的攻击,减少血量 enemy_hp = enemy_hp", "# 敌人的血量 enemy_hp = 1000 while True: # 我受到随机的攻击,减少血量 my_hp", "0: # 如果我此时的血量<=0,则敌人赢了 print(\"敌人赢了\") # 退出循环 break elif enemy_hp <=", "- random.randint(0, 50) if my_hp <= 0: # 如果我此时的血量<=0,则敌人赢了 print(\"敌人赢了\")", "- random.randint(0, 50) # 敌人收到随机的攻击,减少血量 enemy_hp = enemy_hp - random.randint(0,", "敌人收到随机的攻击,减少血量 enemy_hp = enemy_hp - random.randint(0, 50) if my_hp <=", "如果敌人此时的血量<=0,则我赢了 print(\"我赢了\") # 跳出循环 break if __name__ == '__main__': game()", "random.randint(0, 50) # 敌人收到随机的攻击,减少血量 enemy_hp = enemy_hp - random.randint(0, 50)", "1000 # 敌人的血量 enemy_hp = 1000 while True: # 我受到随机的攻击,减少血量", "game(): # 我的血量 my_hp = 1000 # 敌人的血量 enemy_hp =", "如果我此时的血量<=0,则敌人赢了 print(\"敌人赢了\") # 退出循环 break elif enemy_hp <= 0: #", "1000 while True: # 我受到随机的攻击,减少血量 my_hp = my_hp - random.randint(0,", "0: # 如果敌人此时的血量<=0,则我赢了 print(\"我赢了\") # 跳出循环 break if __name__ ==", "break elif enemy_hp <= 0: # 如果敌人此时的血量<=0,则我赢了 print(\"我赢了\") # 跳出循环", "# 我受到随机的攻击,减少血量 my_hp = my_hp - random.randint(0, 50) # 敌人收到随机的攻击,减少血量", "= 1000 # 敌人的血量 enemy_hp = 1000 while True: #", "if my_hp <= 0: # 如果我此时的血量<=0,则敌人赢了 print(\"敌人赢了\") # 退出循环 break", "print(\"敌人赢了\") # 退出循环 break elif enemy_hp <= 0: # 如果敌人此时的血量<=0,则我赢了", "退出循环 break elif enemy_hp <= 0: # 如果敌人此时的血量<=0,则我赢了 print(\"我赢了\") #", "my_hp <= 0: # 如果我此时的血量<=0,则敌人赢了 print(\"敌人赢了\") # 退出循环 break elif", "<= 0: # 如果我此时的血量<=0,则敌人赢了 print(\"敌人赢了\") # 退出循环 break elif enemy_hp", "enemy_hp <= 0: # 如果敌人此时的血量<=0,则我赢了 print(\"我赢了\") # 跳出循环 break if", "enemy_hp = enemy_hp - random.randint(0, 50) if my_hp <= 0:", "50) if my_hp <= 0: # 如果我此时的血量<=0,则敌人赢了 print(\"敌人赢了\") # 退出循环", "# 如果我此时的血量<=0,则敌人赢了 print(\"敌人赢了\") # 退出循环 break elif enemy_hp <= 0:", "50) # 敌人收到随机的攻击,减少血量 enemy_hp = enemy_hp - random.randint(0, 50) if", "random def game(): # 我的血量 my_hp = 1000 # 敌人的血量", "# 敌人收到随机的攻击,减少血量 enemy_hp = enemy_hp - random.randint(0, 50) if my_hp", "# 退出循环 break elif enemy_hp <= 0: # 如果敌人此时的血量<=0,则我赢了 print(\"我赢了\")", "True: # 我受到随机的攻击,减少血量 my_hp = my_hp - random.randint(0, 50) #" ]
[ "\"Warning\" info = \"Info\" ok = \"OK\" too_busy = \"Too", "self.response = response self.message = message super().__init__(self.message) def __str__(self): return", "= message class ApiResponseError(Exception): def __init__(self, response: ApiResponse, message=\"Api exception\"):", "import Enum class ApiResponseType(Enum): error = \"Error\" warning = \"Warning\"", "code: int, response_type: ApiResponseType, message): self.code = code self.type =", "message class ApiResponseError(Exception): def __init__(self, response: ApiResponse, message=\"Api exception\"): self.response", "message=\"Api exception\"): self.response = response self.message = message super().__init__(self.message) def", "from enum import Enum class ApiResponseType(Enum): error = \"Error\" warning", "error = \"Error\" warning = \"Warning\" info = \"Info\" ok", "\"Info\" ok = \"OK\" too_busy = \"Too busy\" class ApiResponse:", "ok = \"OK\" too_busy = \"Too busy\" class ApiResponse: def", "info = \"Info\" ok = \"OK\" too_busy = \"Too busy\"", "response_type: ApiResponseType, message): self.code = code self.type = response_type self.message", "class ApiResponseError(Exception): def __init__(self, response: ApiResponse, message=\"Api exception\"): self.response =", "= response self.message = message super().__init__(self.message) def __str__(self): return f\"{self.message}\\n{self.response.code}:", "= \"OK\" too_busy = \"Too busy\" class ApiResponse: def __init__(self,", "self.type = response_type self.message = message class ApiResponseError(Exception): def __init__(self,", "def __init__(self, response: ApiResponse, message=\"Api exception\"): self.response = response self.message", "exception\"): self.response = response self.message = message super().__init__(self.message) def __str__(self):", "= code self.type = response_type self.message = message class ApiResponseError(Exception):", "\"OK\" too_busy = \"Too busy\" class ApiResponse: def __init__(self, code:", "= \"Error\" warning = \"Warning\" info = \"Info\" ok =", "def __init__(self, code: int, response_type: ApiResponseType, message): self.code = code", "int, response_type: ApiResponseType, message): self.code = code self.type = response_type", "= \"Warning\" info = \"Info\" ok = \"OK\" too_busy =", "class ApiResponseType(Enum): error = \"Error\" warning = \"Warning\" info =", "too_busy = \"Too busy\" class ApiResponse: def __init__(self, code: int,", "= \"Too busy\" class ApiResponse: def __init__(self, code: int, response_type:", "ApiResponseType(Enum): error = \"Error\" warning = \"Warning\" info = \"Info\"", "ApiResponseType, message): self.code = code self.type = response_type self.message =", "code self.type = response_type self.message = message class ApiResponseError(Exception): def", "= \"Info\" ok = \"OK\" too_busy = \"Too busy\" class", "response: ApiResponse, message=\"Api exception\"): self.response = response self.message = message", "__init__(self, response: ApiResponse, message=\"Api exception\"): self.response = response self.message =", "busy\" class ApiResponse: def __init__(self, code: int, response_type: ApiResponseType, message):", "warning = \"Warning\" info = \"Info\" ok = \"OK\" too_busy", "ApiResponse, message=\"Api exception\"): self.response = response self.message = message super().__init__(self.message)", "class ApiResponse: def __init__(self, code: int, response_type: ApiResponseType, message): self.code", "response self.message = message super().__init__(self.message) def __str__(self): return f\"{self.message}\\n{self.response.code}: [{self.response.type}]", "= response_type self.message = message class ApiResponseError(Exception): def __init__(self, response:", "self.code = code self.type = response_type self.message = message class", "__init__(self, code: int, response_type: ApiResponseType, message): self.code = code self.type", "Enum class ApiResponseType(Enum): error = \"Error\" warning = \"Warning\" info", "\"Error\" warning = \"Warning\" info = \"Info\" ok = \"OK\"", "self.message = message class ApiResponseError(Exception): def __init__(self, response: ApiResponse, message=\"Api", "self.message = message super().__init__(self.message) def __str__(self): return f\"{self.message}\\n{self.response.code}: [{self.response.type}] {self.response.message}\"", "enum import Enum class ApiResponseType(Enum): error = \"Error\" warning =", "message): self.code = code self.type = response_type self.message = message", "ApiResponse: def __init__(self, code: int, response_type: ApiResponseType, message): self.code =", "ApiResponseError(Exception): def __init__(self, response: ApiResponse, message=\"Api exception\"): self.response = response", "\"Too busy\" class ApiResponse: def __init__(self, code: int, response_type: ApiResponseType,", "response_type self.message = message class ApiResponseError(Exception): def __init__(self, response: ApiResponse," ]
[ "browser based incomplete template upload, followed by SSVM destroy. Template", "string import telnetlib import os import urllib.request, urllib.parse, urllib.error import", "Private IP and Link local IP # for newly created", "OF ANY # KIND, either express or implied. See the", "more contributor license agreements. See the NOTICE file # distributed", "'privateip'), True, \"Check whether SSVM has private IP field\" )", "SSVM has public IP field\" ) # Wait for the", "zoneid=self.zone.id ) self.assertEqual( isinstance(list_ssvm_response, list), True, \"Check list response returns", "Apache Software Foundation (ASF) under one # or more contributor", "be merged back \"\"\" @classmethod def setUpClass(cls): cls.testClient = super(TestBrowseUploadTemplate,", "except Exception as e: self.fail(\"Exception occurred : %s\" % e)", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import cloudstackTestCase import", "2.0 (the # \"License\"); you may not use this file", "True, \"Check list response returns a valid list\" ) ssvm_response", "nose.plugins.attrib import attr from marvin.cloudstackTestCase import cloudstackTestCase import unittest from", "new name with name of destroyed SSVM\" ) self.assertEqual( hasattr(ssvm_response,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "cmd = destroySystemVm.destroySystemVmCmd() cmd.id = ssvm_response.id self.apiclient.destroySystemVm(cmd) timeout = self.testdata[\"timeout\"]", "specific language governing permissions and limitations # under the License.", "to UploadAbandoned state and get cleaned up. \"\"\" try: self.debug(\"=========================", "under the License is distributed on an # \"AS IS\"", "cls.uploadtemplateformat = \"VHD\" cls.templatename = \"test\" cls.templatehypervisor = \"XenServer\" cls.templateostypeid", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "cls.testClient.getApiClient() cls.hypervisor = cls.testClient.getHypervisorInfo() cls._cleanup = [] cls.cleanup = []", "template_response=self.apiclient.getUploadParamsForTemplate(cmd) #Destroy SSVM, and wait for new one to start", "cls.zone.id) cls.account = Account.create( cls.apiclient, cls.testdata[\"account\"], domainid=cls.domain.id ) cls._cleanup =", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "* from marvin.codes import PASS, FAILED, SUCCESS, XEN_SERVER from marvin.sshClient", "= super(TestBrowseUploadTemplate, self).getClsTestClient().getApiClient() cleanup_resources(self.apiclient, self._cleanup) except Exception as e: raise", "marvin.codes import PASS, FAILED, SUCCESS, XEN_SERVER from marvin.sshClient import SshClient", "self.waitForSystemVMAgent(ssvm_response.name) return @attr(tags = [\"advanced\", \"advancedns\", \"smoke\", \"basic\"], required_hardware=\"false\") def", "distributed with this work for additional information # regarding copyright", "True, \"Check whether SSVM has link local IP field\" )", "tearDownClass(self): try: self.apiclient = super(TestBrowseUploadTemplate, self).getClsTestClient().getApiClient() cleanup_resources(self.apiclient, self._cleanup) except Exception", "SSVM\" ) self.assertEqual( hasattr(ssvm_response, 'privateip'), True, \"Check whether SSVM has", "ssvm_response = list_ssvm_response[0] old_name = ssvm_response.name self.debug(\"Destroying SSVM: %s\" %", "for the # specific language governing permissions and limitations #", "for the agent to be up self.waitForSystemVMAgent(ssvm_response.name) return @attr(tags =", "requests requests.packages.urllib3.disable_warnings() import random import string import telnetlib import os", "See the License for the # specific language governing permissions", "to in writing, # software distributed under the License is", "incomplete template upload, followed by SSVM destroy. Template should go", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "\"There are no hypervisor's available. Check list hosts response\") cls.uploadtemplateformat", "Check list hosts response\") cls.uploadtemplateformat = \"VHD\" cls.templatename = \"test\"", "SSVM start list_template_response=Template.list( self.apiclient, id=template_response.id, templatefilter=\"all\", zoneid=self.zone.id) self.assertEqual(list_template_response, None, \"Template", "= Account.create( cls.apiclient, cls.testdata[\"account\"], domainid=cls.domain.id ) cls._cleanup = [ cls.account", "self.apiclient, zoneid=self.zone.id, systemvmtype='secondarystoragevm' ) if isinstance(list_ssvm_response, list): if list_ssvm_response[0].state ==", "domainid=cls.domain.id ) cls._cleanup = [ cls.account ] def waitForSystemVMAgent(self, vmname):", "marvin.cloudstackTestCase import cloudstackTestCase import unittest from marvin.cloudstackAPI import * from", "self.debug(\"Destroying SSVM: %s\" % ssvm_response.id) cmd = destroySystemVm.destroySystemVmCmd() cmd.id =", "file # distributed with this work for additional information #", "True: list_ssvm_response = list_ssvms( self.apiclient, zoneid=self.zone.id, systemvmtype='secondarystoragevm' ) if isinstance(list_ssvm_response,", "self.assertEqual( hasattr(ssvm_response, 'publicip'), True, \"Check whether SSVM has public IP", "import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import cloudstackTestCase", "1 def destroy_ssvm(self): list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', zoneid=self.zone.id", "failed!\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout - 1 ssvm_response = list_ssvm_response[0]", "unittest from marvin.cloudstackAPI import * from marvin.lib.utils import * from", "self.fail(\"Exception occurred : %s\" % e) return @classmethod def tearDownClass(self):", "destroy_ssvm(self): list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', zoneid=self.zone.id ) self.assertEqual(", "are no hypervisor's available. Check list hosts response\") cls.uploadtemplateformat =", "from marvin.cloudstackAPI import * from marvin.lib.utils import * from marvin.lib.base", "of destroyed SSVM\" ) self.assertEqual( hasattr(ssvm_response, 'privateip'), True, \"Check whether", "implied. See the License for the # specific language governing", "import * from marvin.lib.utils import * from marvin.lib.base import *", "back \"\"\" @classmethod def setUpClass(cls): cls.testClient = super(TestBrowseUploadTemplate, cls).getClsTestClient() cls.testdata", "to you under the Apache License, Version 2.0 (the #", "for browser based upload template feature. Once all issues in", "\"basic\"], required_hardware=\"false\") def test_browser_upload_template_incomplete(self): \"\"\" Test browser based incomplete template", "#Only register template, without uploading cmd = getUploadParamsForTemplate.getUploadParamsForTemplateCmd() cmd.zoneid =", "name with name of destroyed SSVM\" ) self.assertEqual( hasattr(ssvm_response, 'privateip'),", "except Exception as e: raise Exception(\"Warning: Exception during cleanup :", "ssvm_response.id self.apiclient.destroySystemVm(cmd) timeout = self.testdata[\"timeout\"] while True: list_ssvm_response = list_ssvms(", "with template sync-up\") except Exception as e: self.fail(\"Exception occurred :", "] def waitForSystemVMAgent(self, vmname): timeout = self.testdata[\"timeout\"] while True: list_host_response", "== 'Running': break if timeout == 0: raise Exception(\"List SSVM", "may not use this file except in compliance # with", "local IP # for newly created SSVM self.assertNotEqual( ssvm_response.name, old_name,", "this should be merged back \"\"\" @classmethod def setUpClass(cls): cls.testClient", "self.uploadtemplateformat cmd.name=self.templatename+self.account.name+(random.choice(string.ascii_uppercase)) cmd.account=self.account.name cmd.domainid=self.domain.id cmd.displaytext=cmd.name cmd.hypervisor=self.templatehypervisor cmd.ostypeid=self.templateostypeid template_response=self.apiclient.getUploadParamsForTemplate(cmd) #Destroy SSVM,", "* from marvin.lib.common import * from marvin.codes import PASS, FAILED,", "browser based incomplete template upload ========================\") #Only register template, without", "cls.account ] def waitForSystemVMAgent(self, vmname): timeout = self.testdata[\"timeout\"] while True:", "all issues in test_browse_templates.py are fixed, this should be merged", "state='Running', zoneid=self.zone.id ) self.assertEqual( isinstance(list_ssvm_response, list), True, \"Check list response", "License, Version 2.0 (the # \"License\"); you may not use", "template sync-up\") except Exception as e: self.fail(\"Exception occurred : %s\"", "either express or implied. See the License for the #", "fixed, this should be merged back \"\"\" @classmethod def setUpClass(cls):", "return @classmethod def tearDownClass(self): try: self.apiclient = super(TestBrowseUploadTemplate, self).getClsTestClient().getApiClient() cleanup_resources(self.apiclient,", "import * from marvin.codes import PASS, FAILED, SUCCESS, XEN_SERVER from", "[] hosts = list_hosts( cls.apiclient, type=\"Routing\" ) if hosts is", "be up self.waitForSystemVMAgent(ssvm_response.name) return @attr(tags = [\"advanced\", \"advancedns\", \"smoke\", \"basic\"],", "cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests()) cls.domain = get_domain(cls.apiclient) cls.pod = get_pod(cls.apiclient,", "part of sync-up during new SSVM start list_template_response=Template.list( self.apiclient, id=template_response.id,", "field\" ) self.assertEqual( hasattr(ssvm_response, 'publicip'), True, \"Check whether SSVM has", "Template should go to UploadAbandoned state and get cleaned up.", "cls._cleanup = [ cls.account ] def waitForSystemVMAgent(self, vmname): timeout =", "additional information # regarding copyright ownership. The ASF licenses this", "import time import tempfile _multiprocess_shared_ = True class TestBrowseUploadTemplate(cloudstackTestCase): \"\"\"", "SSVM new name with name of destroyed SSVM\" ) self.assertEqual(", "See the NOTICE file # distributed with this work for", "= list_hosts( cls.apiclient, type=\"Routing\" ) if hosts is None: cls.SkipTest(", "= getUploadParamsForTemplate.getUploadParamsForTemplateCmd() cmd.zoneid = self.zone.id cmd.format = self.uploadtemplateformat cmd.name=self.templatename+self.account.name+(random.choice(string.ascii_uppercase)) cmd.account=self.account.name", "self.apiclient, name=vmname ) if list_host_response and list_host_response[0].state == 'Up': break", "while True: list_host_response = list_hosts( self.apiclient, name=vmname ) if list_host_response", "Link local IP # for newly created SSVM self.assertNotEqual( ssvm_response.name,", "for newly created SSVM self.assertNotEqual( ssvm_response.name, old_name, \"Check SSVM new", "hasattr(ssvm_response, 'linklocalip'), True, \"Check whether SSVM has link local IP", "= 142 cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests()) cls.domain = get_domain(cls.apiclient) cls.pod", "Apache License, Version 2.0 (the # \"License\"); you may not", "cls.hypervisor = cls.testClient.getHypervisorInfo() cls._cleanup = [] cls.cleanup = [] hosts", "XEN_SERVER from marvin.sshClient import SshClient import requests requests.packages.urllib3.disable_warnings() import random", "are fixed, this should be merged back \"\"\" @classmethod def", "import string import telnetlib import os import urllib.request, urllib.parse, urllib.error", "PASS, FAILED, SUCCESS, XEN_SERVER from marvin.sshClient import SshClient import requests", "list_host_response[0].state == 'Up': break if timeout == 0: raise Exception(\"Timed", "name=vmname ) if list_host_response and list_host_response[0].state == 'Up': break if", "cmd.zoneid = self.zone.id cmd.format = self.uploadtemplateformat cmd.name=self.templatename+self.account.name+(random.choice(string.ascii_uppercase)) cmd.account=self.account.name cmd.domainid=self.domain.id cmd.displaytext=cmd.name", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "file except in compliance # with the License. You may", "and Link local IP # for newly created SSVM self.assertNotEqual(", "# specific language governing permissions and limitations # under the", "Exception as e: self.fail(\"Exception occurred : %s\" % e) return", ": %s\" % e) return @classmethod def tearDownClass(self): try: self.apiclient", "== 0: raise Exception(\"List SSVM call failed!\") time.sleep(self.testdata[\"sleep\"]) timeout =", "is None: cls.SkipTest( \"There are no hypervisor's available. Check list", "you may not use this file except in compliance #", "test_browse_templates.py are fixed, this should be merged back \"\"\" @classmethod", "= \"XenServer\" cls.templateostypeid = 142 cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests()) cls.domain", "cls.account = Account.create( cls.apiclient, cls.testdata[\"account\"], domainid=cls.domain.id ) cls._cleanup = [", "register template, without uploading cmd = getUploadParamsForTemplate.getUploadParamsForTemplateCmd() cmd.zoneid = self.zone.id", "SUCCESS, XEN_SERVER from marvin.sshClient import SshClient import requests requests.packages.urllib3.disable_warnings() import", "use this file except in compliance # with the License.", "Name, Public IP, Private IP and Link local IP #", "[\"expunge.delay\", \"expunge.interval\"]) #Verify that the template is cleaned up as", "# for newly created SSVM self.assertNotEqual( ssvm_response.name, old_name, \"Check SSVM", "SSVM, and wait for new one to start self.destroy_ssvm() wait_for_cleanup(self.apiclient,", "Local Modules import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase", "'publicip'), True, \"Check whether SSVM has public IP field\" )", "contributor license agreements. See the NOTICE file # distributed with", "urllib.parse, urllib.error import time import tempfile _multiprocess_shared_ = True class", "cmd.format = self.uploadtemplateformat cmd.name=self.templatename+self.account.name+(random.choice(string.ascii_uppercase)) cmd.account=self.account.name cmd.domainid=self.domain.id cmd.displaytext=cmd.name cmd.hypervisor=self.templatehypervisor cmd.ostypeid=self.templateostypeid template_response=self.apiclient.getUploadParamsForTemplate(cmd)", "should go to UploadAbandoned state and get cleaned up. \"\"\"", "cls.SkipTest( \"There are no hypervisor's available. Check list hosts response\")", "from marvin.lib.common import * from marvin.codes import PASS, FAILED, SUCCESS,", "destroyed SSVM\" ) self.assertEqual( hasattr(ssvm_response, 'privateip'), True, \"Check whether SSVM", ") self.assertEqual( hasattr(ssvm_response, 'linklocalip'), True, \"Check whether SSVM has link", "_multiprocess_shared_ = True class TestBrowseUploadTemplate(cloudstackTestCase): \"\"\" Tests for browser based", "upload ========================\") #Only register template, without uploading cmd = getUploadParamsForTemplate.getUploadParamsForTemplateCmd()", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "Public IP, Private IP and Link local IP # for", "newly created SSVM self.assertNotEqual( ssvm_response.name, old_name, \"Check SSVM new name", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "[\"advanced\", \"advancedns\", \"smoke\", \"basic\"], required_hardware=\"false\") def test_browser_upload_template_incomplete(self): \"\"\" Test browser", "with this work for additional information # regarding copyright ownership.", "the agent to be up self.waitForSystemVMAgent(ssvm_response.name) return @attr(tags = [\"advanced\",", "if list_host_response and list_host_response[0].state == 'Up': break if timeout ==", "as e: self.fail(\"Exception occurred : %s\" % e) return @classmethod", "cls.testClient = super(TestBrowseUploadTemplate, cls).getClsTestClient() cls.testdata = cls.testClient.getParsedTestDataConfig() cls.apiclient = cls.testClient.getApiClient()", "= get_zone(cls.apiclient, cls.testClient.getZoneForTests()) cls.domain = get_domain(cls.apiclient) cls.pod = get_pod(cls.apiclient, cls.zone.id)", "time.sleep(self.testdata[\"sleep\"]) timeout = timeout - 1 ssvm_response = list_ssvm_response[0] #", "work for additional information # regarding copyright ownership. The ASF", "cls.templatename = \"test\" cls.templatehypervisor = \"XenServer\" cls.templateostypeid = 142 cls.zone", "systemvmtype='secondarystoragevm' ) if isinstance(list_ssvm_response, list): if list_ssvm_response[0].state == 'Running': break", "getUploadParamsForTemplate.getUploadParamsForTemplateCmd() cmd.zoneid = self.zone.id cmd.format = self.uploadtemplateformat cmd.name=self.templatename+self.account.name+(random.choice(string.ascii_uppercase)) cmd.account=self.account.name cmd.domainid=self.domain.id", "distributed under the License is distributed on an # \"AS", "timeout == 0: raise Exception(\"Timed out waiting for SSVM agent", "break if timeout == 0: raise Exception(\"Timed out waiting for", "template, without uploading cmd = getUploadParamsForTemplate.getUploadParamsForTemplateCmd() cmd.zoneid = self.zone.id cmd.format", "# software distributed under the License is distributed on an", "templatefilter=\"all\", zoneid=self.zone.id) self.assertEqual(list_template_response, None, \"Template is not cleaned up, some", "from marvin.codes import PASS, FAILED, SUCCESS, XEN_SERVER from marvin.sshClient import", "the License. You may obtain a copy of the License", "0: raise Exception(\"Timed out waiting for SSVM agent to be", "cls.cleanup = [] hosts = list_hosts( cls.apiclient, type=\"Routing\" ) if", "import os import urllib.request, urllib.parse, urllib.error import time import tempfile", "self.assertEqual(list_template_response, None, \"Template is not cleaned up, some issue with", "under the Apache License, Version 2.0 (the # \"License\"); you", "cmd.displaytext=cmd.name cmd.hypervisor=self.templatehypervisor cmd.ostypeid=self.templateostypeid template_response=self.apiclient.getUploadParamsForTemplate(cmd) #Destroy SSVM, and wait for new", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "self.assertEqual( hasattr(ssvm_response, 'privateip'), True, \"Check whether SSVM has private IP", "regarding copyright ownership. The ASF licenses this file # to", "cls.templatehypervisor = \"XenServer\" cls.templateostypeid = 142 cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())", "or agreed to in writing, # software distributed under the", "urllib.error import time import tempfile _multiprocess_shared_ = True class TestBrowseUploadTemplate(cloudstackTestCase):", "= ssvm_response.name self.debug(\"Destroying SSVM: %s\" % ssvm_response.id) cmd = destroySystemVm.destroySystemVmCmd()", "cls.domain = get_domain(cls.apiclient) cls.pod = get_pod(cls.apiclient, cls.zone.id) cls.account = Account.create(", "Import Local Modules import marvin from nose.plugins.attrib import attr from", "* from marvin.lib.utils import * from marvin.lib.base import * from", "list_host_response = list_hosts( self.apiclient, name=vmname ) if list_host_response and list_host_response[0].state", "hosts = list_hosts( cls.apiclient, type=\"Routing\" ) if hosts is None:", "has private IP field\" ) self.assertEqual( hasattr(ssvm_response, 'linklocalip'), True, \"Check", "#Destroy SSVM, and wait for new one to start self.destroy_ssvm()", "= True class TestBrowseUploadTemplate(cloudstackTestCase): \"\"\" Tests for browser based upload", "try: self.apiclient = super(TestBrowseUploadTemplate, self).getClsTestClient().getApiClient() cleanup_resources(self.apiclient, self._cleanup) except Exception as", "raise Exception(\"Timed out waiting for SSVM agent to be Up\")", "os import urllib.request, urllib.parse, urllib.error import time import tempfile _multiprocess_shared_", "\"Template is not cleaned up, some issue with template sync-up\")", "try: self.debug(\"========================= Test browser based incomplete template upload ========================\") #Only", "or more contributor license agreements. See the NOTICE file #", "IP field\" ) self.assertEqual( hasattr(ssvm_response, 'linklocalip'), True, \"Check whether SSVM", "cmd.name=self.templatename+self.account.name+(random.choice(string.ascii_uppercase)) cmd.account=self.account.name cmd.domainid=self.domain.id cmd.displaytext=cmd.name cmd.hypervisor=self.templatehypervisor cmd.ostypeid=self.templateostypeid template_response=self.apiclient.getUploadParamsForTemplate(cmd) #Destroy SSVM, and", "this work for additional information # regarding copyright ownership. The", "Exception(\"List SSVM call failed!\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout - 1", "old_name, \"Check SSVM new name with name of destroyed SSVM\"", "cloudstackTestCase import unittest from marvin.cloudstackAPI import * from marvin.lib.utils import", "= timeout - 1 def destroy_ssvm(self): list_ssvm_response = list_ssvms( self.apiclient,", "Once all issues in test_browse_templates.py are fixed, this should be", "the NOTICE file # distributed with this work for additional", "if timeout == 0: raise Exception(\"List SSVM call failed!\") time.sleep(self.testdata[\"sleep\"])", "Test browser based incomplete template upload, followed by SSVM destroy.", "based incomplete template upload ========================\") #Only register template, without uploading", "self._cleanup) except Exception as e: raise Exception(\"Warning: Exception during cleanup", "as e: raise Exception(\"Warning: Exception during cleanup : %s\" %", "whether SSVM has public IP field\" ) # Wait for", "based upload template feature. Once all issues in test_browse_templates.py are", "from marvin.sshClient import SshClient import requests requests.packages.urllib3.disable_warnings() import random import", "self.assertEqual( hasattr(ssvm_response, 'linklocalip'), True, \"Check whether SSVM has link local", "tempfile _multiprocess_shared_ = True class TestBrowseUploadTemplate(cloudstackTestCase): \"\"\" Tests for browser", "= [] hosts = list_hosts( cls.apiclient, type=\"Routing\" ) if hosts", "field\" ) self.assertEqual( hasattr(ssvm_response, 'linklocalip'), True, \"Check whether SSVM has", "True, \"Check whether SSVM has public IP field\" ) #", "should be merged back \"\"\" @classmethod def setUpClass(cls): cls.testClient =", "\"expunge.interval\"]) #Verify that the template is cleaned up as part", ") self.assertEqual( isinstance(list_ssvm_response, list), True, \"Check list response returns a", "created SSVM self.assertNotEqual( ssvm_response.name, old_name, \"Check SSVM new name with", "= get_pod(cls.apiclient, cls.zone.id) cls.account = Account.create( cls.apiclient, cls.testdata[\"account\"], domainid=cls.domain.id )", "upload template feature. Once all issues in test_browse_templates.py are fixed,", "list\" ) ssvm_response = list_ssvm_response[0] old_name = ssvm_response.name self.debug(\"Destroying SSVM:", "\"Check whether SSVM has public IP field\" ) # Wait", "cleanup_resources(self.apiclient, self._cleanup) except Exception as e: raise Exception(\"Warning: Exception during", "cls.testClient.getHypervisorInfo() cls._cleanup = [] cls.cleanup = [] hosts = list_hosts(", "local IP field\" ) self.assertEqual( hasattr(ssvm_response, 'publicip'), True, \"Check whether", "template upload ========================\") #Only register template, without uploading cmd =", "None: cls.SkipTest( \"There are no hypervisor's available. Check list hosts", "KIND, either express or implied. See the License for the", "if hosts is None: cls.SkipTest( \"There are no hypervisor's available.", "\"Check list response returns a valid list\" ) ssvm_response =", "e: raise Exception(\"Warning: Exception during cleanup : %s\" % e)", "private IP field\" ) self.assertEqual( hasattr(ssvm_response, 'linklocalip'), True, \"Check whether", "template feature. Once all issues in test_browse_templates.py are fixed, this", "License. # Import Local Modules import marvin from nose.plugins.attrib import", ") if isinstance(list_ssvm_response, list): if list_ssvm_response[0].state == 'Running': break if", "class TestBrowseUploadTemplate(cloudstackTestCase): \"\"\" Tests for browser based upload template feature.", "self.testdata[\"timeout\"] while True: list_host_response = list_hosts( self.apiclient, name=vmname ) if", "= cls.testClient.getApiClient() cls.hypervisor = cls.testClient.getHypervisorInfo() cls._cleanup = [] cls.cleanup =", "raise Exception(\"List SSVM call failed!\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout -", "e) return @classmethod def tearDownClass(self): try: self.apiclient = super(TestBrowseUploadTemplate, self).getClsTestClient().getApiClient()", "or implied. See the License for the # specific language", "express or implied. See the License for the # specific", "valid list\" ) ssvm_response = list_ssvm_response[0] old_name = ssvm_response.name self.debug(\"Destroying", "marvin.lib.utils import * from marvin.lib.base import * from marvin.lib.common import", "= list_ssvm_response[0] # Verify Name, Public IP, Private IP and", "up as part of sync-up during new SSVM start list_template_response=Template.list(", "import attr from marvin.cloudstackTestCase import cloudstackTestCase import unittest from marvin.cloudstackAPI", "governing permissions and limitations # under the License. # Import", "cls.apiclient, type=\"Routing\" ) if hosts is None: cls.SkipTest( \"There are", "None, \"Template is not cleaned up, some issue with template", "self.apiclient, id=template_response.id, templatefilter=\"all\", zoneid=self.zone.id) self.assertEqual(list_template_response, None, \"Template is not cleaned", "the # specific language governing permissions and limitations # under", "be Up\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout - 1 def destroy_ssvm(self):", "== 'Up': break if timeout == 0: raise Exception(\"Timed out", "super(TestBrowseUploadTemplate, self).getClsTestClient().getApiClient() cleanup_resources(self.apiclient, self._cleanup) except Exception as e: raise Exception(\"Warning:", "1 ssvm_response = list_ssvm_response[0] # Verify Name, Public IP, Private", "vmname): timeout = self.testdata[\"timeout\"] while True: list_host_response = list_hosts( self.apiclient,", "Test browser based incomplete template upload ========================\") #Only register template,", "may obtain a copy of the License at # #", "urllib.request, urllib.parse, urllib.error import time import tempfile _multiprocess_shared_ = True", "@classmethod def tearDownClass(self): try: self.apiclient = super(TestBrowseUploadTemplate, self).getClsTestClient().getApiClient() cleanup_resources(self.apiclient, self._cleanup)", "\"\"\" @classmethod def setUpClass(cls): cls.testClient = super(TestBrowseUploadTemplate, cls).getClsTestClient() cls.testdata =", "SSVM self.assertNotEqual( ssvm_response.name, old_name, \"Check SSVM new name with name", "'Running': break if timeout == 0: raise Exception(\"List SSVM call", "The ASF licenses this file # to you under the", "hosts is None: cls.SkipTest( \"There are no hypervisor's available. Check", "timeout = timeout - 1 ssvm_response = list_ssvm_response[0] # Verify", "permissions and limitations # under the License. # Import Local", "from nose.plugins.attrib import attr from marvin.cloudstackTestCase import cloudstackTestCase import unittest", "time.sleep(self.testdata[\"sleep\"]) timeout = timeout - 1 def destroy_ssvm(self): list_ssvm_response =", "get_domain(cls.apiclient) cls.pod = get_pod(cls.apiclient, cls.zone.id) cls.account = Account.create( cls.apiclient, cls.testdata[\"account\"],", "# Licensed to the Apache Software Foundation (ASF) under one", "SSVM has private IP field\" ) self.assertEqual( hasattr(ssvm_response, 'linklocalip'), True,", "@classmethod def setUpClass(cls): cls.testClient = super(TestBrowseUploadTemplate, cls).getClsTestClient() cls.testdata = cls.testClient.getParsedTestDataConfig()", "import urllib.request, urllib.parse, urllib.error import time import tempfile _multiprocess_shared_ =", "issues in test_browse_templates.py are fixed, this should be merged back", "ssvm_response.id) cmd = destroySystemVm.destroySystemVmCmd() cmd.id = ssvm_response.id self.apiclient.destroySystemVm(cmd) timeout =", "= list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', zoneid=self.zone.id ) self.assertEqual( isinstance(list_ssvm_response, list),", "issue with template sync-up\") except Exception as e: self.fail(\"Exception occurred", "import * from marvin.lib.base import * from marvin.lib.common import *", "cmd.ostypeid=self.templateostypeid template_response=self.apiclient.getUploadParamsForTemplate(cmd) #Destroy SSVM, and wait for new one to", "hosts response\") cls.uploadtemplateformat = \"VHD\" cls.templatename = \"test\" cls.templatehypervisor =", "law or agreed to in writing, # software distributed under", "SSVM: %s\" % ssvm_response.id) cmd = destroySystemVm.destroySystemVmCmd() cmd.id = ssvm_response.id", "\"\"\" Tests for browser based upload template feature. Once all", "Foundation (ASF) under one # or more contributor license agreements.", "from marvin.lib.base import * from marvin.lib.common import * from marvin.codes", "id=template_response.id, templatefilter=\"all\", zoneid=self.zone.id) self.assertEqual(list_template_response, None, \"Template is not cleaned up,", "to be up self.waitForSystemVMAgent(ssvm_response.name) return @attr(tags = [\"advanced\", \"advancedns\", \"smoke\",", "occurred : %s\" % e) return @classmethod def tearDownClass(self): try:", "import * from marvin.lib.common import * from marvin.codes import PASS,", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "True class TestBrowseUploadTemplate(cloudstackTestCase): \"\"\" Tests for browser based upload template", "SSVM agent to be Up\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout -", "Software Foundation (ASF) under one # or more contributor license", "zoneid=self.zone.id, systemvmtype='secondarystoragevm' ) if isinstance(list_ssvm_response, list): if list_ssvm_response[0].state == 'Running':", "field\" ) # Wait for the agent to be up", "followed by SSVM destroy. Template should go to UploadAbandoned state", "# regarding copyright ownership. The ASF licenses this file #", "get_zone(cls.apiclient, cls.testClient.getZoneForTests()) cls.domain = get_domain(cls.apiclient) cls.pod = get_pod(cls.apiclient, cls.zone.id) cls.account", "in compliance # with the License. You may obtain a", "# to you under the Apache License, Version 2.0 (the", "License for the # specific language governing permissions and limitations", "#Verify that the template is cleaned up as part of", "cls.testClient.getZoneForTests()) cls.domain = get_domain(cls.apiclient) cls.pod = get_pod(cls.apiclient, cls.zone.id) cls.account =", "get cleaned up. \"\"\" try: self.debug(\"========================= Test browser based incomplete", "start self.destroy_ssvm() wait_for_cleanup(self.apiclient, [\"expunge.delay\", \"expunge.interval\"]) #Verify that the template is", "OR CONDITIONS OF ANY # KIND, either express or implied.", "ssvm_response.name self.debug(\"Destroying SSVM: %s\" % ssvm_response.id) cmd = destroySystemVm.destroySystemVmCmd() cmd.id", "and limitations # under the License. # Import Local Modules", "def waitForSystemVMAgent(self, vmname): timeout = self.testdata[\"timeout\"] while True: list_host_response =", "= self.testdata[\"timeout\"] while True: list_ssvm_response = list_ssvms( self.apiclient, zoneid=self.zone.id, systemvmtype='secondarystoragevm'", "list_template_response=Template.list( self.apiclient, id=template_response.id, templatefilter=\"all\", zoneid=self.zone.id) self.assertEqual(list_template_response, None, \"Template is not", "timeout = timeout - 1 def destroy_ssvm(self): list_ssvm_response = list_ssvms(", "SSVM has link local IP field\" ) self.assertEqual( hasattr(ssvm_response, 'publicip'),", "random import string import telnetlib import os import urllib.request, urllib.parse,", "* from marvin.lib.base import * from marvin.lib.common import * from", "self.testdata[\"timeout\"] while True: list_ssvm_response = list_ssvms( self.apiclient, zoneid=self.zone.id, systemvmtype='secondarystoragevm' )", "this file # to you under the Apache License, Version", "copyright ownership. The ASF licenses this file # to you", "= ssvm_response.id self.apiclient.destroySystemVm(cmd) timeout = self.testdata[\"timeout\"] while True: list_ssvm_response =", "list_ssvm_response[0] # Verify Name, Public IP, Private IP and Link", "%s\" % ssvm_response.id) cmd = destroySystemVm.destroySystemVmCmd() cmd.id = ssvm_response.id self.apiclient.destroySystemVm(cmd)", "\"smoke\", \"basic\"], required_hardware=\"false\") def test_browser_upload_template_incomplete(self): \"\"\" Test browser based incomplete", "list_ssvm_response[0] old_name = ssvm_response.name self.debug(\"Destroying SSVM: %s\" % ssvm_response.id) cmd", "type=\"Routing\" ) if hosts is None: cls.SkipTest( \"There are no", "in writing, # software distributed under the License is distributed", ") ssvm_response = list_ssvm_response[0] old_name = ssvm_response.name self.debug(\"Destroying SSVM: %s\"", "marvin.cloudstackAPI import * from marvin.lib.utils import * from marvin.lib.base import", "cls.testdata[\"account\"], domainid=cls.domain.id ) cls._cleanup = [ cls.account ] def waitForSystemVMAgent(self,", "[] cls.cleanup = [] hosts = list_hosts( cls.apiclient, type=\"Routing\" )", "new SSVM start list_template_response=Template.list( self.apiclient, id=template_response.id, templatefilter=\"all\", zoneid=self.zone.id) self.assertEqual(list_template_response, None,", "as part of sync-up during new SSVM start list_template_response=Template.list( self.apiclient,", "template is cleaned up as part of sync-up during new", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "'linklocalip'), True, \"Check whether SSVM has link local IP field\"", "= cls.testClient.getHypervisorInfo() cls._cleanup = [] cls.cleanup = [] hosts =", "License is distributed on an # \"AS IS\" BASIS, WITHOUT", "list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', zoneid=self.zone.id ) self.assertEqual( isinstance(list_ssvm_response, list), True,", ") # Wait for the agent to be up self.waitForSystemVMAgent(ssvm_response.name)", "@attr(tags = [\"advanced\", \"advancedns\", \"smoke\", \"basic\"], required_hardware=\"false\") def test_browser_upload_template_incomplete(self): \"\"\"", "Exception(\"Timed out waiting for SSVM agent to be Up\") time.sleep(self.testdata[\"sleep\"])", "= destroySystemVm.destroySystemVmCmd() cmd.id = ssvm_response.id self.apiclient.destroySystemVm(cmd) timeout = self.testdata[\"timeout\"] while", "# \"License\"); you may not use this file except in", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "get_pod(cls.apiclient, cls.zone.id) cls.account = Account.create( cls.apiclient, cls.testdata[\"account\"], domainid=cls.domain.id ) cls._cleanup", "self.apiclient.destroySystemVm(cmd) timeout = self.testdata[\"timeout\"] while True: list_ssvm_response = list_ssvms( self.apiclient,", "timeout = self.testdata[\"timeout\"] while True: list_ssvm_response = list_ssvms( self.apiclient, zoneid=self.zone.id,", "self).getClsTestClient().getApiClient() cleanup_resources(self.apiclient, self._cleanup) except Exception as e: raise Exception(\"Warning: Exception", "to the Apache Software Foundation (ASF) under one # or", "\"License\"); you may not use this file except in compliance", "old_name = ssvm_response.name self.debug(\"Destroying SSVM: %s\" % ssvm_response.id) cmd =", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "sync-up during new SSVM start list_template_response=Template.list( self.apiclient, id=template_response.id, templatefilter=\"all\", zoneid=self.zone.id)", "from marvin.lib.utils import * from marvin.lib.base import * from marvin.lib.common", "cls.pod = get_pod(cls.apiclient, cls.zone.id) cls.account = Account.create( cls.apiclient, cls.testdata[\"account\"], domainid=cls.domain.id", "# distributed with this work for additional information # regarding", "writing, # software distributed under the License is distributed on", "cls.apiclient = cls.testClient.getApiClient() cls.hypervisor = cls.testClient.getHypervisorInfo() cls._cleanup = [] cls.cleanup", "self.zone.id cmd.format = self.uploadtemplateformat cmd.name=self.templatename+self.account.name+(random.choice(string.ascii_uppercase)) cmd.account=self.account.name cmd.domainid=self.domain.id cmd.displaytext=cmd.name cmd.hypervisor=self.templatehypervisor cmd.ostypeid=self.templateostypeid", "True, \"Check whether SSVM has private IP field\" ) self.assertEqual(", "\"Check SSVM new name with name of destroyed SSVM\" )", "def tearDownClass(self): try: self.apiclient = super(TestBrowseUploadTemplate, self).getClsTestClient().getApiClient() cleanup_resources(self.apiclient, self._cleanup) except", "'Up': break if timeout == 0: raise Exception(\"Timed out waiting", "cls._cleanup = [] cls.cleanup = [] hosts = list_hosts( cls.apiclient,", "cleaned up, some issue with template sync-up\") except Exception as", "limitations # under the License. # Import Local Modules import", "= \"test\" cls.templatehypervisor = \"XenServer\" cls.templateostypeid = 142 cls.zone =", "break if timeout == 0: raise Exception(\"List SSVM call failed!\")", "========================\") #Only register template, without uploading cmd = getUploadParamsForTemplate.getUploadParamsForTemplateCmd() cmd.zoneid", "CONDITIONS OF ANY # KIND, either express or implied. See", "has link local IP field\" ) self.assertEqual( hasattr(ssvm_response, 'publicip'), True,", ") if hosts is None: cls.SkipTest( \"There are no hypervisor's", "for new one to start self.destroy_ssvm() wait_for_cleanup(self.apiclient, [\"expunge.delay\", \"expunge.interval\"]) #Verify", "self.assertNotEqual( ssvm_response.name, old_name, \"Check SSVM new name with name of", "for SSVM agent to be Up\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout", "list): if list_ssvm_response[0].state == 'Running': break if timeout == 0:", "requests.packages.urllib3.disable_warnings() import random import string import telnetlib import os import", "for additional information # regarding copyright ownership. The ASF licenses", "if timeout == 0: raise Exception(\"Timed out waiting for SSVM", "sync-up\") except Exception as e: self.fail(\"Exception occurred : %s\" %", "the Apache Software Foundation (ASF) under one # or more", "\"test\" cls.templatehypervisor = \"XenServer\" cls.templateostypeid = 142 cls.zone = get_zone(cls.apiclient,", "= self.zone.id cmd.format = self.uploadtemplateformat cmd.name=self.templatename+self.account.name+(random.choice(string.ascii_uppercase)) cmd.account=self.account.name cmd.domainid=self.domain.id cmd.displaytext=cmd.name cmd.hypervisor=self.templatehypervisor", "# # Unless required by applicable law or agreed to", "= timeout - 1 ssvm_response = list_ssvm_response[0] # Verify Name,", "Version 2.0 (the # \"License\"); you may not use this", "hasattr(ssvm_response, 'publicip'), True, \"Check whether SSVM has public IP field\"", "hasattr(ssvm_response, 'privateip'), True, \"Check whether SSVM has private IP field\"", "from marvin.cloudstackTestCase import cloudstackTestCase import unittest from marvin.cloudstackAPI import *", "one # or more contributor license agreements. See the NOTICE", "the License. # Import Local Modules import marvin from nose.plugins.attrib", "list_hosts( self.apiclient, name=vmname ) if list_host_response and list_host_response[0].state == 'Up':", "def destroy_ssvm(self): list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', zoneid=self.zone.id )", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "import tempfile _multiprocess_shared_ = True class TestBrowseUploadTemplate(cloudstackTestCase): \"\"\" Tests for", "= self.testdata[\"timeout\"] while True: list_host_response = list_hosts( self.apiclient, name=vmname )", "and wait for new one to start self.destroy_ssvm() wait_for_cleanup(self.apiclient, [\"expunge.delay\",", "== 0: raise Exception(\"Timed out waiting for SSVM agent to", "cmd = getUploadParamsForTemplate.getUploadParamsForTemplateCmd() cmd.zoneid = self.zone.id cmd.format = self.uploadtemplateformat cmd.name=self.templatename+self.account.name+(random.choice(string.ascii_uppercase))", "= list_hosts( self.apiclient, name=vmname ) if list_host_response and list_host_response[0].state ==", "except in compliance # with the License. You may obtain", "self.destroy_ssvm() wait_for_cleanup(self.apiclient, [\"expunge.delay\", \"expunge.interval\"]) #Verify that the template is cleaned", "True: list_host_response = list_hosts( self.apiclient, name=vmname ) if list_host_response and", "timeout - 1 def destroy_ssvm(self): list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm',", "cmd.id = ssvm_response.id self.apiclient.destroySystemVm(cmd) timeout = self.testdata[\"timeout\"] while True: list_ssvm_response", "cmd.hypervisor=self.templatehypervisor cmd.ostypeid=self.templateostypeid template_response=self.apiclient.getUploadParamsForTemplate(cmd) #Destroy SSVM, and wait for new one", "NOTICE file # distributed with this work for additional information", "template upload, followed by SSVM destroy. Template should go to", "raise Exception(\"Warning: Exception during cleanup : %s\" % e) return", "if list_ssvm_response[0].state == 'Running': break if timeout == 0: raise", "= get_domain(cls.apiclient) cls.pod = get_pod(cls.apiclient, cls.zone.id) cls.account = Account.create( cls.apiclient,", "up, some issue with template sync-up\") except Exception as e:", "this file except in compliance # with the License. You", "state and get cleaned up. \"\"\" try: self.debug(\"========================= Test browser", "self.assertEqual( isinstance(list_ssvm_response, list), True, \"Check list response returns a valid", "if isinstance(list_ssvm_response, list): if list_ssvm_response[0].state == 'Running': break if timeout", "\"Check whether SSVM has link local IP field\" ) self.assertEqual(", "license agreements. See the NOTICE file # distributed with this", "required by applicable law or agreed to in writing, #", "upload, followed by SSVM destroy. Template should go to UploadAbandoned", "Verify Name, Public IP, Private IP and Link local IP", "list_host_response and list_host_response[0].state == 'Up': break if timeout == 0:", "marvin.sshClient import SshClient import requests requests.packages.urllib3.disable_warnings() import random import string", "import requests requests.packages.urllib3.disable_warnings() import random import string import telnetlib import", "SSVM destroy. Template should go to UploadAbandoned state and get", "is cleaned up as part of sync-up during new SSVM", "isinstance(list_ssvm_response, list), True, \"Check list response returns a valid list\"", "the License for the # specific language governing permissions and", "response\") cls.uploadtemplateformat = \"VHD\" cls.templatename = \"test\" cls.templatehypervisor = \"XenServer\"", "ANY # KIND, either express or implied. See the License", "the License is distributed on an # \"AS IS\" BASIS,", "self.debug(\"========================= Test browser based incomplete template upload ========================\") #Only register", "while True: list_ssvm_response = list_ssvms( self.apiclient, zoneid=self.zone.id, systemvmtype='secondarystoragevm' ) if", "link local IP field\" ) self.assertEqual( hasattr(ssvm_response, 'publicip'), True, \"Check", ") if list_host_response and list_host_response[0].state == 'Up': break if timeout", "= self.uploadtemplateformat cmd.name=self.templatename+self.account.name+(random.choice(string.ascii_uppercase)) cmd.account=self.account.name cmd.domainid=self.domain.id cmd.displaytext=cmd.name cmd.hypervisor=self.templatehypervisor cmd.ostypeid=self.templateostypeid template_response=self.apiclient.getUploadParamsForTemplate(cmd) #Destroy", "whether SSVM has private IP field\" ) self.assertEqual( hasattr(ssvm_response, 'linklocalip'),", "by SSVM destroy. Template should go to UploadAbandoned state and", "wait_for_cleanup(self.apiclient, [\"expunge.delay\", \"expunge.interval\"]) #Verify that the template is cleaned up", "the template is cleaned up as part of sync-up during", "list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', zoneid=self.zone.id ) self.assertEqual( isinstance(list_ssvm_response,", "# under the License. # Import Local Modules import marvin", "uploading cmd = getUploadParamsForTemplate.getUploadParamsForTemplateCmd() cmd.zoneid = self.zone.id cmd.format = self.uploadtemplateformat", "has public IP field\" ) # Wait for the agent", "browser based upload template feature. Once all issues in test_browse_templates.py", "IP and Link local IP # for newly created SSVM", "not use this file except in compliance # with the", "self.apiclient, systemvmtype='secondarystoragevm', state='Running', zoneid=self.zone.id ) self.assertEqual( isinstance(list_ssvm_response, list), True, \"Check", "142 cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests()) cls.domain = get_domain(cls.apiclient) cls.pod =", "cls.templateostypeid = 142 cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests()) cls.domain = get_domain(cls.apiclient)", "def test_browser_upload_template_incomplete(self): \"\"\" Test browser based incomplete template upload, followed", "timeout = self.testdata[\"timeout\"] while True: list_host_response = list_hosts( self.apiclient, name=vmname", "waiting for SSVM agent to be Up\") time.sleep(self.testdata[\"sleep\"]) timeout =", "Unless required by applicable law or agreed to in writing,", "# Import Local Modules import marvin from nose.plugins.attrib import attr", "Modules import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import", "wait for new one to start self.destroy_ssvm() wait_for_cleanup(self.apiclient, [\"expunge.delay\", \"expunge.interval\"])", "timeout - 1 ssvm_response = list_ssvm_response[0] # Verify Name, Public", "(ASF) under one # or more contributor license agreements. See", "go to UploadAbandoned state and get cleaned up. \"\"\" try:", "IP field\" ) self.assertEqual( hasattr(ssvm_response, 'publicip'), True, \"Check whether SSVM", "# or more contributor license agreements. See the NOTICE file", "agreed to in writing, # software distributed under the License", "- 1 def destroy_ssvm(self): list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running',", "to be Up\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout - 1 def", "returns a valid list\" ) ssvm_response = list_ssvm_response[0] old_name =", "TestBrowseUploadTemplate(cloudstackTestCase): \"\"\" Tests for browser based upload template feature. Once", "Up\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout - 1 def destroy_ssvm(self): list_ssvm_response", "= [ cls.account ] def waitForSystemVMAgent(self, vmname): timeout = self.testdata[\"timeout\"]", "response returns a valid list\" ) ssvm_response = list_ssvm_response[0] old_name", "return @attr(tags = [\"advanced\", \"advancedns\", \"smoke\", \"basic\"], required_hardware=\"false\") def test_browser_upload_template_incomplete(self):", "and list_host_response[0].state == 'Up': break if timeout == 0: raise", "- 1 ssvm_response = list_ssvm_response[0] # Verify Name, Public IP,", "start list_template_response=Template.list( self.apiclient, id=template_response.id, templatefilter=\"all\", zoneid=self.zone.id) self.assertEqual(list_template_response, None, \"Template is", "(the # \"License\"); you may not use this file except", "setUpClass(cls): cls.testClient = super(TestBrowseUploadTemplate, cls).getClsTestClient() cls.testdata = cls.testClient.getParsedTestDataConfig() cls.apiclient =", "that the template is cleaned up as part of sync-up", "import cloudstackTestCase import unittest from marvin.cloudstackAPI import * from marvin.lib.utils", "incomplete template upload ========================\") #Only register template, without uploading cmd", "agent to be up self.waitForSystemVMAgent(ssvm_response.name) return @attr(tags = [\"advanced\", \"advancedns\",", ") self.assertEqual( hasattr(ssvm_response, 'privateip'), True, \"Check whether SSVM has private", "= [] cls.cleanup = [] hosts = list_hosts( cls.apiclient, type=\"Routing\"", "zoneid=self.zone.id) self.assertEqual(list_template_response, None, \"Template is not cleaned up, some issue", "cleaned up as part of sync-up during new SSVM start", "ASF licenses this file # to you under the Apache", "list), True, \"Check list response returns a valid list\" )", "destroySystemVm.destroySystemVmCmd() cmd.id = ssvm_response.id self.apiclient.destroySystemVm(cmd) timeout = self.testdata[\"timeout\"] while True:", "up. \"\"\" try: self.debug(\"========================= Test browser based incomplete template upload", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "import PASS, FAILED, SUCCESS, XEN_SERVER from marvin.sshClient import SshClient import", "out waiting for SSVM agent to be Up\") time.sleep(self.testdata[\"sleep\"]) timeout", "= list_ssvm_response[0] old_name = ssvm_response.name self.debug(\"Destroying SSVM: %s\" % ssvm_response.id)", "\"Check whether SSVM has private IP field\" ) self.assertEqual( hasattr(ssvm_response,", "destroy. Template should go to UploadAbandoned state and get cleaned", "cmd.domainid=self.domain.id cmd.displaytext=cmd.name cmd.hypervisor=self.templatehypervisor cmd.ostypeid=self.templateostypeid template_response=self.apiclient.getUploadParamsForTemplate(cmd) #Destroy SSVM, and wait for", "= [\"advanced\", \"advancedns\", \"smoke\", \"basic\"], required_hardware=\"false\") def test_browser_upload_template_incomplete(self): \"\"\" Test", "new one to start self.destroy_ssvm() wait_for_cleanup(self.apiclient, [\"expunge.delay\", \"expunge.interval\"]) #Verify that", "cls.testClient.getParsedTestDataConfig() cls.apiclient = cls.testClient.getApiClient() cls.hypervisor = cls.testClient.getHypervisorInfo() cls._cleanup = []", "% e) return @classmethod def tearDownClass(self): try: self.apiclient = super(TestBrowseUploadTemplate,", "ownership. The ASF licenses this file # to you under", ") cls._cleanup = [ cls.account ] def waitForSystemVMAgent(self, vmname): timeout", "up self.waitForSystemVMAgent(ssvm_response.name) return @attr(tags = [\"advanced\", \"advancedns\", \"smoke\", \"basic\"], required_hardware=\"false\")", "cleaned up. \"\"\" try: self.debug(\"========================= Test browser based incomplete template", "import random import string import telnetlib import os import urllib.request,", "\"VHD\" cls.templatename = \"test\" cls.templatehypervisor = \"XenServer\" cls.templateostypeid = 142", "a valid list\" ) ssvm_response = list_ssvm_response[0] old_name = ssvm_response.name", "of sync-up during new SSVM start list_template_response=Template.list( self.apiclient, id=template_response.id, templatefilter=\"all\",", "whether SSVM has link local IP field\" ) self.assertEqual( hasattr(ssvm_response,", "self.apiclient = super(TestBrowseUploadTemplate, self).getClsTestClient().getApiClient() cleanup_resources(self.apiclient, self._cleanup) except Exception as e:", "Wait for the agent to be up self.waitForSystemVMAgent(ssvm_response.name) return @attr(tags", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "list_ssvm_response[0].state == 'Running': break if timeout == 0: raise Exception(\"List", "some issue with template sync-up\") except Exception as e: self.fail(\"Exception", "with the License. You may obtain a copy of the", "in test_browse_templates.py are fixed, this should be merged back \"\"\"", "cls.apiclient, cls.testdata[\"account\"], domainid=cls.domain.id ) cls._cleanup = [ cls.account ] def", "merged back \"\"\" @classmethod def setUpClass(cls): cls.testClient = super(TestBrowseUploadTemplate, cls).getClsTestClient()", "ssvm_response.name, old_name, \"Check SSVM new name with name of destroyed", "name of destroyed SSVM\" ) self.assertEqual( hasattr(ssvm_response, 'privateip'), True, \"Check", "required_hardware=\"false\") def test_browser_upload_template_incomplete(self): \"\"\" Test browser based incomplete template upload,", "applicable law or agreed to in writing, # software distributed", "not cleaned up, some issue with template sync-up\") except Exception", "list_ssvm_response = list_ssvms( self.apiclient, zoneid=self.zone.id, systemvmtype='secondarystoragevm' ) if isinstance(list_ssvm_response, list):", "Exception as e: raise Exception(\"Warning: Exception during cleanup : %s\"", "no hypervisor's available. Check list hosts response\") cls.uploadtemplateformat = \"VHD\"", "marvin.lib.base import * from marvin.lib.common import * from marvin.codes import", "def setUpClass(cls): cls.testClient = super(TestBrowseUploadTemplate, cls).getClsTestClient() cls.testdata = cls.testClient.getParsedTestDataConfig() cls.apiclient", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "file # to you under the Apache License, Version 2.0", "% ssvm_response.id) cmd = destroySystemVm.destroySystemVmCmd() cmd.id = ssvm_response.id self.apiclient.destroySystemVm(cmd) timeout", "is not cleaned up, some issue with template sync-up\") except", "IP, Private IP and Link local IP # for newly", "# with the License. You may obtain a copy of", "list_hosts( cls.apiclient, type=\"Routing\" ) if hosts is None: cls.SkipTest( \"There", "0: raise Exception(\"List SSVM call failed!\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout", "marvin.lib.common import * from marvin.codes import PASS, FAILED, SUCCESS, XEN_SERVER", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "IP field\" ) # Wait for the agent to be", "language governing permissions and limitations # under the License. #", "attr from marvin.cloudstackTestCase import cloudstackTestCase import unittest from marvin.cloudstackAPI import", "Tests for browser based upload template feature. Once all issues", "software distributed under the License is distributed on an #", "Licensed to the Apache Software Foundation (ASF) under one #", "public IP field\" ) # Wait for the agent to", "one to start self.destroy_ssvm() wait_for_cleanup(self.apiclient, [\"expunge.delay\", \"expunge.interval\"]) #Verify that the", "Account.create( cls.apiclient, cls.testdata[\"account\"], domainid=cls.domain.id ) cls._cleanup = [ cls.account ]", "IP # for newly created SSVM self.assertNotEqual( ssvm_response.name, old_name, \"Check", "under one # or more contributor license agreements. See the", "[ cls.account ] def waitForSystemVMAgent(self, vmname): timeout = self.testdata[\"timeout\"] while", "= cls.testClient.getParsedTestDataConfig() cls.apiclient = cls.testClient.getApiClient() cls.hypervisor = cls.testClient.getHypervisorInfo() cls._cleanup =", "systemvmtype='secondarystoragevm', state='Running', zoneid=self.zone.id ) self.assertEqual( isinstance(list_ssvm_response, list), True, \"Check list", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "hypervisor's available. Check list hosts response\") cls.uploadtemplateformat = \"VHD\" cls.templatename", "and get cleaned up. \"\"\" try: self.debug(\"========================= Test browser based", "# Wait for the agent to be up self.waitForSystemVMAgent(ssvm_response.name) return", "feature. Once all issues in test_browse_templates.py are fixed, this should", "information # regarding copyright ownership. The ASF licenses this file", "import telnetlib import os import urllib.request, urllib.parse, urllib.error import time", "waitForSystemVMAgent(self, vmname): timeout = self.testdata[\"timeout\"] while True: list_host_response = list_hosts(", "the Apache License, Version 2.0 (the # \"License\"); you may", "e: self.fail(\"Exception occurred : %s\" % e) return @classmethod def", "import SshClient import requests requests.packages.urllib3.disable_warnings() import random import string import", ") self.assertEqual( hasattr(ssvm_response, 'publicip'), True, \"Check whether SSVM has public", "timeout == 0: raise Exception(\"List SSVM call failed!\") time.sleep(self.testdata[\"sleep\"]) timeout", "cls).getClsTestClient() cls.testdata = cls.testClient.getParsedTestDataConfig() cls.apiclient = cls.testClient.getApiClient() cls.hypervisor = cls.testClient.getHypervisorInfo()", "with name of destroyed SSVM\" ) self.assertEqual( hasattr(ssvm_response, 'privateip'), True,", "you under the Apache License, Version 2.0 (the # \"License\");", "import unittest from marvin.cloudstackAPI import * from marvin.lib.utils import *", "# KIND, either express or implied. See the License for", "without uploading cmd = getUploadParamsForTemplate.getUploadParamsForTemplateCmd() cmd.zoneid = self.zone.id cmd.format =", "= \"VHD\" cls.templatename = \"test\" cls.templatehypervisor = \"XenServer\" cls.templateostypeid =", "\"XenServer\" cls.templateostypeid = 142 cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests()) cls.domain =", "during new SSVM start list_template_response=Template.list( self.apiclient, id=template_response.id, templatefilter=\"all\", zoneid=self.zone.id) self.assertEqual(list_template_response,", "UploadAbandoned state and get cleaned up. \"\"\" try: self.debug(\"========================= Test", "\"advancedns\", \"smoke\", \"basic\"], required_hardware=\"false\") def test_browser_upload_template_incomplete(self): \"\"\" Test browser based", "agreements. See the NOTICE file # distributed with this work", "available. Check list hosts response\") cls.uploadtemplateformat = \"VHD\" cls.templatename =", "licenses this file # to you under the Apache License,", "SshClient import requests requests.packages.urllib3.disable_warnings() import random import string import telnetlib", "to start self.destroy_ssvm() wait_for_cleanup(self.apiclient, [\"expunge.delay\", \"expunge.interval\"]) #Verify that the template", "telnetlib import os import urllib.request, urllib.parse, urllib.error import time import", "isinstance(list_ssvm_response, list): if list_ssvm_response[0].state == 'Running': break if timeout ==", "by applicable law or agreed to in writing, # software", "\"\"\" Test browser based incomplete template upload, followed by SSVM", "# Unless required by applicable law or agreed to in", "under the License. # Import Local Modules import marvin from", "cls.testdata = cls.testClient.getParsedTestDataConfig() cls.apiclient = cls.testClient.getApiClient() cls.hypervisor = cls.testClient.getHypervisorInfo() cls._cleanup", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "list_ssvms( self.apiclient, zoneid=self.zone.id, systemvmtype='secondarystoragevm' ) if isinstance(list_ssvm_response, list): if list_ssvm_response[0].state", "%s\" % e) return @classmethod def tearDownClass(self): try: self.apiclient =", "time import tempfile _multiprocess_shared_ = True class TestBrowseUploadTemplate(cloudstackTestCase): \"\"\" Tests", "License. You may obtain a copy of the License at", "test_browser_upload_template_incomplete(self): \"\"\" Test browser based incomplete template upload, followed by", "= list_ssvms( self.apiclient, zoneid=self.zone.id, systemvmtype='secondarystoragevm' ) if isinstance(list_ssvm_response, list): if", "You may obtain a copy of the License at #", "= super(TestBrowseUploadTemplate, cls).getClsTestClient() cls.testdata = cls.testClient.getParsedTestDataConfig() cls.apiclient = cls.testClient.getApiClient() cls.hypervisor", "SSVM call failed!\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout - 1 ssvm_response", "# Verify Name, Public IP, Private IP and Link local", "agent to be Up\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout - 1", "list hosts response\") cls.uploadtemplateformat = \"VHD\" cls.templatename = \"test\" cls.templatehypervisor", "call failed!\") time.sleep(self.testdata[\"sleep\"]) timeout = timeout - 1 ssvm_response =", "compliance # with the License. You may obtain a copy", "cmd.account=self.account.name cmd.domainid=self.domain.id cmd.displaytext=cmd.name cmd.hypervisor=self.templatehypervisor cmd.ostypeid=self.templateostypeid template_response=self.apiclient.getUploadParamsForTemplate(cmd) #Destroy SSVM, and wait", "FAILED, SUCCESS, XEN_SERVER from marvin.sshClient import SshClient import requests requests.packages.urllib3.disable_warnings()", "\"\"\" try: self.debug(\"========================= Test browser based incomplete template upload ========================\")", "list response returns a valid list\" ) ssvm_response = list_ssvm_response[0]", "super(TestBrowseUploadTemplate, cls).getClsTestClient() cls.testdata = cls.testClient.getParsedTestDataConfig() cls.apiclient = cls.testClient.getApiClient() cls.hypervisor =", "based incomplete template upload, followed by SSVM destroy. Template should", "ssvm_response = list_ssvm_response[0] # Verify Name, Public IP, Private IP" ]
[ "import ( ATTR_IS_AWAKE, ATTR_IS_BEAMING, ATTR_IS_FAILED, ATTR_IS_FLIRS, ATTR_IS_ROUTING, ATTR_IS_SECURITYV1, ATTR_IS_ZWAVE_PLUS, ATTR_NEIGHBORS,", "status await client.send_json({ID: 6, TYPE: \"ozw/node_status\", NODE_ID: 32}) msg =", "14, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_val, }", "setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) # Send the refresh_node_info", "TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) msg = await client.receive_json() assert len(sent_messages)", "different node message = MQTTMessage( topic=\"OpenZWave/1/node/35/\", payload={\"NodeID\": 35, \"NodeQueryStage\": \"fake_shouldnt_be_received\"},", "topic=\"OpenZWave/1/node/35/\", payload={\"NodeID\": 35, \"NodeQueryStage\": \"fake_shouldnt_be_received\"}, ) message.encode() receive_message(message) # Verify", "== \"Binary Power Switch\" assert result[ATTR_NEIGHBORS] == [1, 33, 36,", "next( option[0] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[0] != current_val", "client.send_json({ID: 11, TYPE: \"ozw/network_statistics\"}) msg = await client.receive_json() result =", "= msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test parameter not", "from unittest.mock import patch from openzwavemqtt.const import ( ATTR_CODE_SLOT, ATTR_LABEL,", "Test OZW Instance not found error await client.send_json( {ID: 16,", "from OZW message = MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"initializing\"},", "async def test_websocket_api(opp, generic_data, opp_ws_client): \"\"\"Test the ozw websocket api.\"\"\"", "command await client.send_json({ID: 9, TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) msg =", "assert result[\"code\"] == ERR_NOT_FOUND async def test_ws_locks(opp, lock_data, opp_ws_client): \"\"\"Test", "setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) with patch(\"openzwavemqtt.OZWOptions.listen\") as mock_listen:", "the ozw refresh node api.\"\"\" receive_message = await setup_ozw(opp, fixture=generic_data)", "result[\"send_count\"] == 57 assert result[\"sent_failed\"] == 0 assert result[\"retries\"] ==", "msg = await client.receive_json() result = msg[\"result\"] assert result[\"Status\"] ==", "we received the message for node 39 but not for", "39, \"NodeQueryStage\": \"initializing\"}, ) message.encode() receive_message(message) # Verify we got", "result[\"code\"] == ERR_NOT_FOUND # Test list value not found await", "from openpeerpower.components.websocket_api.const import ( ERR_INVALID_FORMAT, ERR_NOT_FOUND, ERR_NOT_SUPPORTED, ) from .common", "= await client.receive_json() result = msg[\"result\"] assert result[\"readCnt\"] == 92220", "= next( option[1] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[1] !=", "ID: 2, TYPE: \"ozw/set_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1, ATTR_USERCODE: \"1234\",", "Test invalid bitset format await client.send_json( { ID: 22, TYPE:", "assert result[\"last_request_rtt\"] == 26 assert result[\"last_response_rtt\"] == 38 assert result[\"average_request_rtt\"]", "await client.send_json( { ID: 18, TYPE: \"ozw/set_config_parameter\", NODE_ID: 999, PARAMETER:", "update for a different node message = MQTTMessage( topic=\"OpenZWave/1/node/35/\", payload={\"NodeID\":", "await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) # Test instance", "assert not result[1][ATTR_IS_FAILED] # Test get config parameters await client.send_json({ID:", "on the websocket msg = await client.receive_json() result = msg[\"event\"]", "but not for node 35 msg = await client.receive_json() result", "with patch(\"openzwavemqtt.OZWOptions.listen\") as mock_listen: # Send the refresh_node_info command await", "import ATTR_CONFIG_PARAMETER from openpeerpower.components.ozw.lock import ATTR_USERCODE from openpeerpower.components.ozw.websocket_api import (", ") # Test set config parameter config_param = result[0] current_val", "opp_ws_client): \"\"\"Test the ozw refresh node api.\"\"\" receive_message = await", "await client.receive_json() assert msg[\"success\"] # Test OZW Instance not found", ") msg = await client.receive_json() assert msg[\"success\"] await client.send_json( {", "= await client.receive_json() result = msg[\"error\"] assert result[\"code\"] == ERR_INVALID_FORMAT", "await client.send_json( { ID: 23, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER:", "result[\"type\"] == \"node_updated\" assert result[\"node_query_stage\"] == \"initializing\" # Send another", "parameter config_param = result[0] current_val = config_param[ATTR_VALUE] new_val = next(", "in result: assert config_param[\"type\"] in ( ValueType.LIST.value, ValueType.BOOL.value, ValueType.INT.value, ValueType.BYTE.value,", "client.receive_json() assert msg[\"success\"] await client.send_json( { ID: 2, TYPE: \"ozw/set_usercode\",", "\"ozw/set_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1, ATTR_USERCODE: \"1234\", } ) msg", ") msg = await client.receive_json() assert msg[\"success\"] async def test_refresh_node(opp,", "command await client.send_json({ID: 9, TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) await client.receive_json()", "ATTR_IS_BEAMING, ATTR_IS_FAILED, ATTR_IS_FLIRS, ATTR_IS_ROUTING, ATTR_IS_SECURITYV1, ATTR_IS_ZWAVE_PLUS, ATTR_NEIGHBORS, ATTR_NODE_BASIC_STRING, ATTR_NODE_BAUD_RATE, ATTR_NODE_GENERIC_STRING,", "# Test network status await client.send_json({ID: 5, TYPE: \"ozw/network_status\"}) msg", "13, TYPE: \"ozw/get_config_parameters\", NODE_ID: 39}) msg = await client.receive_json() result", "TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_val, } )", "\"initializing\" # Send another mock status update from OZW message", "# Test node metadata await client.send_json({ID: 9, TYPE: \"ozw/node_metadata\", NODE_ID:", "1, TYPE: \"ozw/get_code_slots\", NODE_ID: 10, } ) msg = await", "assert result[\"received_dup_packets\"] == 12 assert result[\"received_unsolicited\"] == 3546 # Test", "NODE_ID: 39}) msg = await client.receive_json() assert len(sent_messages) == 1", "== 1 assert msg[\"success\"] # Receive a mock status update", "0 assert result[\"retries\"] == 1 assert result[\"last_request_rtt\"] == 26 assert", "TYPE: \"ozw/get_instances\"}) msg = await client.receive_json() assert len(msg[\"result\"]) == 1", "assert result[\"Status\"] == \"driverAllNodesQueried\" assert result[OZW_INSTANCE] == 1 # Test", "update from OZW message = MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\":", "= msg[\"event\"] assert result[\"type\"] == \"node_updated\" assert result[\"node_query_stage\"] == \"versions\"", "opp_ws_client(opp) # Test instance list await client.send_json({ID: 4, TYPE: \"ozw/get_instances\"})", "network status await client.send_json({ID: 5, TYPE: \"ozw/network_status\"}) msg = await", "msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test value type invalid", "invalid bitset format await client.send_json( { ID: 22, TYPE: \"ozw/set_config_parameter\",", "result[OZW_INSTANCE] == 1 assert result[NODE_ID] == 32 assert result[ATTR_NODE_QUERY_STAGE] ==", "fixture=lock_data) client = await opp_ws_client(opp) await client.send_json( { ID: 1,", "result[\"Status\"] == \"driverAllNodesQueried\" assert result[OZW_INSTANCE] == 1 # Test node", "result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test OZW", ") msg = await client.receive_json() result = msg[\"error\"] assert result[\"code\"]", "999, NODE_ID: 1} ) msg = await client.receive_json() result =", "assert result[\"send_count\"] == 57 assert result[\"sent_failed\"] == 0 assert result[\"retries\"]", "# Test invalid bitset format await client.send_json( { ID: 22,", "ID, NODE_ID, OZW_INSTANCE, PARAMETER, SCHEMA, TYPE, VALUE, ) from openpeerpower.components.websocket_api.const", "unittest.mock import patch from openzwavemqtt.const import ( ATTR_CODE_SLOT, ATTR_LABEL, ATTR_OPTIONS,", "assert result[\"readCnt\"] == 92220 assert result[OZW_INSTANCE] == 1 assert result[\"node_count\"]", "await client.receive_json() result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND async", "MQTTMessage( topic=\"OpenZWave/1/node/35/\", payload={\"NodeID\": 35, \"NodeQueryStage\": \"fake_shouldnt_be_received\"}, ) message.encode() receive_message(message) #", "client.send_json({ID: 7, TYPE: \"ozw/node_status\", NODE_ID: 999}) msg = await client.receive_json()", "= MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"versions\"}, ) message.encode() receive_message(message)", "config parameter config_param = result[0] current_val = config_param[ATTR_VALUE] new_val =", "39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_label, } ) msg = await", "Test set config parameter config_param = result[0] current_val = config_param[ATTR_VALUE]", "\"node_updated\" assert result[\"node_query_stage\"] == \"initializing\" # Send another mock status", "assert result[\"code\"] == ERR_NOT_FOUND # Test OZW Node not found", "result[\"code\"] == ERR_NOT_FOUND # Test OZW Node not found error", "ValueType.BOOL.value, ValueType.INT.value, ValueType.BYTE.value, ValueType.SHORT.value, ValueType.BITSET.value, ) # Test set config", "= await opp_ws_client(opp) # Send the refresh_node_info command await client.send_json({ID:", "msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test list value not", "32 assert result[ATTR_NODE_QUERY_STAGE] == \"Complete\" assert result[ATTR_IS_ZWAVE_PLUS] assert result[ATTR_IS_AWAKE] assert", "\"1234\", } ) msg = await client.receive_json() assert msg[\"success\"] await", "error await client.send_json( {ID: 16, TYPE: \"ozw/get_config_parameters\", OZW_INSTANCE: 999, NODE_ID:", "assert msg[\"success\"] # Receive a mock status update from OZW", "await client.receive_json() assert msg[\"success\"] await client.send_json( { ID: 2, TYPE:", "the ozw websocket api.\"\"\" await setup_ozw(opp, fixture=generic_data) client = await", "option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[1] != current_val and option[0] !=", "TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_label, } )", "# Test set config parameter config_param = result[0] current_val =", "== 32 assert result[ATTR_NODE_QUERY_STAGE] == \"Complete\" assert result[ATTR_IS_ZWAVE_PLUS] assert result[ATTR_IS_AWAKE]", "TYPE: \"ozw/node_statistics\", NODE_ID: 39}) msg = await client.receive_json() result =", "\"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_label, } ) msg", ") message.encode() receive_message(message) # Verify we received the message for", "result[\"code\"] == ERR_INVALID_FORMAT # Test valid bitset format passes validation", "33, 36, 37, 39] await client.send_json({ID: 7, TYPE: \"ozw/node_status\", NODE_ID:", "await client.receive_json() assert len(msg[\"result\"]) == 1 result = msg[\"result\"][0] assert", "the websocket msg = await client.receive_json() result = msg[\"event\"] assert", "await client.send_json({ID: 9, TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) await client.receive_json() #", "node 39 but not for node 35 msg = await", "assert config_param[\"type\"] in ( ValueType.LIST.value, ValueType.BOOL.value, ValueType.INT.value, ValueType.BYTE.value, ValueType.SHORT.value, ValueType.BITSET.value,", "topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"initializing\"}, ) message.encode() receive_message(message) # Verify", "== 1 result = msg[\"result\"][0] assert result[OZW_INSTANCE] == 1 assert", "result[ATTR_IS_FLIRS] assert result[ATTR_IS_ROUTING] assert not result[ATTR_IS_SECURITYV1] assert result[ATTR_NODE_BASIC_STRING] == \"Routing", "1 assert result[\"node_count\"] == 5 # Test get nodes await", "NODE_ID: 10, ATTR_CODE_SLOT: 1, } ) msg = await client.receive_json()", "\"ozw/refresh_node_info\", NODE_ID: 39}) msg = await client.receive_json() assert len(sent_messages) ==", "NODE_ID: 32}) msg = await client.receive_json() result = msg[\"result\"] assert", "client.receive_json() result = msg[\"result\"] assert result[OZW_INSTANCE] == 1 assert result[NODE_ID]", "result[\"last_response_rtt\"] == 38 assert result[\"average_request_rtt\"] == 29 assert result[\"average_response_rtt\"] ==", "21, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3, VALUE: 0, }", "get config parameters await client.send_json({ID: 13, TYPE: \"ozw/get_config_parameters\", NODE_ID: 39})", "# Verify we got expected data on the websocket msg", "validation await client.send_json( { ID: 23, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39,", "msg[\"success\"] await client.send_json( { ID: 2, TYPE: \"ozw/set_usercode\", NODE_ID: 10,", "ATTR_NODE_BASIC_STRING, ATTR_NODE_BAUD_RATE, ATTR_NODE_GENERIC_STRING, ATTR_NODE_QUERY_STAGE, ATTR_NODE_SPECIFIC_STRING, ID, NODE_ID, OZW_INSTANCE, PARAMETER, SCHEMA,", "result[ATTR_IS_AWAKE] assert not result[ATTR_IS_FAILED] assert result[ATTR_NODE_BAUD_RATE] == 100000 assert result[ATTR_IS_BEAMING]", "== ERR_INVALID_FORMAT # Test valid bitset format passes validation await", "node api.\"\"\" receive_message = await setup_ozw(opp, fixture=generic_data) client = await", "await client.send_json( { ID: 14, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER:", "client = await opp_ws_client(opp) with patch(\"openzwavemqtt.OZWOptions.listen\") as mock_listen: # Send", "in config_param[SCHEMA][0][ATTR_OPTIONS] if option[1] != current_val and option[0] != new_val", "# Test OZW Node not found error await client.send_json( {", "== ERR_NOT_SUPPORTED # Test invalid bitset format await client.send_json( {", "message.encode() receive_message(message) # Verify we got expected data on the", "config_param[SCHEMA][0][ATTR_OPTIONS] if option[1] != current_val and option[0] != new_val )", "37 assert result[\"received_packets\"] == 3594 assert result[\"received_dup_packets\"] == 12 assert", "mock status update from OZW message = MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\":", "apis.\"\"\" await setup_ozw(opp, fixture=lock_data) client = await opp_ws_client(opp) await client.send_json(", "Receive a mock status update from OZW message = MQTTMessage(", "openpeerpower.components.websocket_api.const import ( ERR_INVALID_FORMAT, ERR_NOT_FOUND, ERR_NOT_SUPPORTED, ) from .common import", "PARAMETER: 3, VALUE: 0, } ) msg = await client.receive_json()", "4, TYPE: \"ozw/get_instances\"}) msg = await client.receive_json() assert len(msg[\"result\"]) ==", "len(sent_messages) == 1 assert msg[\"success\"] # Receive a mock status", "ATTR_CODE_SLOT: 1, ATTR_USERCODE: \"1234\", } ) msg = await client.receive_json()", "ATTR_CONFIG_PARAMETER from openpeerpower.components.ozw.lock import ATTR_USERCODE from openpeerpower.components.ozw.websocket_api import ( ATTR_IS_AWAKE,", "1 # Test node status await client.send_json({ID: 6, TYPE: \"ozw/node_status\",", "def test_refresh_node_unsubscribe(opp, generic_data, opp_ws_client): \"\"\"Test unsubscribing the ozw refresh node", "{ ID: 15, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE:", "client.send_json({ID: 6, TYPE: \"ozw/node_status\", NODE_ID: 32}) msg = await client.receive_json()", "# Test parameter not found await client.send_json( { ID: 19,", "ATTR_NODE_BAUD_RATE, ATTR_NODE_GENERIC_STRING, ATTR_NODE_QUERY_STAGE, ATTR_NODE_SPECIFIC_STRING, ID, NODE_ID, OZW_INSTANCE, PARAMETER, SCHEMA, TYPE,", "config_param[\"type\"] in ( ValueType.LIST.value, ValueType.BOOL.value, ValueType.INT.value, ValueType.BYTE.value, ValueType.SHORT.value, ValueType.BITSET.value, )", "assert result[\"code\"] == ERR_NOT_FOUND # Test network statistics await client.send_json({ID:", "Verify we got expected data on the websocket msg =", "ATTR_POSITION, ATTR_VALUE, ValueType, ) from openpeerpower.components.ozw.const import ATTR_CONFIG_PARAMETER from openpeerpower.components.ozw.lock", "client.send_json({ID: 12, TYPE: \"ozw/get_nodes\"}) msg = await client.receive_json() result =", "ERR_NOT_FOUND # Test list value not found await client.send_json( {", "msg[\"error\"] assert result[\"code\"] == ERR_NOT_SUPPORTED # Test invalid bitset format", "39 but not for node 35 msg = await client.receive_json()", "def test_ws_locks(opp, lock_data, opp_ws_client): \"\"\"Test lock websocket apis.\"\"\" await setup_ozw(opp,", "9, TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) await client.receive_json() # Send the", "msg[\"success\"] await client.send_json( { ID: 15, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39,", "ERR_INVALID_FORMAT # Test valid bitset format passes validation await client.send_json(", "ERR_NOT_FOUND async def test_ws_locks(opp, lock_data, opp_ws_client): \"\"\"Test lock websocket apis.\"\"\"", "def test_refresh_node(opp, generic_data, sent_messages, opp_ws_client): \"\"\"Test the ozw refresh node", "client.receive_json() result = msg[\"result\"] assert len(result) == 5 assert result[2][ATTR_IS_AWAKE]", "VALUE: new_label, } ) msg = await client.receive_json() assert msg[\"success\"]", "== ERR_NOT_FOUND # Test list value not found await client.send_json(", "await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) # Send the", "opp_ws_client(opp) with patch(\"openzwavemqtt.OZWOptions.listen\") as mock_listen: # Send the refresh_node_info command", "11, TYPE: \"ozw/network_statistics\"}) msg = await client.receive_json() result = msg[\"result\"]", "websocket msg = await client.receive_json() result = msg[\"event\"] assert result[\"type\"]", "== 38 assert result[\"average_request_rtt\"] == 29 assert result[\"average_response_rtt\"] == 37", "result[\"node_query_stage\"] == \"versions\" async def test_refresh_node_unsubscribe(opp, generic_data, opp_ws_client): \"\"\"Test unsubscribing", "assert result[2][ATTR_IS_AWAKE] assert not result[1][ATTR_IS_FAILED] # Test get config parameters", "== 1 assert result[\"node_count\"] == 5 # Test get nodes", "assert result[OZW_INSTANCE] == 1 # Test node status await client.send_json({ID:", "= msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test value type", "\"ozw/get_config_parameters\", OZW_INSTANCE: 999, NODE_ID: 1} ) msg = await client.receive_json()", "msg = await client.receive_json() assert msg[\"success\"] async def test_refresh_node(opp, generic_data,", "OZW message = MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"initializing\"}, )", "not result[1][ATTR_IS_FAILED] # Test get config parameters await client.send_json({ID: 13,", "assert not result[ATTR_IS_SECURITYV1] assert result[ATTR_NODE_BASIC_STRING] == \"Routing Slave\" assert result[ATTR_NODE_GENERIC_STRING]", "== ERR_NOT_FOUND # Test value type invalid await client.send_json( {", "TYPE: \"ozw/node_metadata\", NODE_ID: 999}) msg = await client.receive_json() result =", "client.send_json( { ID: 22, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3,", "msg[\"result\"] assert result[\"readCnt\"] == 92220 assert result[OZW_INSTANCE] == 1 assert", "ERR_NOT_SUPPORTED # Test invalid bitset format await client.send_json( { ID:", "await client.send_json({ID: 9, TYPE: \"ozw/node_metadata\", NODE_ID: 39}) msg = await", "result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test list", "= msg[\"result\"] assert result[OZW_INSTANCE] == 1 assert result[NODE_ID] == 39", "assert result[\"sent_failed\"] == 0 assert result[\"retries\"] == 1 assert result[\"last_request_rtt\"]", "assert result[\"retries\"] == 1 assert result[\"last_request_rtt\"] == 26 assert result[\"last_response_rtt\"]", "1 assert result[\"last_request_rtt\"] == 26 assert result[\"last_response_rtt\"] == 38 assert", "\"ozw/network_statistics\"}) msg = await client.receive_json() result = msg[\"result\"] assert result[\"readCnt\"]", "OZW Node not found error await client.send_json( { ID: 18,", "# Test valid bitset format passes validation await client.send_json( {", "\"\"\"Test the ozw refresh node api.\"\"\" receive_message = await setup_ozw(opp,", "0, } ) msg = await client.receive_json() result = msg[\"error\"]", "MQTTMessage, setup_ozw async def test_websocket_api(opp, generic_data, opp_ws_client): \"\"\"Test the ozw", "assert result[ATTR_IS_ZWAVE_PLUS] assert result[ATTR_IS_AWAKE] assert not result[ATTR_IS_FAILED] assert result[ATTR_NODE_BAUD_RATE] ==", "assert result[\"code\"] == ERR_NOT_FOUND # Test list value not found", "value type invalid await client.send_json( { ID: 21, TYPE: \"ozw/set_config_parameter\",", "client.send_json({ID: 10, TYPE: \"ozw/node_metadata\", NODE_ID: 999}) msg = await client.receive_json()", "option[0] != current_val ) new_label = next( option[1] for option", "VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True, ATTR_LABEL: \"test\"}, } ) msg", "{ ID: 18, TYPE: \"ozw/set_config_parameter\", NODE_ID: 999, PARAMETER: 0, VALUE:", "ERR_NOT_FOUND # Test parameter not found await client.send_json( { ID:", "result[OZW_INSTANCE] == 1 assert result[NODE_ID] == 39 assert result[\"send_count\"] ==", "list await client.send_json({ID: 4, TYPE: \"ozw/get_instances\"}) msg = await client.receive_json()", "== \"versions\" async def test_refresh_node_unsubscribe(opp, generic_data, opp_ws_client): \"\"\"Test unsubscribing the", "TYPE: \"ozw/clear_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1, } ) msg =", "payload={\"NodeID\": 35, \"NodeQueryStage\": \"fake_shouldnt_be_received\"}, ) message.encode() receive_message(message) # Verify we", "= msg[\"error\"] assert result[\"code\"] == ERR_NOT_SUPPORTED # Test invalid bitset", "ATTR_VALUE: True}, } ) msg = await client.receive_json() result =", "ERR_NOT_FOUND, ERR_NOT_SUPPORTED, ) from .common import MQTTMessage, setup_ozw async def", "client.send_json({ID: 9, TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) msg = await client.receive_json()", "VALUE: \"test\", } ) msg = await client.receive_json() result =", "ATTR_NODE_QUERY_STAGE, ATTR_NODE_SPECIFIC_STRING, ID, NODE_ID, OZW_INSTANCE, PARAMETER, SCHEMA, TYPE, VALUE, )", "and option[0] != new_val ) await client.send_json( { ID: 14,", "3, VALUE: 0, } ) msg = await client.receive_json() result", "in config_param[SCHEMA][0][ATTR_OPTIONS] if option[0] != current_val ) new_label = next(", "6, TYPE: \"ozw/node_status\", NODE_ID: 32}) msg = await client.receive_json() result", "39, PARAMETER: 10000, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True}, } )", "{ ID: 14, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE:", "ERR_INVALID_FORMAT, ERR_NOT_FOUND, ERR_NOT_SUPPORTED, ) from .common import MQTTMessage, setup_ozw async", "msg[\"result\"] assert result[OZW_INSTANCE] == 1 assert result[NODE_ID] == 39 assert", "await client.receive_json() assert msg[\"success\"] await client.send_json( { ID: 15, TYPE:", "assert not result[ATTR_IS_FLIRS] assert result[ATTR_IS_ROUTING] assert not result[ATTR_IS_SECURITYV1] assert result[ATTR_NODE_BASIC_STRING]", "PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_label, } ) msg = await client.receive_json()", "39, \"NodeQueryStage\": \"versions\"}, ) message.encode() receive_message(message) # Send a mock", "for node 39 but not for node 35 msg =", "set config parameter config_param = result[0] current_val = config_param[ATTR_VALUE] new_val", "await client.send_json( { ID: 20, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER:", "assert result[\"type\"] == \"node_updated\" assert result[\"node_query_stage\"] == \"initializing\" # Send", "refresh_node_info command await client.send_json({ID: 9, TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) await", "== 1 assert result[NODE_ID] == 32 assert result[ATTR_NODE_QUERY_STAGE] == \"Complete\"", "result = msg[\"result\"] assert result[\"readCnt\"] == 92220 assert result[OZW_INSTANCE] ==", "client.send_json( { ID: 3, TYPE: \"ozw/clear_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1,", "1, } ) msg = await client.receive_json() assert msg[\"success\"] async", "VALUE: new_val, } ) msg = await client.receive_json() assert msg[\"success\"]", "result[ATTR_NODE_BAUD_RATE] == 100000 assert result[ATTR_IS_BEAMING] assert not result[ATTR_IS_FLIRS] assert result[ATTR_IS_ROUTING]", "OpenZWave Websocket API.\"\"\" from unittest.mock import patch from openzwavemqtt.const import", "22, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3, VALUE: {ATTR_POSITION: 1,", "payload={\"NodeID\": 39, \"NodeQueryStage\": \"versions\"}, ) message.encode() receive_message(message) # Send a", "assert result[\"average_request_rtt\"] == 29 assert result[\"average_response_rtt\"] == 37 assert result[\"received_packets\"]", "ID: 19, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 45, VALUE: \"test\",", "== 5 # Test get nodes await client.send_json({ID: 12, TYPE:", "TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: \"test\", } )", "# Test value type invalid await client.send_json( { ID: 21,", "35 msg = await client.receive_json() result = msg[\"event\"] assert result[\"type\"]", "assert result[NODE_ID] == 32 assert result[ATTR_NODE_QUERY_STAGE] == \"Complete\" assert result[ATTR_IS_ZWAVE_PLUS]", "result[ATTR_IS_ZWAVE_PLUS] assert result[ATTR_IS_AWAKE] assert not result[ATTR_IS_FAILED] assert result[ATTR_NODE_BAUD_RATE] == 100000", "current_val ) new_label = next( option[1] for option in config_param[SCHEMA][0][ATTR_OPTIONS]", "found await client.send_json( { ID: 19, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39,", "refresh_node_info command await client.send_json({ID: 9, TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) msg", "assert result[\"type\"] == \"node_updated\" assert result[\"node_query_stage\"] == \"versions\" async def", "got expected data on the websocket msg = await client.receive_json()", "result[\"received_dup_packets\"] == 12 assert result[\"received_unsolicited\"] == 3546 # Test node", "!= new_val ) await client.send_json( { ID: 14, TYPE: \"ozw/set_config_parameter\",", "opp_ws_client): \"\"\"Test unsubscribing the ozw refresh node api.\"\"\" await setup_ozw(opp,", "opp_ws_client): \"\"\"Test the ozw websocket api.\"\"\" await setup_ozw(opp, fixture=generic_data) client", "== 26 assert result[\"last_response_rtt\"] == 38 assert result[\"average_request_rtt\"] == 29", "for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[0] != current_val ) new_label", "msg = await client.receive_json() result = msg[\"error\"] assert result[\"code\"] ==", "Switch\" assert result[ATTR_NODE_SPECIFIC_STRING] == \"Binary Power Switch\" assert result[ATTR_NEIGHBORS] ==", "Power Switch\" assert result[ATTR_NEIGHBORS] == [1, 33, 36, 37, 39]", "result[ATTR_NEIGHBORS] == [1, 33, 36, 37, 39] await client.send_json({ID: 7,", "{ ID: 3, TYPE: \"ozw/clear_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1, }", "= msg[\"result\"][0] assert result[OZW_INSTANCE] == 1 assert result[\"Status\"] == \"driverAllNodesQueried\"", "39}) msg = await client.receive_json() result = msg[\"result\"] assert result[\"metadata\"][\"ProductPic\"]", "type invalid await client.send_json( { ID: 21, TYPE: \"ozw/set_config_parameter\", NODE_ID:", "result[\"code\"] == ERR_NOT_FOUND # Test node statistics await client.send_json({ID: 8,", "== 1 assert result[\"last_request_rtt\"] == 26 assert result[\"last_response_rtt\"] == 38", "def test_websocket_api(opp, generic_data, opp_ws_client): \"\"\"Test the ozw websocket api.\"\"\" await", "= await client.receive_json() assert len(msg[\"result\"]) == 1 result = msg[\"result\"][0]", "assert result[ATTR_NODE_BASIC_STRING] == \"Routing Slave\" assert result[ATTR_NODE_GENERIC_STRING] == \"Binary Switch\"", "== \"Routing Slave\" assert result[ATTR_NODE_GENERIC_STRING] == \"Binary Switch\" assert result[ATTR_NODE_SPECIFIC_STRING]", "await setup_ozw(opp, fixture=lock_data) client = await opp_ws_client(opp) await client.send_json( {", "client.send_json( {ID: 16, TYPE: \"ozw/get_config_parameters\", OZW_INSTANCE: 999, NODE_ID: 1} )", "if option[0] != current_val ) new_label = next( option[1] for", "OZW_INSTANCE, PARAMETER, SCHEMA, TYPE, VALUE, ) from openpeerpower.components.websocket_api.const import (", "assert msg[\"success\"] # Test OZW Instance not found error await", "await client.receive_json() result = msg[\"error\"] assert result[\"code\"] == ERR_INVALID_FORMAT #", "assert result[OZW_INSTANCE] == 1 assert result[NODE_ID] == 39 assert result[\"send_count\"]", "websocket apis.\"\"\" await setup_ozw(opp, fixture=lock_data) client = await opp_ws_client(opp) await", "fixture=generic_data) client = await opp_ws_client(opp) # Test instance list await", "msg = await client.receive_json() result = msg[\"result\"] assert result[\"readCnt\"] ==", "5 assert result[2][ATTR_IS_AWAKE] assert not result[1][ATTR_IS_FAILED] # Test get config", "option[1] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[1] != current_val and", "await client.send_json({ID: 6, TYPE: \"ozw/node_status\", NODE_ID: 32}) msg = await", "option[1] != current_val and option[0] != new_val ) await client.send_json(", ") new_label = next( option[1] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if", "57 assert result[\"sent_failed\"] == 0 assert result[\"retries\"] == 1 assert", "mock_listen: # Send the refresh_node_info command await client.send_json({ID: 9, TYPE:", "msg = await client.receive_json() result = msg[\"result\"] assert len(result) ==", "async def test_refresh_node(opp, generic_data, sent_messages, opp_ws_client): \"\"\"Test the ozw refresh", "assert result[OZW_INSTANCE] == 1 assert result[\"Status\"] == \"driverAllNodesQueried\" assert result[\"OpenZWave_Version\"]", "openpeerpower.components.ozw.websocket_api import ( ATTR_IS_AWAKE, ATTR_IS_BEAMING, ATTR_IS_FAILED, ATTR_IS_FLIRS, ATTR_IS_ROUTING, ATTR_IS_SECURITYV1, ATTR_IS_ZWAVE_PLUS,", "not result[ATTR_IS_FLIRS] assert result[ATTR_IS_ROUTING] assert not result[ATTR_IS_SECURITYV1] assert result[ATTR_NODE_BASIC_STRING] ==", "result = msg[\"result\"] assert len(result) == 5 assert result[2][ATTR_IS_AWAKE] assert", "message.encode() receive_message(message) # Send a mock status update for a", "Send another mock status update from OZW message = MQTTMessage(", "await client.send_json( { ID: 22, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER:", "\"driverAllNodesQueried\" assert result[OZW_INSTANCE] == 1 # Test node status await", "19, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 45, VALUE: \"test\", }", "Send the refresh_node_info command await client.send_json({ID: 9, TYPE: \"ozw/refresh_node_info\", NODE_ID:", "39, PARAMETER: 45, VALUE: \"test\", } ) msg = await", "PARAMETER: 10000, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True}, } ) msg", "payload={\"NodeID\": 39, \"NodeQueryStage\": \"initializing\"}, ) message.encode() receive_message(message) # Verify we", "TYPE: \"ozw/set_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1, ATTR_USERCODE: \"1234\", } )", ".common import MQTTMessage, setup_ozw async def test_websocket_api(opp, generic_data, opp_ws_client): \"\"\"Test", "import ATTR_USERCODE from openpeerpower.components.ozw.websocket_api import ( ATTR_IS_AWAKE, ATTR_IS_BEAMING, ATTR_IS_FAILED, ATTR_IS_FLIRS,", "await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) with patch(\"openzwavemqtt.OZWOptions.listen\") as", "client.send_json({ID: 13, TYPE: \"ozw/get_config_parameters\", NODE_ID: 39}) msg = await client.receive_json()", "the ozw refresh node api.\"\"\" await setup_ozw(opp, fixture=generic_data) client =", "client.send_json( { ID: 19, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 45,", "== \"node_updated\" assert result[\"node_query_stage\"] == \"versions\" async def test_refresh_node_unsubscribe(opp, generic_data,", "12 assert result[\"received_unsolicited\"] == 3546 # Test node metadata await", "msg = await client.receive_json() result = msg[\"result\"] assert result[\"metadata\"][\"ProductPic\"] ==", "await opp_ws_client(opp) with patch(\"openzwavemqtt.OZWOptions.listen\") as mock_listen: # Send the refresh_node_info", "msg[\"result\"] assert len(result) == 5 assert result[2][ATTR_IS_AWAKE] assert not result[1][ATTR_IS_FAILED]", "ATTR_NODE_SPECIFIC_STRING, ID, NODE_ID, OZW_INSTANCE, PARAMETER, SCHEMA, TYPE, VALUE, ) from", "= await client.receive_json() assert msg[\"success\"] # Test OZW Instance not", "VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True}, } ) msg = await", "await client.receive_json() assert len(sent_messages) == 1 assert msg[\"success\"] # Receive", "ID: 15, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_label,", "value not found await client.send_json( { ID: 20, TYPE: \"ozw/set_config_parameter\",", "async def test_ws_locks(opp, lock_data, opp_ws_client): \"\"\"Test lock websocket apis.\"\"\" await", ") message.encode() receive_message(message) # Verify we got expected data on", "\"node_updated\" assert result[\"node_query_stage\"] == \"versions\" async def test_refresh_node_unsubscribe(opp, generic_data, opp_ws_client):", "} ) msg = await client.receive_json() assert msg[\"success\"] # Test", "await client.send_json( {ID: 16, TYPE: \"ozw/get_config_parameters\", OZW_INSTANCE: 999, NODE_ID: 1}", "config parameters await client.send_json({ID: 13, TYPE: \"ozw/get_config_parameters\", NODE_ID: 39}) msg", "TYPE: \"ozw/get_code_slots\", NODE_ID: 10, } ) msg = await client.receive_json()", "result[ATTR_IS_ROUTING] assert not result[ATTR_IS_SECURITYV1] assert result[ATTR_NODE_BASIC_STRING] == \"Routing Slave\" assert", "# Test get config parameters await client.send_json({ID: 13, TYPE: \"ozw/get_config_parameters\",", "Instance not found error await client.send_json( {ID: 16, TYPE: \"ozw/get_config_parameters\",", "\"Complete\" assert result[ATTR_IS_ZWAVE_PLUS] assert result[ATTR_IS_AWAKE] assert not result[ATTR_IS_FAILED] assert result[ATTR_NODE_BAUD_RATE]", "result[\"node_query_stage\"] == \"initializing\" # Send another mock status update from", "client.receive_json() assert msg[\"success\"] await client.send_json( { ID: 15, TYPE: \"ozw/set_config_parameter\",", "= msg[\"result\"] assert len(result) == 5 assert result[2][ATTR_IS_AWAKE] assert not", "new_val, } ) msg = await client.receive_json() assert msg[\"success\"] await", "39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: \"test\", } ) msg = await", "assert result[\"metadata\"][\"ProductPic\"] == \"images/aeotec/zwa002.png\" await client.send_json({ID: 10, TYPE: \"ozw/node_metadata\", NODE_ID:", "await client.send_json({ID: 10, TYPE: \"ozw/node_metadata\", NODE_ID: 999}) msg = await", "NODE_ID: 1} ) msg = await client.receive_json() result = msg[\"error\"]", "ID: 22, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3, VALUE: {ATTR_POSITION:", "msg[\"success\"] # Receive a mock status update from OZW message", "next( option[1] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[1] != current_val", "assert result[ATTR_NODE_QUERY_STAGE] == \"Complete\" assert result[ATTR_IS_ZWAVE_PLUS] assert result[ATTR_IS_AWAKE] assert not", "received the message for node 39 but not for node", "await client.send_json( { ID: 2, TYPE: \"ozw/set_usercode\", NODE_ID: 10, ATTR_CODE_SLOT:", "client.send_json( { ID: 21, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3,", "assert result[\"Status\"] == \"driverAllNodesQueried\" assert result[\"OpenZWave_Version\"] == \"1.6.1008\" # Test", "msg[\"result\"][0] assert result[OZW_INSTANCE] == 1 assert result[\"Status\"] == \"driverAllNodesQueried\" assert", "metadata await client.send_json({ID: 9, TYPE: \"ozw/node_metadata\", NODE_ID: 39}) msg =", "10, TYPE: \"ozw/node_metadata\", NODE_ID: 999}) msg = await client.receive_json() result", "MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"versions\"}, ) message.encode() receive_message(message) #", "message = MQTTMessage( topic=\"OpenZWave/1/node/35/\", payload={\"NodeID\": 35, \"NodeQueryStage\": \"fake_shouldnt_be_received\"}, ) message.encode()", "api.\"\"\" await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) # Test", "\"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 10000, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True},", "TYPE: \"ozw/get_config_parameters\", NODE_ID: 39}) msg = await client.receive_json() result =", "len(result) == 8 for config_param in result: assert config_param[\"type\"] in", "= await client.receive_json() result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_SUPPORTED", "\"1.6.1008\" # Test network status await client.send_json({ID: 5, TYPE: \"ozw/network_status\"})", "result[\"code\"] == ERR_NOT_FOUND async def test_ws_locks(opp, lock_data, opp_ws_client): \"\"\"Test lock", "ID: 23, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 10000, VALUE: {ATTR_POSITION:", "PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: \"test\", } ) msg = await client.receive_json()", "SCHEMA, TYPE, VALUE, ) from openpeerpower.components.websocket_api.const import ( ERR_INVALID_FORMAT, ERR_NOT_FOUND,", "api.\"\"\" receive_message = await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp)", "instance list await client.send_json({ID: 4, TYPE: \"ozw/get_instances\"}) msg = await", "node status await client.send_json({ID: 6, TYPE: \"ozw/node_status\", NODE_ID: 32}) msg", "node statistics await client.send_json({ID: 8, TYPE: \"ozw/node_statistics\", NODE_ID: 39}) msg", "client = await opp_ws_client(opp) # Send the refresh_node_info command await", "fixture=generic_data) client = await opp_ws_client(opp) with patch(\"openzwavemqtt.OZWOptions.listen\") as mock_listen: #", "== \"node_updated\" assert result[\"node_query_stage\"] == \"initializing\" # Send another mock", "receive_message(message) # Verify we got expected data on the websocket", "format passes validation await client.send_json( { ID: 23, TYPE: \"ozw/set_config_parameter\",", "result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test parameter", "1 assert msg[\"success\"] # Receive a mock status update from", "\"initializing\"}, ) message.encode() receive_message(message) # Verify we got expected data", "= await client.receive_json() assert msg[\"success\"] await client.send_json( { ID: 2,", "TYPE: \"ozw/network_statistics\"}) msg = await client.receive_json() result = msg[\"result\"] assert", "== 39 assert result[\"send_count\"] == 57 assert result[\"sent_failed\"] == 0", "receive_message(message) # Verify we received the message for node 39", "assert result[\"code\"] == ERR_NOT_FOUND # Test node statistics await client.send_json({ID:", "async def test_refresh_node_unsubscribe(opp, generic_data, opp_ws_client): \"\"\"Test unsubscribing the ozw refresh", "assert msg[\"success\"] await client.send_json( { ID: 3, TYPE: \"ozw/clear_usercode\", NODE_ID:", "assert result[\"code\"] == ERR_NOT_SUPPORTED # Test invalid bitset format await", "msg[\"success\"] async def test_refresh_node(opp, generic_data, sent_messages, opp_ws_client): \"\"\"Test the ozw", "result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test network", "result[ATTR_IS_SECURITYV1] assert result[ATTR_NODE_BASIC_STRING] == \"Routing Slave\" assert result[ATTR_NODE_GENERIC_STRING] == \"Binary", "== ERR_NOT_FOUND # Test node statistics await client.send_json({ID: 8, TYPE:", "client.send_json({ID: 8, TYPE: \"ozw/node_statistics\", NODE_ID: 39}) msg = await client.receive_json()", "refresh node api.\"\"\" await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp)", "client.receive_json() result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test", "we got expected data on the websocket msg = await", "error await client.send_json( { ID: 18, TYPE: \"ozw/set_config_parameter\", NODE_ID: 999,", "lock websocket apis.\"\"\" await setup_ozw(opp, fixture=lock_data) client = await opp_ws_client(opp)", "assert result[ATTR_IS_ROUTING] assert not result[ATTR_IS_SECURITYV1] assert result[ATTR_NODE_BASIC_STRING] == \"Routing Slave\"", "\"ozw/node_status\", NODE_ID: 999}) msg = await client.receive_json() result = msg[\"error\"]", "message = MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"initializing\"}, ) message.encode()", "20, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: \"test\", }", "PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_val, } ) msg = await client.receive_json()", "[1, 33, 36, 37, 39] await client.send_json({ID: 7, TYPE: \"ozw/node_status\",", "26 assert result[\"last_response_rtt\"] == 38 assert result[\"average_request_rtt\"] == 29 assert", "3, TYPE: \"ozw/clear_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1, } ) msg", "setup_ozw(opp, fixture=lock_data) client = await opp_ws_client(opp) await client.send_json( { ID:", "== 100000 assert result[ATTR_IS_BEAMING] assert not result[ATTR_IS_FLIRS] assert result[ATTR_IS_ROUTING] assert", "status await client.send_json({ID: 5, TYPE: \"ozw/network_status\"}) msg = await client.receive_json()", "node 35 msg = await client.receive_json() result = msg[\"event\"] assert", "ID: 20, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: \"test\",", "for config_param in result: assert config_param[\"type\"] in ( ValueType.LIST.value, ValueType.BOOL.value,", "await client.receive_json() result = msg[\"result\"] assert result[OZW_INSTANCE] == 1 assert", "await client.send_json({ID: 8, TYPE: \"ozw/node_statistics\", NODE_ID: 39}) msg = await", "result[\"code\"] == ERR_NOT_FOUND # Test parameter not found await client.send_json(", "websocket api.\"\"\" await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) #", "in ( ValueType.LIST.value, ValueType.BOOL.value, ValueType.INT.value, ValueType.BYTE.value, ValueType.SHORT.value, ValueType.BITSET.value, ) #", "== ERR_NOT_FOUND async def test_ws_locks(opp, lock_data, opp_ws_client): \"\"\"Test lock websocket", "TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) await client.receive_json() # Send the unsubscribe", "result[\"received_unsolicited\"] == 3546 # Test node metadata await client.send_json({ID: 9,", "== 3546 # Test node metadata await client.send_json({ID: 9, TYPE:", "API.\"\"\" from unittest.mock import patch from openzwavemqtt.const import ( ATTR_CODE_SLOT,", "= await client.receive_json() result = msg[\"result\"] assert result[OZW_INSTANCE] == 1", "result[ATTR_NODE_SPECIFIC_STRING] == \"Binary Power Switch\" assert result[ATTR_NEIGHBORS] == [1, 33,", "await client.send_json({ID: 12, TYPE: \"ozw/get_nodes\"}) msg = await client.receive_json() result", "\"NodeQueryStage\": \"fake_shouldnt_be_received\"}, ) message.encode() receive_message(message) # Verify we received the", "39}) msg = await client.receive_json() assert len(sent_messages) == 1 assert", "test_refresh_node(opp, generic_data, sent_messages, opp_ws_client): \"\"\"Test the ozw refresh node api.\"\"\"", "assert not result[ATTR_IS_FAILED] assert result[ATTR_NODE_BAUD_RATE] == 100000 assert result[ATTR_IS_BEAMING] assert", "ATTR_USERCODE: \"1234\", } ) msg = await client.receive_json() assert msg[\"success\"]", "import ( ERR_INVALID_FORMAT, ERR_NOT_FOUND, ERR_NOT_SUPPORTED, ) from .common import MQTTMessage,", "invalid await client.send_json( { ID: 21, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39,", "= await client.receive_json() assert len(sent_messages) == 1 assert msg[\"success\"] #", "statistics await client.send_json({ID: 8, TYPE: \"ozw/node_statistics\", NODE_ID: 39}) msg =", "command await client.send_json({ID: 10, TYPE: \"unsubscribe_events\", \"subscription\": 9}) await client.receive_json()", "Test value type invalid await client.send_json( { ID: 21, TYPE:", "result[\"metadata\"][\"ProductPic\"] == \"images/aeotec/zwa002.png\" await client.send_json({ID: 10, TYPE: \"ozw/node_metadata\", NODE_ID: 999})", "assert result[\"node_query_stage\"] == \"initializing\" # Send another mock status update", "result = msg[\"result\"][0] assert result[OZW_INSTANCE] == 1 assert result[\"Status\"] ==", ") from .common import MQTTMessage, setup_ozw async def test_websocket_api(opp, generic_data,", "config_param = result[0] current_val = config_param[ATTR_VALUE] new_val = next( option[0]", "1} ) msg = await client.receive_json() result = msg[\"error\"] assert", "await client.receive_json() result = msg[\"event\"] assert result[\"type\"] == \"node_updated\" assert", "unsubscribing the ozw refresh node api.\"\"\" await setup_ozw(opp, fixture=generic_data) client", "client.receive_json() result = msg[\"error\"] assert result[\"code\"] == ERR_INVALID_FORMAT # Test", "16, TYPE: \"ozw/get_config_parameters\", OZW_INSTANCE: 999, NODE_ID: 1} ) msg =", "TYPE: \"ozw/get_nodes\"}) msg = await client.receive_json() result = msg[\"result\"] assert", "\"ozw/node_status\", NODE_ID: 32}) msg = await client.receive_json() result = msg[\"result\"]", "{ ID: 19, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 45, VALUE:", "\"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: \"test\", } ) msg", "await client.receive_json() result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_SUPPORTED #", "passes validation await client.send_json( { ID: 23, TYPE: \"ozw/set_config_parameter\", NODE_ID:", "NODE_ID: 39}) await client.receive_json() # Send the unsubscribe command await", "data on the websocket msg = await client.receive_json() result =", "\"\"\"Test unsubscribing the ozw refresh node api.\"\"\" await setup_ozw(opp, fixture=generic_data)", "23, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 10000, VALUE: {ATTR_POSITION: 1,", "( ERR_INVALID_FORMAT, ERR_NOT_FOUND, ERR_NOT_SUPPORTED, ) from .common import MQTTMessage, setup_ozw", "ATTR_LABEL, ATTR_OPTIONS, ATTR_POSITION, ATTR_VALUE, ValueType, ) from openpeerpower.components.ozw.const import ATTR_CONFIG_PARAMETER", "Test instance list await client.send_json({ID: 4, TYPE: \"ozw/get_instances\"}) msg =", "ATTR_NEIGHBORS, ATTR_NODE_BASIC_STRING, ATTR_NODE_BAUD_RATE, ATTR_NODE_GENERIC_STRING, ATTR_NODE_QUERY_STAGE, ATTR_NODE_SPECIFIC_STRING, ID, NODE_ID, OZW_INSTANCE, PARAMETER,", "# Receive a mock status update from OZW message =", "msg = await client.receive_json() assert msg[\"success\"] await client.send_json( { ID:", "TYPE: \"ozw/get_config_parameters\", OZW_INSTANCE: 999, NODE_ID: 1} ) msg = await", "NODE_ID: 39, PARAMETER: 45, VALUE: \"test\", } ) msg =", "ERR_NOT_FOUND # Test node statistics await client.send_json({ID: 8, TYPE: \"ozw/node_statistics\",", "client.receive_json() result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_SUPPORTED # Test", "client.send_json( { ID: 1, TYPE: \"ozw/get_code_slots\", NODE_ID: 10, } )", "client.send_json( { ID: 23, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 10000,", "\"ozw/node_metadata\", NODE_ID: 999}) msg = await client.receive_json() result = msg[\"error\"]", "result[ATTR_IS_FAILED] assert result[ATTR_NODE_BAUD_RATE] == 100000 assert result[ATTR_IS_BEAMING] assert not result[ATTR_IS_FLIRS]", ") from openpeerpower.components.ozw.const import ATTR_CONFIG_PARAMETER from openpeerpower.components.ozw.lock import ATTR_USERCODE from", "msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test parameter not found", "\"NodeQueryStage\": \"initializing\"}, ) message.encode() receive_message(message) # Verify we got expected", "\"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True,", "patch from openzwavemqtt.const import ( ATTR_CODE_SLOT, ATTR_LABEL, ATTR_OPTIONS, ATTR_POSITION, ATTR_VALUE,", "== \"1.6.1008\" # Test network status await client.send_json({ID: 5, TYPE:", "test_refresh_node_unsubscribe(opp, generic_data, opp_ws_client): \"\"\"Test unsubscribing the ozw refresh node api.\"\"\"", "Verify we received the message for node 39 but not", "assert result[ATTR_NODE_BAUD_RATE] == 100000 assert result[ATTR_IS_BEAMING] assert not result[ATTR_IS_FLIRS] assert", "} ) msg = await client.receive_json() assert msg[\"success\"] async def", "ATTR_IS_SECURITYV1, ATTR_IS_ZWAVE_PLUS, ATTR_NEIGHBORS, ATTR_NODE_BASIC_STRING, ATTR_NODE_BAUD_RATE, ATTR_NODE_GENERIC_STRING, ATTR_NODE_QUERY_STAGE, ATTR_NODE_SPECIFIC_STRING, ID, NODE_ID,", "= msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test OZW Node", "await client.receive_json() result = msg[\"result\"] assert len(result) == 5 assert", "ID: 3, TYPE: \"ozw/clear_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1, } )", "== 0 assert result[\"retries\"] == 1 assert result[\"last_request_rtt\"] == 26", "result[\"last_request_rtt\"] == 26 assert result[\"last_response_rtt\"] == 38 assert result[\"average_request_rtt\"] ==", "ATTR_IS_ROUTING, ATTR_IS_SECURITYV1, ATTR_IS_ZWAVE_PLUS, ATTR_NEIGHBORS, ATTR_NODE_BASIC_STRING, ATTR_NODE_BAUD_RATE, ATTR_NODE_GENERIC_STRING, ATTR_NODE_QUERY_STAGE, ATTR_NODE_SPECIFIC_STRING, ID,", "= msg[\"result\"] assert result[\"metadata\"][\"ProductPic\"] == \"images/aeotec/zwa002.png\" await client.send_json({ID: 10, TYPE:", "\"test\", } ) msg = await client.receive_json() result = msg[\"error\"]", "client.send_json({ID: 4, TYPE: \"ozw/get_instances\"}) msg = await client.receive_json() assert len(msg[\"result\"])", "TYPE: \"ozw/set_config_parameter\", NODE_ID: 999, PARAMETER: 0, VALUE: \"test\", } )", "for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[1] != current_val and option[0]", "result[1][ATTR_IS_FAILED] # Test get config parameters await client.send_json({ID: 13, TYPE:", "7, TYPE: \"ozw/node_status\", NODE_ID: 999}) msg = await client.receive_json() result", "ATTR_CODE_SLOT: 1, } ) msg = await client.receive_json() assert msg[\"success\"]", "ozw refresh node api.\"\"\" receive_message = await setup_ozw(opp, fixture=generic_data) client", "NODE_ID: 10, } ) msg = await client.receive_json() assert msg[\"success\"]", "Slave\" assert result[ATTR_NODE_GENERIC_STRING] == \"Binary Switch\" assert result[ATTR_NODE_SPECIFIC_STRING] == \"Binary", "35, \"NodeQueryStage\": \"fake_shouldnt_be_received\"}, ) message.encode() receive_message(message) # Verify we received", "Test node status await client.send_json({ID: 6, TYPE: \"ozw/node_status\", NODE_ID: 32})", "config_param[ATTR_VALUE] new_val = next( option[0] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if", "1 assert result[\"Status\"] == \"driverAllNodesQueried\" assert result[\"OpenZWave_Version\"] == \"1.6.1008\" #", "\"images/aeotec/zwa002.png\" await client.send_json({ID: 10, TYPE: \"ozw/node_metadata\", NODE_ID: 999}) msg =", "# Test instance list await client.send_json({ID: 4, TYPE: \"ozw/get_instances\"}) msg", "ATTR_VALUE, ValueType, ) from openpeerpower.components.ozw.const import ATTR_CONFIG_PARAMETER from openpeerpower.components.ozw.lock import", "ERR_NOT_FOUND # Test network statistics await client.send_json({ID: 11, TYPE: \"ozw/network_statistics\"})", "ValueType.BYTE.value, ValueType.SHORT.value, ValueType.BITSET.value, ) # Test set config parameter config_param", "await client.send_json( { ID: 19, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER:", "ATTR_NODE_GENERIC_STRING, ATTR_NODE_QUERY_STAGE, ATTR_NODE_SPECIFIC_STRING, ID, NODE_ID, OZW_INSTANCE, PARAMETER, SCHEMA, TYPE, VALUE,", "sent_messages, opp_ws_client): \"\"\"Test the ozw refresh node api.\"\"\" receive_message =", "Switch\" assert result[ATTR_NEIGHBORS] == [1, 33, 36, 37, 39] await", "\"versions\"}, ) message.encode() receive_message(message) # Send a mock status update", "result[0] current_val = config_param[ATTR_VALUE] new_val = next( option[0] for option", "39, PARAMETER: 3, VALUE: 0, } ) msg = await", "bitset format await client.send_json( { ID: 22, TYPE: \"ozw/set_config_parameter\", NODE_ID:", "generic_data, sent_messages, opp_ws_client): \"\"\"Test the ozw refresh node api.\"\"\" receive_message", "45, VALUE: \"test\", } ) msg = await client.receive_json() result", "client.receive_json() result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND async def", "ID: 18, TYPE: \"ozw/set_config_parameter\", NODE_ID: 999, PARAMETER: 0, VALUE: \"test\",", "= msg[\"event\"] assert result[\"type\"] == \"node_updated\" assert result[\"node_query_stage\"] == \"initializing\"", "Test node metadata await client.send_json({ID: 9, TYPE: \"ozw/node_metadata\", NODE_ID: 39})", "option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[0] != current_val ) new_label =", "msg[\"result\"] assert result[\"metadata\"][\"ProductPic\"] == \"images/aeotec/zwa002.png\" await client.send_json({ID: 10, TYPE: \"ozw/node_metadata\",", "await client.send_json( { ID: 1, TYPE: \"ozw/get_code_slots\", NODE_ID: 10, }", "result[\"average_request_rtt\"] == 29 assert result[\"average_response_rtt\"] == 37 assert result[\"received_packets\"] ==", "client = await opp_ws_client(opp) await client.send_json( { ID: 1, TYPE:", "= MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"initializing\"}, ) message.encode() receive_message(message)", "len(result) == 5 assert result[2][ATTR_IS_AWAKE] assert not result[1][ATTR_IS_FAILED] # Test", "ATTR_IS_FAILED, ATTR_IS_FLIRS, ATTR_IS_ROUTING, ATTR_IS_SECURITYV1, ATTR_IS_ZWAVE_PLUS, ATTR_NEIGHBORS, ATTR_NODE_BASIC_STRING, ATTR_NODE_BAUD_RATE, ATTR_NODE_GENERIC_STRING, ATTR_NODE_QUERY_STAGE,", "node api.\"\"\" await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) with", "result[OZW_INSTANCE] == 1 assert result[\"node_count\"] == 5 # Test get", "= msg[\"result\"] assert result[OZW_INSTANCE] == 1 assert result[NODE_ID] == 32", "== \"images/aeotec/zwa002.png\" await client.send_json({ID: 10, TYPE: \"ozw/node_metadata\", NODE_ID: 999}) msg", "Test valid bitset format passes validation await client.send_json( { ID:", "TYPE, VALUE, ) from openpeerpower.components.websocket_api.const import ( ERR_INVALID_FORMAT, ERR_NOT_FOUND, ERR_NOT_SUPPORTED,", "msg = await client.receive_json() assert msg[\"success\"] # Test OZW Instance", "VALUE: 0, } ) msg = await client.receive_json() result =", "await client.send_json( { ID: 3, TYPE: \"ozw/clear_usercode\", NODE_ID: 10, ATTR_CODE_SLOT:", "msg = await client.receive_json() assert len(msg[\"result\"]) == 1 result =", "OZW_INSTANCE: 999, NODE_ID: 1} ) msg = await client.receive_json() result", "NODE_ID: 39, PARAMETER: 3, VALUE: 0, } ) msg =", "client.send_json({ID: 9, TYPE: \"ozw/node_metadata\", NODE_ID: 39}) msg = await client.receive_json()", "receive_message(message) # Send a mock status update for a different", "\"ozw/node_metadata\", NODE_ID: 39}) msg = await client.receive_json() result = msg[\"result\"]", "assert result[\"OpenZWave_Version\"] == \"1.6.1008\" # Test network status await client.send_json({ID:", "= await client.receive_json() assert msg[\"success\"] await client.send_json( { ID: 3,", "ATTR_OPTIONS, ATTR_POSITION, ATTR_VALUE, ValueType, ) from openpeerpower.components.ozw.const import ATTR_CONFIG_PARAMETER from", "Test OZW Node not found error await client.send_json( { ID:", "a mock status update from OZW message = MQTTMessage( topic=\"OpenZWave/1/node/39/\",", "8 for config_param in result: assert config_param[\"type\"] in ( ValueType.LIST.value,", "Test node statistics await client.send_json({ID: 8, TYPE: \"ozw/node_statistics\", NODE_ID: 39})", "found error await client.send_json( { ID: 18, TYPE: \"ozw/set_config_parameter\", NODE_ID:", "( ATTR_CODE_SLOT, ATTR_LABEL, ATTR_OPTIONS, ATTR_POSITION, ATTR_VALUE, ValueType, ) from openpeerpower.components.ozw.const", "found await client.send_json( { ID: 20, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39,", "36, 37, 39] await client.send_json({ID: 7, TYPE: \"ozw/node_status\", NODE_ID: 999})", "a mock status update for a different node message =", "client.receive_json() # Send the unsubscribe command await client.send_json({ID: 10, TYPE:", "Test list value not found await client.send_json( { ID: 20,", "the unsubscribe command await client.send_json({ID: 10, TYPE: \"unsubscribe_events\", \"subscription\": 9})", "bitset format passes validation await client.send_json( { ID: 23, TYPE:", "1, ATTR_VALUE: True}, } ) msg = await client.receive_json() result", "current_val and option[0] != new_val ) await client.send_json( { ID:", "18, TYPE: \"ozw/set_config_parameter\", NODE_ID: 999, PARAMETER: 0, VALUE: \"test\", }", "\"Routing Slave\" assert result[ATTR_NODE_GENERIC_STRING] == \"Binary Switch\" assert result[ATTR_NODE_SPECIFIC_STRING] ==", "assert result[ATTR_NODE_GENERIC_STRING] == \"Binary Switch\" assert result[ATTR_NODE_SPECIFIC_STRING] == \"Binary Power", "TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 45, VALUE: \"test\", } )", "openpeerpower.components.ozw.const import ATTR_CONFIG_PARAMETER from openpeerpower.components.ozw.lock import ATTR_USERCODE from openpeerpower.components.ozw.websocket_api import", "assert result[\"code\"] == ERR_NOT_FOUND # Test value type invalid await", "10, } ) msg = await client.receive_json() assert msg[\"success\"] await", "\"NodeQueryStage\": \"versions\"}, ) message.encode() receive_message(message) # Send a mock status", "from .common import MQTTMessage, setup_ozw async def test_websocket_api(opp, generic_data, opp_ws_client):", "32}) msg = await client.receive_json() result = msg[\"result\"] assert result[OZW_INSTANCE]", "result[\"average_response_rtt\"] == 37 assert result[\"received_packets\"] == 3594 assert result[\"received_dup_packets\"] ==", "config_param[SCHEMA][0][ATTR_OPTIONS] if option[0] != current_val ) new_label = next( option[1]", "statistics await client.send_json({ID: 11, TYPE: \"ozw/network_statistics\"}) msg = await client.receive_json()", "lock_data, opp_ws_client): \"\"\"Test lock websocket apis.\"\"\" await setup_ozw(opp, fixture=lock_data) client", "NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: \"test\", } ) msg =", "= await client.receive_json() result = msg[\"event\"] assert result[\"type\"] == \"node_updated\"", "msg[\"event\"] assert result[\"type\"] == \"node_updated\" assert result[\"node_query_stage\"] == \"versions\" async", "\"ozw/node_statistics\", NODE_ID: 39}) msg = await client.receive_json() result = msg[\"result\"]", "current_val = config_param[ATTR_VALUE] new_val = next( option[0] for option in", "client.receive_json() assert msg[\"success\"] await client.send_json( { ID: 3, TYPE: \"ozw/clear_usercode\",", "\"ozw/get_nodes\"}) msg = await client.receive_json() result = msg[\"result\"] assert len(result)", "if option[1] != current_val and option[0] != new_val ) await", "msg[\"result\"] assert result[\"Status\"] == \"driverAllNodesQueried\" assert result[OZW_INSTANCE] == 1 #", "# Test list value not found await client.send_json( { ID:", "msg[\"error\"] assert result[\"code\"] == ERR_INVALID_FORMAT # Test valid bitset format", "network statistics await client.send_json({ID: 11, TYPE: \"ozw/network_statistics\"}) msg = await", "= await client.receive_json() result = msg[\"result\"] assert len(result) == 8", "node message = MQTTMessage( topic=\"OpenZWave/1/node/35/\", payload={\"NodeID\": 35, \"NodeQueryStage\": \"fake_shouldnt_be_received\"}, )", "config_param in result: assert config_param[\"type\"] in ( ValueType.LIST.value, ValueType.BOOL.value, ValueType.INT.value,", "await client.send_json({ID: 13, TYPE: \"ozw/get_config_parameters\", NODE_ID: 39}) msg = await", "ozw websocket api.\"\"\" await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp)", "39}) msg = await client.receive_json() result = msg[\"result\"] assert result[OZW_INSTANCE]", "Test get config parameters await client.send_json({ID: 13, TYPE: \"ozw/get_config_parameters\", NODE_ID:", "{ ID: 2, TYPE: \"ozw/set_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1, ATTR_USERCODE:", "import MQTTMessage, setup_ozw async def test_websocket_api(opp, generic_data, opp_ws_client): \"\"\"Test the", "ATTR_USERCODE from openpeerpower.components.ozw.websocket_api import ( ATTR_IS_AWAKE, ATTR_IS_BEAMING, ATTR_IS_FAILED, ATTR_IS_FLIRS, ATTR_IS_ROUTING,", "ValueType.INT.value, ValueType.BYTE.value, ValueType.SHORT.value, ValueType.BITSET.value, ) # Test set config parameter", "{ATTR_POSITION: 1, ATTR_VALUE: True, ATTR_LABEL: \"test\"}, } ) msg =", "result[OZW_INSTANCE] == 1 assert result[\"Status\"] == \"driverAllNodesQueried\" assert result[\"OpenZWave_Version\"] ==", "\"test\"}, } ) msg = await client.receive_json() result = msg[\"error\"]", "} ) msg = await client.receive_json() result = msg[\"error\"] assert", "( ATTR_IS_AWAKE, ATTR_IS_BEAMING, ATTR_IS_FAILED, ATTR_IS_FLIRS, ATTR_IS_ROUTING, ATTR_IS_SECURITYV1, ATTR_IS_ZWAVE_PLUS, ATTR_NEIGHBORS, ATTR_NODE_BASIC_STRING,", "await opp_ws_client(opp) # Test instance list await client.send_json({ID: 4, TYPE:", "TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3, VALUE: {ATTR_POSITION: 1, ATTR_VALUE:", "await client.receive_json() # Send the unsubscribe command await client.send_json({ID: 10,", "await client.receive_json() result = msg[\"result\"] assert result[\"readCnt\"] == 92220 assert", "100000 assert result[ATTR_IS_BEAMING] assert not result[ATTR_IS_FLIRS] assert result[ATTR_IS_ROUTING] assert not", "result[ATTR_IS_BEAMING] assert not result[ATTR_IS_FLIRS] assert result[ATTR_IS_ROUTING] assert not result[ATTR_IS_SECURITYV1] assert", "list value not found await client.send_json( { ID: 20, TYPE:", "TYPE: \"ozw/node_status\", NODE_ID: 999}) msg = await client.receive_json() result =", "a different node message = MQTTMessage( topic=\"OpenZWave/1/node/35/\", payload={\"NodeID\": 35, \"NodeQueryStage\":", "not found await client.send_json( { ID: 20, TYPE: \"ozw/set_config_parameter\", NODE_ID:", "await client.send_json({ID: 9, TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) msg = await", "MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"initializing\"}, ) message.encode() receive_message(message) #", "assert msg[\"success\"] await client.send_json( { ID: 15, TYPE: \"ozw/set_config_parameter\", NODE_ID:", "= config_param[ATTR_VALUE] new_val = next( option[0] for option in config_param[SCHEMA][0][ATTR_OPTIONS]", "not found error await client.send_json( {ID: 16, TYPE: \"ozw/get_config_parameters\", OZW_INSTANCE:", "ERR_NOT_FOUND # Test value type invalid await client.send_json( { ID:", "from openpeerpower.components.ozw.const import ATTR_CONFIG_PARAMETER from openpeerpower.components.ozw.lock import ATTR_USERCODE from openpeerpower.components.ozw.websocket_api", "PARAMETER: 3, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True, ATTR_LABEL: \"test\"}, }", "10, ATTR_CODE_SLOT: 1, } ) msg = await client.receive_json() assert", "not result[ATTR_IS_FAILED] assert result[ATTR_NODE_BAUD_RATE] == 100000 assert result[ATTR_IS_BEAMING] assert not", "assert result[ATTR_NEIGHBORS] == [1, 33, 36, 37, 39] await client.send_json({ID:", "result[2][ATTR_IS_AWAKE] assert not result[1][ATTR_IS_FAILED] # Test get config parameters await", "config_param[ATTR_CONFIG_PARAMETER], VALUE: new_val, } ) msg = await client.receive_json() assert", "PARAMETER: 0, VALUE: \"test\", } ) msg = await client.receive_json()", "\"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 45, VALUE: \"test\", } ) msg", "client.receive_json() result = msg[\"result\"] assert len(result) == 8 for config_param", "assert result[\"average_response_rtt\"] == 37 assert result[\"received_packets\"] == 3594 assert result[\"received_dup_packets\"]", "assert len(sent_messages) == 1 assert msg[\"success\"] # Receive a mock", "3594 assert result[\"received_dup_packets\"] == 12 assert result[\"received_unsolicited\"] == 3546 #", "TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3, VALUE: 0, } )", "ID: 1, TYPE: \"ozw/get_code_slots\", NODE_ID: 10, } ) msg =", "client.send_json( { ID: 2, TYPE: \"ozw/set_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1,", "msg[\"success\"] # Test OZW Instance not found error await client.send_json(", "38 assert result[\"average_request_rtt\"] == 29 assert result[\"average_response_rtt\"] == 37 assert", "result: assert config_param[\"type\"] in ( ValueType.LIST.value, ValueType.BOOL.value, ValueType.INT.value, ValueType.BYTE.value, ValueType.SHORT.value,", "ATTR_IS_FLIRS, ATTR_IS_ROUTING, ATTR_IS_SECURITYV1, ATTR_IS_ZWAVE_PLUS, ATTR_NEIGHBORS, ATTR_NODE_BASIC_STRING, ATTR_NODE_BAUD_RATE, ATTR_NODE_GENERIC_STRING, ATTR_NODE_QUERY_STAGE, ATTR_NODE_SPECIFIC_STRING,", "ATTR_LABEL: \"test\"}, } ) msg = await client.receive_json() result =", "Node not found error await client.send_json( { ID: 18, TYPE:", "{ ID: 1, TYPE: \"ozw/get_code_slots\", NODE_ID: 10, } ) msg", "message.encode() receive_message(message) # Verify we received the message for node", "= await client.receive_json() result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND", "== 1 assert result[\"Status\"] == \"driverAllNodesQueried\" assert result[\"OpenZWave_Version\"] == \"1.6.1008\"", "# Test network statistics await client.send_json({ID: 11, TYPE: \"ozw/network_statistics\"}) msg", "valid bitset format passes validation await client.send_json( { ID: 23,", "{ATTR_POSITION: 1, ATTR_VALUE: True}, } ) msg = await client.receive_json()", "assert msg[\"success\"] await client.send_json( { ID: 2, TYPE: \"ozw/set_usercode\", NODE_ID:", "ValueType.LIST.value, ValueType.BOOL.value, ValueType.INT.value, ValueType.BYTE.value, ValueType.SHORT.value, ValueType.BITSET.value, ) # Test set", "result[\"code\"] == ERR_NOT_FOUND # Test network statistics await client.send_json({ID: 11,", "== 57 assert result[\"sent_failed\"] == 0 assert result[\"retries\"] == 1", "await client.receive_json() result = msg[\"result\"] assert result[\"Status\"] == \"driverAllNodesQueried\" assert", "refresh node api.\"\"\" receive_message = await setup_ozw(opp, fixture=generic_data) client =", "= msg[\"error\"] assert result[\"code\"] == ERR_INVALID_FORMAT # Test valid bitset", "= await client.receive_json() assert msg[\"success\"] async def test_refresh_node(opp, generic_data, sent_messages,", "import patch from openzwavemqtt.const import ( ATTR_CODE_SLOT, ATTR_LABEL, ATTR_OPTIONS, ATTR_POSITION,", "9, TYPE: \"ozw/node_metadata\", NODE_ID: 39}) msg = await client.receive_json() result", "new_label = next( option[1] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[1]", "NODE_ID: 999, PARAMETER: 0, VALUE: \"test\", } ) msg =", "NODE_ID: 39, PARAMETER: 3, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True, ATTR_LABEL:", "from openpeerpower.components.ozw.websocket_api import ( ATTR_IS_AWAKE, ATTR_IS_BEAMING, ATTR_IS_FAILED, ATTR_IS_FLIRS, ATTR_IS_ROUTING, ATTR_IS_SECURITYV1,", "assert len(msg[\"result\"]) == 1 result = msg[\"result\"][0] assert result[OZW_INSTANCE] ==", "result[\"received_packets\"] == 3594 assert result[\"received_dup_packets\"] == 12 assert result[\"received_unsolicited\"] ==", "result[\"node_count\"] == 5 # Test get nodes await client.send_json({ID: 12,", ") await client.send_json( { ID: 14, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39,", "# Verify we received the message for node 39 but", "status update from OZW message = MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39,", "assert result[OZW_INSTANCE] == 1 assert result[NODE_ID] == 32 assert result[ATTR_NODE_QUERY_STAGE]", "92220 assert result[OZW_INSTANCE] == 1 assert result[\"node_count\"] == 5 #", "client.receive_json() result = msg[\"result\"] assert result[\"Status\"] == \"driverAllNodesQueried\" assert result[OZW_INSTANCE]", ") message.encode() receive_message(message) # Send a mock status update for", "message for node 39 but not for node 35 msg", "= await client.receive_json() result = msg[\"result\"] assert len(result) == 5", "result[NODE_ID] == 32 assert result[ATTR_NODE_QUERY_STAGE] == \"Complete\" assert result[ATTR_IS_ZWAVE_PLUS] assert", "result[\"OpenZWave_Version\"] == \"1.6.1008\" # Test network status await client.send_json({ID: 5,", "result = msg[\"event\"] assert result[\"type\"] == \"node_updated\" assert result[\"node_query_stage\"] ==", "result = msg[\"error\"] assert result[\"code\"] == ERR_INVALID_FORMAT # Test valid", "await client.receive_json() result = msg[\"result\"] assert len(result) == 8 for", "parameters await client.send_json({ID: 13, TYPE: \"ozw/get_config_parameters\", NODE_ID: 39}) msg =", "== [1, 33, 36, 37, 39] await client.send_json({ID: 7, TYPE:", "await client.receive_json() result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND #", "( ValueType.LIST.value, ValueType.BOOL.value, ValueType.INT.value, ValueType.BYTE.value, ValueType.SHORT.value, ValueType.BITSET.value, ) # Test", "OZW Instance not found error await client.send_json( {ID: 16, TYPE:", "{ ID: 20, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE:", "result[\"retries\"] == 1 assert result[\"last_request_rtt\"] == 26 assert result[\"last_response_rtt\"] ==", "another mock status update from OZW message = MQTTMessage( topic=\"OpenZWave/1/node/39/\",", "assert result[ATTR_NODE_SPECIFIC_STRING] == \"Binary Power Switch\" assert result[ATTR_NEIGHBORS] == [1,", "client.send_json( { ID: 14, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER],", "assert result[\"code\"] == ERR_INVALID_FORMAT # Test valid bitset format passes", "node metadata await client.send_json({ID: 9, TYPE: \"ozw/node_metadata\", NODE_ID: 39}) msg", "topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"versions\"}, ) message.encode() receive_message(message) # Send", "result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test node", "\"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3, VALUE: 0, } ) msg", "== 1 assert result[NODE_ID] == 39 assert result[\"send_count\"] == 57", "generic_data, opp_ws_client): \"\"\"Test the ozw websocket api.\"\"\" await setup_ozw(opp, fixture=generic_data)", "result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_SUPPORTED # Test invalid", "True}, } ) msg = await client.receive_json() result = msg[\"error\"]", "config_param[ATTR_CONFIG_PARAMETER], VALUE: \"test\", } ) msg = await client.receive_json() result", "receive_message = await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) #", "client.receive_json() result = msg[\"result\"] assert result[\"metadata\"][\"ProductPic\"] == \"images/aeotec/zwa002.png\" await client.send_json({ID:", "client.send_json({ID: 5, TYPE: \"ozw/network_status\"}) msg = await client.receive_json() result =", "\"ozw/get_instances\"}) msg = await client.receive_json() assert len(msg[\"result\"]) == 1 result", "NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_label, } ) msg =", "39}) msg = await client.receive_json() result = msg[\"result\"] assert len(result)", "result[ATTR_NODE_GENERIC_STRING] == \"Binary Switch\" assert result[ATTR_NODE_SPECIFIC_STRING] == \"Binary Power Switch\"", "\"Binary Power Switch\" assert result[ATTR_NEIGHBORS] == [1, 33, 36, 37,", "option[0] != new_val ) await client.send_json( { ID: 14, TYPE:", "8, TYPE: \"ozw/node_statistics\", NODE_ID: 39}) msg = await client.receive_json() result", "await client.send_json( { ID: 15, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER:", "config_param[ATTR_CONFIG_PARAMETER], VALUE: new_label, } ) msg = await client.receive_json() assert", "{ ID: 22, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3, VALUE:", "test_websocket_api(opp, generic_data, opp_ws_client): \"\"\"Test the ozw websocket api.\"\"\" await setup_ozw(opp,", "39] await client.send_json({ID: 7, TYPE: \"ozw/node_status\", NODE_ID: 999}) msg =", "status update for a different node message = MQTTMessage( topic=\"OpenZWave/1/node/35/\",", "== 29 assert result[\"average_response_rtt\"] == 37 assert result[\"received_packets\"] == 3594", "39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_val, } ) msg = await", "generic_data, opp_ws_client): \"\"\"Test unsubscribing the ozw refresh node api.\"\"\" await", "new_val = next( option[0] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[0]", "msg[\"result\"] assert len(result) == 8 for config_param in result: assert", "\"\"\"Test lock websocket apis.\"\"\" await setup_ozw(opp, fixture=lock_data) client = await", "setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) # Test instance list", "== ERR_NOT_FOUND # Test parameter not found await client.send_json( {", "not for node 35 msg = await client.receive_json() result =", "TYPE: \"ozw/network_status\"}) msg = await client.receive_json() result = msg[\"result\"] assert", "new_label, } ) msg = await client.receive_json() assert msg[\"success\"] #", "parameter not found await client.send_json( { ID: 19, TYPE: \"ozw/set_config_parameter\",", "== 8 for config_param in result: assert config_param[\"type\"] in (", "as mock_listen: # Send the refresh_node_info command await client.send_json({ID: 9,", "ID: 14, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_val,", "TYPE: \"ozw/node_status\", NODE_ID: 32}) msg = await client.receive_json() result =", "assert result[NODE_ID] == 39 assert result[\"send_count\"] == 57 assert result[\"sent_failed\"]", "} ) msg = await client.receive_json() assert msg[\"success\"] await client.send_json(", "\"\"\"Test OpenZWave Websocket API.\"\"\" from unittest.mock import patch from openzwavemqtt.const", "test_ws_locks(opp, lock_data, opp_ws_client): \"\"\"Test lock websocket apis.\"\"\" await setup_ozw(opp, fixture=lock_data)", "assert msg[\"success\"] async def test_refresh_node(opp, generic_data, sent_messages, opp_ws_client): \"\"\"Test the", "= await opp_ws_client(opp) await client.send_json( { ID: 1, TYPE: \"ozw/get_code_slots\",", "= msg[\"result\"] assert result[\"readCnt\"] == 92220 assert result[OZW_INSTANCE] == 1", "msg = await client.receive_json() assert len(sent_messages) == 1 assert msg[\"success\"]", "the message for node 39 but not for node 35", "ERR_NOT_SUPPORTED, ) from .common import MQTTMessage, setup_ozw async def test_websocket_api(opp,", "client.receive_json() result = msg[\"result\"] assert result[\"readCnt\"] == 92220 assert result[OZW_INSTANCE]", "{ ID: 23, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 10000, VALUE:", "{ID: 16, TYPE: \"ozw/get_config_parameters\", OZW_INSTANCE: 999, NODE_ID: 1} ) msg", "await client.send_json( { ID: 21, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER:", "opp_ws_client): \"\"\"Test lock websocket apis.\"\"\" await setup_ozw(opp, fixture=lock_data) client =", "== 3594 assert result[\"received_dup_packets\"] == 12 assert result[\"received_unsolicited\"] == 3546", "await client.receive_json() assert msg[\"success\"] async def test_refresh_node(opp, generic_data, sent_messages, opp_ws_client):", "client.receive_json() result = msg[\"event\"] assert result[\"type\"] == \"node_updated\" assert result[\"node_query_stage\"]", "0, VALUE: \"test\", } ) msg = await client.receive_json() result", "msg[\"success\"] await client.send_json( { ID: 3, TYPE: \"ozw/clear_usercode\", NODE_ID: 10,", "result[ATTR_NODE_QUERY_STAGE] == \"Complete\" assert result[ATTR_IS_ZWAVE_PLUS] assert result[ATTR_IS_AWAKE] assert not result[ATTR_IS_FAILED]", "ValueType.SHORT.value, ValueType.BITSET.value, ) # Test set config parameter config_param =", "opp_ws_client(opp) await client.send_json( { ID: 1, TYPE: \"ozw/get_code_slots\", NODE_ID: 10,", "client.send_json({ID: 9, TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) await client.receive_json() # Send", "NODE_ID, OZW_INSTANCE, PARAMETER, SCHEMA, TYPE, VALUE, ) from openpeerpower.components.websocket_api.const import", "1 assert result[NODE_ID] == 32 assert result[ATTR_NODE_QUERY_STAGE] == \"Complete\" assert", "get nodes await client.send_json({ID: 12, TYPE: \"ozw/get_nodes\"}) msg = await", "999, PARAMETER: 0, VALUE: \"test\", } ) msg = await", "{ ID: 21, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3, VALUE:", "assert result[ATTR_IS_BEAMING] assert not result[ATTR_IS_FLIRS] assert result[ATTR_IS_ROUTING] assert not result[ATTR_IS_SECURITYV1]", "result = msg[\"result\"] assert result[OZW_INSTANCE] == 1 assert result[NODE_ID] ==", "openzwavemqtt.const import ( ATTR_CODE_SLOT, ATTR_LABEL, ATTR_OPTIONS, ATTR_POSITION, ATTR_VALUE, ValueType, )", "\"\"\"Test the ozw websocket api.\"\"\" await setup_ozw(opp, fixture=generic_data) client =", "= await client.receive_json() result = msg[\"result\"] assert result[\"Status\"] == \"driverAllNodesQueried\"", "== \"initializing\" # Send another mock status update from OZW", "= await opp_ws_client(opp) with patch(\"openzwavemqtt.OZWOptions.listen\") as mock_listen: # Send the", "ATTR_IS_AWAKE, ATTR_IS_BEAMING, ATTR_IS_FAILED, ATTR_IS_FLIRS, ATTR_IS_ROUTING, ATTR_IS_SECURITYV1, ATTR_IS_ZWAVE_PLUS, ATTR_NEIGHBORS, ATTR_NODE_BASIC_STRING, ATTR_NODE_BAUD_RATE,", "== 12 assert result[\"received_unsolicited\"] == 3546 # Test node metadata", "await client.send_json({ID: 11, TYPE: \"ozw/network_statistics\"}) msg = await client.receive_json() result", "\"ozw/set_config_parameter\", NODE_ID: 999, PARAMETER: 0, VALUE: \"test\", } ) msg", "ValueType, ) from openpeerpower.components.ozw.const import ATTR_CONFIG_PARAMETER from openpeerpower.components.ozw.lock import ATTR_USERCODE", "format await client.send_json( { ID: 22, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39,", "msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test network statistics await", "\"driverAllNodesQueried\" assert result[\"OpenZWave_Version\"] == \"1.6.1008\" # Test network status await", "client.receive_json() assert msg[\"success\"] async def test_refresh_node(opp, generic_data, sent_messages, opp_ws_client): \"\"\"Test", "NODE_ID: 10, ATTR_CODE_SLOT: 1, ATTR_USERCODE: \"1234\", } ) msg =", ") from openpeerpower.components.websocket_api.const import ( ERR_INVALID_FORMAT, ERR_NOT_FOUND, ERR_NOT_SUPPORTED, ) from", "result[\"Status\"] == \"driverAllNodesQueried\" assert result[\"OpenZWave_Version\"] == \"1.6.1008\" # Test network", "PARAMETER, SCHEMA, TYPE, VALUE, ) from openpeerpower.components.websocket_api.const import ( ERR_INVALID_FORMAT,", "39 assert result[\"send_count\"] == 57 assert result[\"sent_failed\"] == 0 assert", "VALUE, ) from openpeerpower.components.websocket_api.const import ( ERR_INVALID_FORMAT, ERR_NOT_FOUND, ERR_NOT_SUPPORTED, )", "Test parameter not found await client.send_json( { ID: 19, TYPE:", "OZW message = MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"versions\"}, )", "= msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test list value", "= msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test network statistics", "# Send the unsubscribe command await client.send_json({ID: 10, TYPE: \"unsubscribe_events\",", "await client.send_json({ID: 10, TYPE: \"unsubscribe_events\", \"subscription\": 9}) await client.receive_json() assert", "Test network status await client.send_json({ID: 5, TYPE: \"ozw/network_status\"}) msg =", "10, ATTR_CODE_SLOT: 1, ATTR_USERCODE: \"1234\", } ) msg = await", "assert result[\"node_query_stage\"] == \"versions\" async def test_refresh_node_unsubscribe(opp, generic_data, opp_ws_client): \"\"\"Test", "# Send another mock status update from OZW message =", "assert result[\"received_unsolicited\"] == 3546 # Test node metadata await client.send_json({ID:", "for a different node message = MQTTMessage( topic=\"OpenZWave/1/node/35/\", payload={\"NodeID\": 35,", "assert result[\"last_response_rtt\"] == 38 assert result[\"average_request_rtt\"] == 29 assert result[\"average_response_rtt\"]", "client = await opp_ws_client(opp) # Test instance list await client.send_json({ID:", "await client.receive_json() assert msg[\"success\"] await client.send_json( { ID: 3, TYPE:", "== 37 assert result[\"received_packets\"] == 3594 assert result[\"received_dup_packets\"] == 12", "nodes await client.send_json({ID: 12, TYPE: \"ozw/get_nodes\"}) msg = await client.receive_json()", "== \"Binary Switch\" assert result[ATTR_NODE_SPECIFIC_STRING] == \"Binary Power Switch\" assert", "not found await client.send_json( { ID: 19, TYPE: \"ozw/set_config_parameter\", NODE_ID:", "NODE_ID: 39, PARAMETER: 10000, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True}, }", "assert result[\"received_packets\"] == 3594 assert result[\"received_dup_packets\"] == 12 assert result[\"received_unsolicited\"]", "for node 35 msg = await client.receive_json() result = msg[\"event\"]", "assert len(result) == 8 for config_param in result: assert config_param[\"type\"]", "1 result = msg[\"result\"][0] assert result[OZW_INSTANCE] == 1 assert result[\"Status\"]", "\"ozw/get_config_parameters\", NODE_ID: 39}) msg = await client.receive_json() result = msg[\"result\"]", ") msg = await client.receive_json() assert msg[\"success\"] # Test OZW", "expected data on the websocket msg = await client.receive_json() result", "2, TYPE: \"ozw/set_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1, ATTR_USERCODE: \"1234\", }", "result[\"type\"] == \"node_updated\" assert result[\"node_query_stage\"] == \"versions\" async def test_refresh_node_unsubscribe(opp,", "patch(\"openzwavemqtt.OZWOptions.listen\") as mock_listen: # Send the refresh_node_info command await client.send_json({ID:", "not result[ATTR_IS_SECURITYV1] assert result[ATTR_NODE_BASIC_STRING] == \"Routing Slave\" assert result[ATTR_NODE_GENERIC_STRING] ==", "result = msg[\"result\"] assert result[\"metadata\"][\"ProductPic\"] == \"images/aeotec/zwa002.png\" await client.send_json({ID: 10,", "# Send a mock status update for a different node", "= next( option[0] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[0] !=", "client.send_json( { ID: 20, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER],", "\"ozw/refresh_node_info\", NODE_ID: 39}) await client.receive_json() # Send the unsubscribe command", "result = msg[\"result\"] assert result[\"Status\"] == \"driverAllNodesQueried\" assert result[OZW_INSTANCE] ==", "999}) msg = await client.receive_json() result = msg[\"error\"] assert result[\"code\"]", "= result[0] current_val = config_param[ATTR_VALUE] new_val = next( option[0] for", "# Test OZW Instance not found error await client.send_json( {ID:", "await client.send_json({ID: 4, TYPE: \"ozw/get_instances\"}) msg = await client.receive_json() assert", "unsubscribe command await client.send_json({ID: 10, TYPE: \"unsubscribe_events\", \"subscription\": 9}) await", "ValueType.BITSET.value, ) # Test set config parameter config_param = result[0]", "\"Binary Switch\" assert result[ATTR_NODE_SPECIFIC_STRING] == \"Binary Power Switch\" assert result[ATTR_NEIGHBORS]", "Websocket API.\"\"\" from unittest.mock import patch from openzwavemqtt.const import (", "== 1 # Test node status await client.send_json({ID: 6, TYPE:", "== \"Complete\" assert result[ATTR_IS_ZWAVE_PLUS] assert result[ATTR_IS_AWAKE] assert not result[ATTR_IS_FAILED] assert", "== 5 assert result[2][ATTR_IS_AWAKE] assert not result[1][ATTR_IS_FAILED] # Test get", "result[\"code\"] == ERR_NOT_FOUND # Test value type invalid await client.send_json(", "await client.send_json({ID: 7, TYPE: \"ozw/node_status\", NODE_ID: 999}) msg = await", "Send the unsubscribe command await client.send_json({ID: 10, TYPE: \"unsubscribe_events\", \"subscription\":", "9, TYPE: \"ozw/refresh_node_info\", NODE_ID: 39}) msg = await client.receive_json() assert", "!= current_val and option[0] != new_val ) await client.send_json( {", "await opp_ws_client(opp) await client.send_json( { ID: 1, TYPE: \"ozw/get_code_slots\", NODE_ID:", "message = MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"versions\"}, ) message.encode()", "= await opp_ws_client(opp) # Test instance list await client.send_json({ID: 4,", "opp_ws_client(opp) # Send the refresh_node_info command await client.send_json({ID: 9, TYPE:", "1, ATTR_USERCODE: \"1234\", } ) msg = await client.receive_json() assert", "openpeerpower.components.ozw.lock import ATTR_USERCODE from openpeerpower.components.ozw.websocket_api import ( ATTR_IS_AWAKE, ATTR_IS_BEAMING, ATTR_IS_FAILED,", "Test network statistics await client.send_json({ID: 11, TYPE: \"ozw/network_statistics\"}) msg =", "not found error await client.send_json( { ID: 18, TYPE: \"ozw/set_config_parameter\",", "== \"driverAllNodesQueried\" assert result[\"OpenZWave_Version\"] == \"1.6.1008\" # Test network status", "= msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test node statistics", "result[NODE_ID] == 39 assert result[\"send_count\"] == 57 assert result[\"sent_failed\"] ==", "ATTR_IS_ZWAVE_PLUS, ATTR_NEIGHBORS, ATTR_NODE_BASIC_STRING, ATTR_NODE_BAUD_RATE, ATTR_NODE_GENERIC_STRING, ATTR_NODE_QUERY_STAGE, ATTR_NODE_SPECIFIC_STRING, ID, NODE_ID, OZW_INSTANCE,", "msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND async def test_ws_locks(opp, lock_data, opp_ws_client):", "\"versions\" async def test_refresh_node_unsubscribe(opp, generic_data, opp_ws_client): \"\"\"Test unsubscribing the ozw", "len(msg[\"result\"]) == 1 result = msg[\"result\"][0] assert result[OZW_INSTANCE] == 1", "assert len(result) == 5 assert result[2][ATTR_IS_AWAKE] assert not result[1][ATTR_IS_FAILED] #", "msg[\"result\"] assert result[OZW_INSTANCE] == 1 assert result[NODE_ID] == 32 assert", "ozw refresh node api.\"\"\" await setup_ozw(opp, fixture=generic_data) client = await", "the refresh_node_info command await client.send_json({ID: 9, TYPE: \"ozw/refresh_node_info\", NODE_ID: 39})", "msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test OZW Node not", "= msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND async def test_ws_locks(opp, lock_data,", "\"ozw/get_code_slots\", NODE_ID: 10, } ) msg = await client.receive_json() assert", "import ( ATTR_CODE_SLOT, ATTR_LABEL, ATTR_OPTIONS, ATTR_POSITION, ATTR_VALUE, ValueType, ) from", "setup_ozw async def test_websocket_api(opp, generic_data, opp_ws_client): \"\"\"Test the ozw websocket", "= await client.receive_json() result = msg[\"result\"] assert result[\"metadata\"][\"ProductPic\"] == \"images/aeotec/zwa002.png\"", "= msg[\"result\"] assert result[\"Status\"] == \"driverAllNodesQueried\" assert result[OZW_INSTANCE] == 1", "msg = await client.receive_json() result = msg[\"event\"] assert result[\"type\"] ==", "3, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True, ATTR_LABEL: \"test\"}, } )", "39, PARAMETER: 3, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True, ATTR_LABEL: \"test\"},", "29 assert result[\"average_response_rtt\"] == 37 assert result[\"received_packets\"] == 3594 assert", "found error await client.send_json( {ID: 16, TYPE: \"ozw/get_config_parameters\", OZW_INSTANCE: 999,", "1, ATTR_VALUE: True, ATTR_LABEL: \"test\"}, } ) msg = await", "assert result[ATTR_IS_AWAKE] assert not result[ATTR_IS_FAILED] assert result[ATTR_NODE_BAUD_RATE] == 100000 assert", "result = msg[\"result\"] assert len(result) == 8 for config_param in", "Test get nodes await client.send_json({ID: 12, TYPE: \"ozw/get_nodes\"}) msg =", "= MQTTMessage( topic=\"OpenZWave/1/node/35/\", payload={\"NodeID\": 35, \"NodeQueryStage\": \"fake_shouldnt_be_received\"}, ) message.encode() receive_message(message)", "msg = await client.receive_json() result = msg[\"result\"] assert result[OZW_INSTANCE] ==", "ERR_NOT_FOUND # Test OZW Node not found error await client.send_json(", "NODE_ID: 39}) msg = await client.receive_json() result = msg[\"result\"] assert", "37, 39] await client.send_json({ID: 7, TYPE: \"ozw/node_status\", NODE_ID: 999}) msg", "result[\"code\"] == ERR_NOT_SUPPORTED # Test invalid bitset format await client.send_json(", "from OZW message = MQTTMessage( topic=\"OpenZWave/1/node/39/\", payload={\"NodeID\": 39, \"NodeQueryStage\": \"versions\"},", "\"fake_shouldnt_be_received\"}, ) message.encode() receive_message(message) # Verify we received the message", "api.\"\"\" await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) with patch(\"openzwavemqtt.OZWOptions.listen\")", "== ERR_NOT_FOUND # Test network statistics await client.send_json({ID: 11, TYPE:", "NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_val, } ) msg =", "PARAMETER: 45, VALUE: \"test\", } ) msg = await client.receive_json()", "await client.send_json({ID: 5, TYPE: \"ozw/network_status\"}) msg = await client.receive_json() result", "ATTR_VALUE: True, ATTR_LABEL: \"test\"}, } ) msg = await client.receive_json()", "# Send the refresh_node_info command await client.send_json({ID: 9, TYPE: \"ozw/refresh_node_info\",", "assert result[\"code\"] == ERR_NOT_FOUND # Test parameter not found await", "True, ATTR_LABEL: \"test\"}, } ) msg = await client.receive_json() result", "5 # Test get nodes await client.send_json({ID: 12, TYPE: \"ozw/get_nodes\"})", "ATTR_CODE_SLOT, ATTR_LABEL, ATTR_OPTIONS, ATTR_POSITION, ATTR_VALUE, ValueType, ) from openpeerpower.components.ozw.const import", "39}) await client.receive_json() # Send the unsubscribe command await client.send_json({ID:", "# Test node status await client.send_json({ID: 6, TYPE: \"ozw/node_status\", NODE_ID:", "# Test node statistics await client.send_json({ID: 8, TYPE: \"ozw/node_statistics\", NODE_ID:", "result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND async def test_ws_locks(opp,", "TYPE: \"ozw/node_metadata\", NODE_ID: 39}) msg = await client.receive_json() result =", "\"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_val, } ) msg", "\"ozw/clear_usercode\", NODE_ID: 10, ATTR_CODE_SLOT: 1, } ) msg = await", "1 assert result[NODE_ID] == 39 assert result[\"send_count\"] == 57 assert", "client.receive_json() assert msg[\"success\"] # Test OZW Instance not found error", "ID: 21, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 3, VALUE: 0,", "msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test node statistics await", "assert result[\"node_count\"] == 5 # Test get nodes await client.send_json({ID:", "TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: 10000, VALUE: {ATTR_POSITION: 1, ATTR_VALUE:", "= msg[\"result\"] assert len(result) == 8 for config_param in result:", "assert result[OZW_INSTANCE] == 1 assert result[\"node_count\"] == 5 # Test", "= await setup_ozw(opp, fixture=generic_data) client = await opp_ws_client(opp) # Send", "from openpeerpower.components.ozw.lock import ATTR_USERCODE from openpeerpower.components.ozw.websocket_api import ( ATTR_IS_AWAKE, ATTR_IS_BEAMING,", "new_val ) await client.send_json( { ID: 14, TYPE: \"ozw/set_config_parameter\", NODE_ID:", "result[\"readCnt\"] == 92220 assert result[OZW_INSTANCE] == 1 assert result[\"node_count\"] ==", "result = msg[\"error\"] assert result[\"code\"] == ERR_NOT_FOUND # Test value", "client.send_json({ID: 10, TYPE: \"unsubscribe_events\", \"subscription\": 9}) await client.receive_json() assert mock_listen.return_value.called", "== 92220 assert result[OZW_INSTANCE] == 1 assert result[\"node_count\"] == 5", "result[\"sent_failed\"] == 0 assert result[\"retries\"] == 1 assert result[\"last_request_rtt\"] ==", "3546 # Test node metadata await client.send_json({ID: 9, TYPE: \"ozw/node_metadata\",", "\"ozw/network_status\"}) msg = await client.receive_json() result = msg[\"result\"] assert result[\"Status\"]", "= await client.receive_json() assert msg[\"success\"] await client.send_json( { ID: 15,", "12, TYPE: \"ozw/get_nodes\"}) msg = await client.receive_json() result = msg[\"result\"]", "msg[\"event\"] assert result[\"type\"] == \"node_updated\" assert result[\"node_query_stage\"] == \"initializing\" #", "== \"driverAllNodesQueried\" assert result[OZW_INSTANCE] == 1 # Test node status", "fixture=generic_data) client = await opp_ws_client(opp) # Send the refresh_node_info command", "option[0] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[0] != current_val )", "mock status update for a different node message = MQTTMessage(", "# Test get nodes await client.send_json({ID: 12, TYPE: \"ozw/get_nodes\"}) msg", "10000, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True}, } ) msg =", "15, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_label, }", "== ERR_NOT_FOUND # Test OZW Node not found error await", "client.receive_json() assert len(sent_messages) == 1 assert msg[\"success\"] # Receive a", "!= current_val ) new_label = next( option[1] for option in", "client.receive_json() assert len(msg[\"result\"]) == 1 result = msg[\"result\"][0] assert result[OZW_INSTANCE]", "client.send_json( { ID: 18, TYPE: \"ozw/set_config_parameter\", NODE_ID: 999, PARAMETER: 0,", "Send a mock status update for a different node message", "client.send_json( { ID: 15, TYPE: \"ozw/set_config_parameter\", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER],", "result[ATTR_NODE_BASIC_STRING] == \"Routing Slave\" assert result[ATTR_NODE_GENERIC_STRING] == \"Binary Switch\" assert", "NODE_ID: 999}) msg = await client.receive_json() result = msg[\"error\"] assert", "from openzwavemqtt.const import ( ATTR_CODE_SLOT, ATTR_LABEL, ATTR_OPTIONS, ATTR_POSITION, ATTR_VALUE, ValueType,", "await opp_ws_client(opp) # Send the refresh_node_info command await client.send_json({ID: 9,", "await client.receive_json() result = msg[\"result\"] assert result[\"metadata\"][\"ProductPic\"] == \"images/aeotec/zwa002.png\" await", "result[OZW_INSTANCE] == 1 # Test node status await client.send_json({ID: 6,", "5, TYPE: \"ozw/network_status\"}) msg = await client.receive_json() result = msg[\"result\"]" ]
[ "'+ one\\n' '+ two\\n' '+ three\\n' ), marks=pytest.mark.xfail(raises=AssertionError)), ( #", "def test_normalise_whitespace(): assert normalise_whitespace('\\u200C Your tax is\\ndue\\n\\n') == 'Your tax", "assert markdown_function( 'col | col\\n' '----|----\\n' 'val | val\\n' )", "'markdown_function, expected', ( [ notify_letter_preview_markdown, '<h2>heading</h2>\\n' ], [ notify_email_markdown, (", "'this is some text with a link ' '<a style=\"word-wrap:", "25px; color: #0B0C0C;\">' '{}' '</p>' ).format(expected_html) assert expected_html_in_template in str(HTMLEmailTemplate({'content':", "{'before_each': '<i>', 'after_each': '</i>'}, '<i>1</i>, <i>2</i> and <i>3</i>'), ]) def", "line-height: 25px; color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>'", "<a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", ), ]) def", "words & some more <words>' def test_removing_pipes(): assert strip_pipes('|a|b|c') ==", "), ( '\\n \\t . word', '\\n. word', ), ])", "#005ea5;\" href=\"{}\">{}</a>'.format(url, url) assert (notify_email_markdown(url) == ( '<p style=\"Margin: 0", "== expected def test_sms_preview_adds_newlines(): template = SMSPreviewTemplate({'content': \"\"\" the quick", "'prefix_plural': 'bar'}, 'bar ‘1’, ‘2’ and ‘3’'), ([1], {'prefix': 'foo',", "URL\">' 'Example' '</a>' '</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n'", "'</p>' ).format(output) @pytest.mark.parametrize( \"url\", [ \"example.com\", \"www.example.com\", \"ftp://example.com\", \"<EMAIL>\", \"mailto:<EMAIL>\",", "(\"bonjour .\", \"bonjour.\"), ('double -- dash', 'double \\u2013 dash'), ]", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' 'Next paragraph' '</p>'", "\"\"\" the quick brown fox \"\"\"}) template.prefix = None template.sender", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">inset", "Markup) def test_removing_dvla_markup(): assert strip_dvla_markup( ( 'some words & some", "], [ notify_plain_text_email_markdown, ( '\\n' '\\nline one' '\\nline two' '\\n'", "unlink_govuk_escaped(template_content) == expected assert expected in str(PlainTextEmailTemplate({'content': template_content, 'subject': ''}))", "output): assert notify_email_markdown(input) == ( '<p style=\"Margin: 0 0 20px", "message', 'Hello Jo,\\n\\nThis is a message' ), ( '\\n \\t", "], [ notify_plain_text_email_markdown, ( '\\n' '\\nExample (An example URL): http://example.com'", "25px; color: #0B0C0C;\">three</li>' '</ol>' '</td>' '</tr>' '</table>' ) ], [", "19px;' 'line-height: 25px; color: #0B0C0C;\">two</li>' '<li style=\"Margin: 5px 0 5px;", "is a message', 'Hello ((name)),\\n\\nThis is a message' ), (", "'subject': ''})) def test_HTML_template_has_URLs_replaced_with_links(): assert ( '<a style=\"word-wrap: break-word; color:", "'<i>&amp;</i>'), ([1, 2, 3], {'before_each': '<i>', 'after_each': '</i>'}, '<i>1</i>, <i>2</i>", "), ( 'triple --- dash', 'triple \\u2013 dash', ), (", "'this is some text with a link http://example.com in the", "called `thing`' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "**important**</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething **important**', ], )) def test_double_emphasis(markdown_function,", "body}) template.prefix = prefix template.sender = None assert str(template) ==", "([1], {'prefix': 'foo', 'prefix_plural': 'bar'}, 'foo ‘1’'), ([1, 2, 3],", "href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>')\"\"\", # noqa \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>‘)\"\"\", #", "'<p>a</p>' '<div class=\"page-break\">&nbsp;</div>' '<p>b</p>' ) ], [ notify_email_markdown, ( '<p", "@pytest.mark.parametrize('input, output', [ ( ( 'this is some text with", "# tab '* one\\n' '* two\\n' '* three\\n' ), (", "URL): http://example.com' ), ], )) def test_link_with_title(markdown_function, expected): assert markdown_function(", "notify_letter_preview_markdown, notify_plain_text_email_markdown, sms_encode, formatted_list, strip_dvla_markup, strip_pipes, escape_html, remove_whitespace_before_punctuation, make_quotes_smart, replace_hyphens_with_en_dashes,", "assert markdown_function( 'variable called `thing`' ) == expected @pytest.mark.parametrize('markdown_function, expected',", "assert hyphen not in en_dash_replacement_sequence @pytest.mark.parametrize('markup, expected_fixed', [ ( 'a',", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+", "'\\n' '\\nline one' '\\nline two' '\\n' '\\nnew paragraph' ), ],", "test_unicode_dash_lookup(): en_dash_replacement_sequence = '\\u0020\\u2013' hyphen = '-' en_dash = '–'", "], )) def test_ordered_list(markdown_function, expected): assert markdown_function( '1. one\\n' '2.", "‘2’ foo ‘3’'), (['&'], {'before_each': '<i>', 'after_each': '</i>'}, '<i>&amp;</i>'), ([1,", "single space '* one\\n' '* two\\n' '* three\\n' ), (", "line-height: 25px; color: #0B0C0C;\">a</p>' '<hr style=\"border: 0; height: 1px; background:", "'- three\\n' ), pytest.param(( # plus as bullet '+ one\\n'", "( '\\n' '\\ninset text' ), ], )) def test_level_2_header(markdown_function, expected):", "em dash. ' ), ( 'The en dash \\u2013 always", "25px; color: #0B0C0C;\">variable called thing</p>' ], [ notify_plain_text_email_markdown, '\\n\\nvariable called", "( '<p>a</p>' '<div class=\"page-break\">&nbsp;</div>' '<p>b</p>' ) ], [ notify_email_markdown, (", "en_dash_replacement_sequence @pytest.mark.parametrize('markup, expected_fixed', [ ( 'a', 'a', ), ( 'before<p><cr><p><cr>after',", "), ], )) def test_hrule(markdown_function, expected): assert markdown_function('a\\n\\n***\\n\\nb') == expected", "def test_ordered_list(markdown_function, expected): assert markdown_function( '1. one\\n' '2. two\\n' '3.", "5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">three</li>' '</ul>' '</td>' '</tr>'", "a2b and a3b'), ([1, 2, 3], {'conjunction': 'foo'}, '‘1’, ‘2’", "'</td>' '</tr>' '</table>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\n•", "font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">three</li>' '</ol>' '</td>' '</tr>' '</table>'", "& some more <words>' def test_removing_pipes(): assert strip_pipes('|a|b|c') == 'abc'", "'<ol>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ol>\\n' ) ], [ notify_email_markdown, (", "' assert strip_and_remove_obscure_whitespace(sentence) == 'words \\n over multiple lines with", "'\\n \\t . word', '\\n. word', ), ]) def test_removing_whitespace_before_full_stops(dirty,", "text](http://example.com/image.png)' ) == ( '' ) @pytest.mark.parametrize('markdown_function, expected', ( [", "\\u2013 dash', ), ( 'quadruple ---- dash', 'quadruple ---- dash',", "def test_unordered_list(markdown, markdown_function, expected): assert markdown_function(markdown) == expected @pytest.mark.parametrize('markdown_function, expected',", "assert markdown_function( 'something **important**' ) == expected @pytest.mark.parametrize('markdown_function, expected', (", "], )) def test_emphasis(markdown_function, expected): assert markdown_function( 'something *important*' )", "address line ‘three’ \"\"\") def test_strip_unsupported_characters(): assert strip_unsupported_characters(\"line one\\u2028line two\")", "text') == (expected) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>a</p>'", "thing</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0 20px 0;", "word', '\\n. word', ), ]) def test_removing_whitespace_before_full_stops(dirty, clean): assert remove_whitespace_before_punctuation(dirty)", "'<p>Example: <strong>example.com</strong></p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin: 0", "markdown_function( 'variable called `thing`' ) == expected @pytest.mark.parametrize('markdown_function, expected', (", "expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>inset text</p>' ], [", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">something *important*</p>' ],", "'something *important*' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_email_markdown,", "color: #0B0C0C;\">a</p>' '<hr style=\"border: 0; height: 1px; background: #BFC1C3; Margin:", "'double \\u2013 dash', ), ( 'triple --- dash', 'triple \\u2013", "), ], [ notify_plain_text_email_markdown, ( '\\n\\n+ one' '\\n\\n+ two' '\\n\\n+", "expected assert expected in str(PlainTextEmailTemplate({'content': template_content, 'subject': ''})) assert expected", "sms_encode('aàá…') == 'aàa...' @pytest.mark.parametrize('items, kwargs, expected_output', [ ([1], {}, '‘1’'),", "#0B0C0C;\">after</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nbefore' '\\n' '\\nafter'", "'http://example.com', ( '\\n' '\\nhttp://example.com' ), ], )) def test_autolink(markdown_function, link,", ") ) def test_block_code(markdown_function, expected): assert markdown_function('```\\nprint(\"hello\")\\n```') == expected @pytest.mark.parametrize('markdown_function,", "tweak_dvla_list_markup(markup) == expected_fixed def test_make_list_from_linebreaks(): assert nl2li( 'a\\n' 'b\\n' 'c\\n'", "replace_hyphens_with_en_dashes(nasty) == nice def test_unicode_dash_lookup(): en_dash_replacement_sequence = '\\u0020\\u2013' hyphen =", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>'\"\"\", # noqa \"\"\"<a style=\"word-wrap: break-word;", ").format(output) @pytest.mark.parametrize( \"url\", [ \"example.com\", \"www.example.com\", \"ftp://example.com\", \"<EMAIL>\", \"mailto:<EMAIL>\", \"<a", "'line-height: 25px; color: #0B0C0C;\">three</li>' '</ol>' '</td>' '</tr>' '</table>' ) ],", "'• three\\n' ), )) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, (", "'val | val\\n' ) == ( '' ) @pytest.mark.parametrize('markdown_function, link,", "color: #005ea5;\" href=\"http://example.com\">http://example.com</a>)' ), ) ]) def test_makes_links_out_of_URLs_in_context(input, output): assert", "), ( # dash as bullet '- one\\n' '- two\\n'", "( '\\n' '\\nExample: http://example.com' ), ], )) def test_link(markdown_function, expected):", "'\">' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt; line-height:", "| col\\n' '----|----\\n' 'val | val\\n' ) == ( ''", "this pass def test_sms_encode(): assert sms_encode('aàá…') == 'aàa...' @pytest.mark.parametrize('items, kwargs,", "( 'double -- dash', 'double \\u2013 dash', ), ( 'triple", "[ notify_email_markdown, ( '<h2 style=\"Margin: 0 0 20px 0; padding:", "'</a>' '</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nExample (An", "notify_email_markdown, ( '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "test_preserves_whitespace_when_making_links( markdown_function, expected_output ): assert markdown_function( 'https://example.com\\n' '\\n' 'Next paragraph'", "str(template) == expected def test_sms_preview_adds_newlines(): template = SMSPreviewTemplate({'content': \"\"\" the", "\"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>’\"\"\", # noqa ), ]", ")) def test_level_2_header(markdown_function, expected): assert markdown_function('## inset text') == (expected)", "assert (notify_email_markdown(url) == ( '<p style=\"Margin: 0 0 20px 0;", "paragraph' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, (", "), ], )) def test_ordered_list(markdown_function, expected): assert markdown_function( '1. one\\n'", "25px; color: #0B0C0C;\">something *important*</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething *important*', ],", "'\\nNext paragraph' )), ]) def test_preserves_whitespace_when_making_links( markdown_function, expected_output ): assert", "( # no space '*one\\n' '*two\\n' '*three\\n' ), ( #", "== expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<ol>\\n' '<li>one</li>\\n'", "'<p>inset text</p>' ) ], [ notify_email_markdown, ( '<blockquote ' 'style=\"Margin:", ") def test_doesnt_make_links_out_of_invalid_urls(url): assert notify_email_markdown(url) == ( '<p style=\"Margin: 0", "test_strip_whitespace(value): assert strip_whitespace(value) == 'bar' @pytest.mark.parametrize('value', [ 'notifications-email', ' \\tnotifications-email", "formatted_list(items, **kwargs) == expected_output def test_formatted_list_returns_markup(): assert isinstance(formatted_list([0]), Markup) def", "nice def test_unicode_dash_lookup(): en_dash_replacement_sequence = '\\u0020\\u2013' hyphen = '-' en_dash", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">inset text</p>' '</blockquote>' )", "expected): assert markdown_function( '1. one\\n' '2. two\\n' '3. three\\n' )", "expected): assert markdown_function( '+ one\\n' '+ two\\n' '+ three\\n' )", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com\">' 'https://example.com' '</a>' '</p>' '<p style=\"Margin:", "‘2’'), ([1, 2, 3], {}, '‘1’, ‘2’ and ‘3’'), ([1,", "( 'some words & some more <words>' '<cr><h1><h2><p><normal><op><np><bul><tab>' '<CR><H1><H2><P><NORMAL><OP><NP><BUL><TAB>' '<tAb>'", "color: #0B0C0C;\">Strike</p>' ], [ notify_plain_text_email_markdown, '\\n\\nStrike' ], )) def test_strikethrough(markdown_function,", "= '\\u0020\\u2013' hyphen = '-' en_dash = '–' space =", "), ( 'The en dash \\u2013 always with spaces in", "pytest.param(( # plus as bullet '+ one\\n' '+ two\\n' '+", "2, 3], {'before_each': 'a', 'after_each': 'b'}, 'a1b, a2b and a3b'),", "def test_link_with_title(markdown_function, expected): assert markdown_function( '[Example](http://example.com \"An example URL\")' )", "title=\"An example URL\">' 'Example' '</a>' '</p>' ) ], [ notify_plain_text_email_markdown,", "], )) def test_pluses_dont_render_as_lists(markdown_function, expected): assert markdown_function( '+ one\\n' '+", "3], {'before_each': 'a', 'after_each': 'b'}, 'a1b, a2b and a3b'), ([1,", "'<p>Strike</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0 20px 0;", "tweak_dvla_list_markup, nl2li, strip_whitespace, strip_and_remove_obscure_whitespace, remove_smart_quotes_from_email_addresses, strip_unsupported_characters, normalise_whitespace ) from notifications_utils.template", "style=\"Margin: 0 0 20px 0; padding: 0; font-size: 27px; '", "line one’s quote first.o'<EMAIL> is someone’s email address line ‘three’", "replace_hyphens_with_en_dashes, tweak_dvla_list_markup, nl2li, strip_whitespace, strip_and_remove_obscure_whitespace, remove_smart_quotes_from_email_addresses, strip_unsupported_characters, normalise_whitespace ) from", "]) def test_makes_links_out_of_URLs_in_context(input, output): assert notify_email_markdown(input) == ( '<p style=\"Margin:", "test_table(markdown_function): assert markdown_function( 'col | col\\n' '----|----\\n' 'val | val\\n'", "assert formatted_list(items, **kwargs) == expected_output def test_formatted_list_returns_markup(): assert isinstance(formatted_list([0]), Markup)", "advantage over the unspaced em dash. ' ), ( 'The", ") ], [ notify_plain_text_email_markdown, ( '\\n' '\\nbefore' '\\n' '\\nafter' ),", "import Markup from notifications_utils.formatters import ( unlink_govuk_escaped, notify_email_markdown, notify_letter_preview_markdown, notify_plain_text_email_markdown,", "non_breaking_space not in en_dash_replacement_sequence assert hyphen not in en_dash_replacement_sequence @pytest.mark.parametrize('markup,", "3], {'conjunction': 'foo'}, '‘1’, ‘2’ foo ‘3’'), (['&'], {'before_each': '<i>',", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">a</p>'", "(\"a\", \"b\", \"a: b\"), (None, \"b\", \"b\"), ] ) def", "notify_email_markdown( \"http://example.com/?token=<span class='placeholder'>((token))</span>&key=1\" ) == ( '<p style=\"Margin: 0 0", "== expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>variable called thing</p>'", "0 0 5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">three</li>' '</ol>'", "'some words & some more <words>' def test_removing_pipes(): assert strip_pipes('|a|b|c')", "'<h2 style=\"Margin: 0 0 20px 0; padding: 0; font-size: 27px;", "20px 0; font-size: 11pt; line-height: 25px; ' 'color: #0B0C0C;\">' '<a", "( 'this link is in brackets (http://example.com)' ), ( 'this", "test_nested_emphasis(markdown_function, expected): assert markdown_function( 'foo ****** bar' ) == expected", "( 'this is some text with a link http://example.com in", "& some more <words>' '<cr><h1><h2><p><normal><op><np><bul><tab>' '<CR><H1><H2><P><NORMAL><OP><NP><BUL><TAB>' '<tAb>' ) ) ==", "expected_fixed', [ ( 'a', 'a', ), ( 'before<p><cr><p><cr>after', 'before<p><cr>after', ),", "'-' en_dash = '–' space = ' ' non_breaking_space =", "line-height: 25px; color: #0B0C0C;\">after</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n'", "[ notify_plain_text_email_markdown, '\\n\\nsomething **important**', ], )) def test_double_emphasis(markdown_function, expected): assert", "0 20px 0; border-left: 10px solid #BFC1C3;' 'padding: 15px 0", "[ ( ( 'this is some text with a link", "'line two\\n' '\\n' 'new paragraph' ) == expected @pytest.mark.parametrize('markdown_function, expected',", "expected', ( [ notify_letter_preview_markdown, '<p>variable called thing</p>' ], [ notify_email_markdown,", "expected): assert markdown_function(markdown) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "( ( 'this link is in brackets (http://example.com)' ), (", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(url)", "en_dash_replacement_sequence = '\\u0020\\u2013' hyphen = '-' en_dash = '–' space", "[ notify_letter_preview_markdown, '<p>something important</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0", "'\\n' 'Thanks\\n' ), 'subject': ''})) @pytest.mark.parametrize('markdown_function, expected_output', [ (notify_email_markdown, (", "0 20px 0; font-size: 11pt; line-height: 25px; ' 'color: #0B0C0C;\">'", "expected', ( [ notify_letter_preview_markdown, '<p>+ one</p><p>+ two</p><p>+ three</p>', ], [", "' '(<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>)' ), ) ])", "3], {'prefix': 'foo', 'prefix_plural': 'bar'}, 'bar ‘1’, ‘2’ and ‘3’'),", "( '\\n' '\\n• one' '\\n• two' '\\n• three' ), ],", "breakfast at Tiffany's\"?\"\"\", \"\"\"And I said, “what about breakfast at", "is in brackets (http://example.com)' ), ( 'this link is in", "( [ notify_letter_preview_markdown, ( '<p>' 'line one<br>' 'line two' '</p>'", "== ( \"&lt;to cancel daily cat facts reply 'cancel'&gt;\" )", "dash both have a certain ' 'technical advantage over the", "5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">one</li>' '<li style=\"Margin: 5px", "three\\n' ), marks=pytest.mark.xfail(raises=AssertionError)), ( # bullet as bullet '• one\\n'", "( 'bonjour | hi', 'bonjour | hi', ), ]) def", "25px; color: #0B0C0C;\">inset text</p>' '</blockquote>' ) ], [ notify_plain_text_email_markdown, (", "notify_plain_text_email_markdown, ( '\\n' '\\ninset text' ), ], )) def test_level_2_header(markdown_function,", "\"\"\", ), ]) def test_smart_quotes(dumb, smart): assert make_quotes_smart(dumb) == smart", "a link http://example.com in the middle' ), ( 'this is", "three\\n' ) == expected assert markdown_function( '1.one\\n' '2.two\\n' '3.three\\n' )", "]) def test_formatted_list(items, kwargs, expected_output): assert formatted_list(items, **kwargs) == expected_output", "11pt; line-height: 25px; color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\"", "def test_strip_whitespace(value): assert strip_whitespace(value) == 'bar' @pytest.mark.parametrize('value', [ 'notifications-email', '", "\"prefix, body, expected\", [ (\"a\", \"b\", \"a: b\"), (None, \"b\",", "assert strip_and_remove_obscure_whitespace(value) == 'notifications-email' def test_strip_and_remove_obscure_whitespace_only_removes_normal_whitespace_from_ends(): sentence = ' words", "and <i>3</i>'), ]) def test_formatted_list(items, kwargs, expected_output): assert formatted_list(items, **kwargs)", "assert expected == HTMLEmailTemplate({'content': '', 'subject': subject}).subject @pytest.mark.parametrize( \"prefix, body,", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(output)", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>')\"\"\", # noqa \"\"\"<a style=\"word-wrap: break-word;", "notify_letter_preview_markdown, '<p>something important</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0", "@pytest.mark.parametrize( \"url, expected_html, expected_html_in_template\", [ ( \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", \"\"\"<a style=\"word-wrap: break-word;", "@pytest.mark.parametrize('value', [ 'notifications-email', ' \\tnotifications-email \\x0c ', '\\rn\\u200Coti\\u200Dfi\\u200Bcati\\u2060ons-\\u180Eemai\\uFEFFl\\uFEFF', ]) def", "one' '\\n2. two' '\\n3. three' ), ], )) def test_ordered_list(markdown_function,", "'before{}<np>after'.format('<cr>' * 4), 'before{}<np>after'.format('<cr>' * 3), ), ]) def test_tweaking_dvla_list_markup(markup,", "'+ three\\n' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "[ notify_letter_preview_markdown, ( '<p>' 'line one<br>' 'line two' '</p>' '<p>'", "clean', [ ( 'Hello ((name)) ,\\n\\nThis is a message', 'Hello", "'\\nline one' '\\nline two' '\\n' '\\nnew paragraph' ), ], ))", "style=\"Margin: 0 0 20px 0; font-size: 11pt; line-height: 25px; '", "'a1b, a2b and a3b'), ([1, 2, 3], {'conjunction': 'foo'}, '‘1’,", "from notifications_utils.template import ( HTMLEmailTemplate, PlainTextEmailTemplate, SMSMessageTemplate, SMSPreviewTemplate ) @pytest.mark.parametrize(", "expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown )) def test_image(markdown_function): assert", "'<ul>' '<li>a</li>' '<li>b</li>' '<li>c</li>' '</ul>' ) @pytest.mark.parametrize('value', [ 'bar', '", "== expected @pytest.mark.parametrize('heading', ( '# heading', '#heading', )) @pytest.mark.parametrize( 'markdown_function,", ") == expected @pytest.mark.parametrize('markdown', ( ( # no space '*one\\n'", "19px;' 'line-height: 25px; color: #0B0C0C;\">three</li>' '</ol>' '</td>' '</tr>' '</table>' )", "'<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ol>\\n' ) ], [ notify_email_markdown, ( '<table", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\" title=\"An example URL\">' 'Example' '</a>'", "'line-height: 25px; color: #0B0C0C;\">three</li>' '</ul>' '</td>' '</tr>' '</table>' ) ],", "( unlink_govuk_escaped, notify_email_markdown, notify_letter_preview_markdown, notify_plain_text_email_markdown, sms_encode, formatted_list, strip_dvla_markup, strip_pipes, escape_html,", "'\\n' '\\na' '\\n' '\\n=================================================================' '\\n' '\\nb' ), ], )) def", "line-height: 25px; color: #0B0C0C;\">before</p>' '<p style=\"Margin: 0 0 20px 0;", "assert notify_email_markdown(input) == ( '<p style=\"Margin: 0 0 20px 0;", "message', 'Hello ((name)),\\n\\nThis is a message' ), ( 'Hello Jo", ") def test_sms_message_adds_prefix(prefix, body, expected): template = SMSMessageTemplate({'content': body}) template.prefix", "]) def test_removing_whitespace_before_punctuation(dirty, clean): assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dirty, clean',", "11pt; line-height: 25px; color: #0B0C0C;\">something *important*</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething", "'</ol>' '</td>' '</tr>' '</table>' ) ], [ notify_plain_text_email_markdown, ( '\\n'", "( '<ol>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ol>\\n' ) ], [ notify_email_markdown,", "0 5px; padding: 0 0 0 5px; font-size: 19px;' 'line-height:", "**important**' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>something", "'\\n\\nvariable called thing', ], )) def test_codespan(markdown_function, expected): assert markdown_function(", "expected', ( [ notify_letter_preview_markdown, ( '<ol>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ol>\\n'", "( [ notify_letter_preview_markdown, ( '<ul>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ul>\\n' )", "@pytest.mark.parametrize('markdown_function, expected_output', [ (notify_email_markdown, ( '<p style=\"Margin: 0 0 20px", "11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(output) @pytest.mark.parametrize( \"url\",", "a parenthesis or ' 'pause - and the spaced em", "two\\n' '+ three\\n' ), marks=pytest.mark.xfail(raises=AssertionError)), ( # bullet as bullet", "notify_letter_preview_markdown, ( '<p>Example: <strong>example.com</strong></p>' ) ], [ notify_email_markdown, ( '<p", "20px 0; border-left: 10px solid #BFC1C3;' 'padding: 15px 0 0.1px", "<i>3</i>'), ]) def test_formatted_list(items, kwargs, expected_output): assert formatted_list(items, **kwargs) ==", "word', ), ]) def test_removing_whitespace_before_full_stops(dirty, clean): assert remove_whitespace_before_punctuation(dirty) == clean", "25px; ' 'color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">Example</a>'", "markdown_function( '![alt text](http://example.com/image.png)' ) == ( '' ) @pytest.mark.parametrize('markdown_function, expected',", "style=\"Margin: 0 0 0 20px; padding: 0; list-style-type: disc;\">' '<li", ")) def test_table(markdown_function): assert markdown_function( 'col | col\\n' '----|----\\n' 'val", "@pytest.mark.parametrize( \"url\", [ \"http://example.com\", \"http://www.gov.uk/\", \"https://www.gov.uk/\", \"http://service.gov.uk\", \"http://service.gov.uk/blah.ext?q=a%20b%20c&order=desc#fragment\", pytest.param(\"http://service.gov.uk/blah.ext?q=one two", ") == ( '<ul>' '<li>a</li>' '<li>b</li>' '<li>c</li>' '</ul>' ) @pytest.mark.parametrize('value',", "fox \"\"\"}) template.prefix = None template.sender = None assert '<br>'", "def test_removing_pipes(): assert strip_pipes('|a|b|c') == 'abc' def test_bleach_doesnt_try_to_make_valid_html_before_cleaning(): assert escape_html(", "), ) ]) def test_makes_links_out_of_URLs_in_context(input, output): assert notify_email_markdown(input) == (", "#0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com/?token=\">' 'http://example.com/?token=' '</a>' '<span", "( \"\"\"https://example.com\"style='text-decoration:blink'\"\"\", \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>'\"\"\", # noqa", "@pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown )) def test_table(markdown_function): assert markdown_function(", "spaces in running text when, as ' 'discussed in this", "'<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\" title=\"An example URL\">' 'Example'", "( '\\n\\n+ one' '\\n\\n+ two' '\\n\\n+ three' ), ], ))", "link:\\n' 'https://service.example.com/accept_invite/a1b2c3d4\\n' '\\n' 'Thanks\\n' ), 'subject': ''})) @pytest.mark.parametrize('markdown_function, expected_output', [", "some text with a link http://example.com in the middle' ),", ") ], [ notify_plain_text_email_markdown, ( '\\n' '\\n• one' '\\n• two'", "expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_email_markdown, '<p style=\"Margin: 0 0", "'Hello ((name)),\\n\\nThis is a message' ), ( 'Hello Jo ,\\n\\nThis", "expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>inset text</p>' )", "two' '\\n• three' ), ], )) def test_unordered_list(markdown, markdown_function, expected):", "assert markdown_function( 'https://example.com\\n' '\\n' 'Next paragraph' ) == expected_output @pytest.mark.parametrize(", "11pt; line-height: 25px; color: #0B0C0C;\">+ one</p>' '<p style=\"Margin: 0 0", "), ], ) ) def test_level_1_header(markdown_function, heading, expected): assert markdown_function(heading)", "25px; color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com/?token=\">' 'http://example.com/?token='", "three' ), ], )) def test_pluses_dont_render_as_lists(markdown_function, expected): assert markdown_function( '+", "break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>')\"\"\", # noqa \"\"\"<a style=\"word-wrap: break-word; color:", "notify_plain_text_email_markdown, ( '\\n' '\\nbefore' '\\n' '\\nafter' ), ], )) def", "( '' ) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>Example:", "to a service. Click this link:\\n' 'https://service.example.com/accept_invite/a1b2c3d4\\n' '\\n' 'Thanks\\n' ),", "noqa ), ( \"\"\"https://example.com\"style='text-decoration:blink'\"\"\", \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>'\"\"\",", "\"<EMAIL>\", \"mailto:<EMAIL>\", \"<a href=\\\"https://example.com\\\">Example</a>\", ] ) def test_doesnt_make_links_out_of_invalid_urls(url): assert notify_email_markdown(url)", "def test_hrule(markdown_function, expected): assert markdown_function('a\\n\\n***\\n\\nb') == expected assert markdown_function('a\\n\\n---\\n\\nb') ==", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">Strike</p>' ],", "], [ notify_plain_text_email_markdown, 'print(\"hello\")' ], ) ) def test_block_code(markdown_function, expected):", "\"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>'\"\"\", # noqa \"\"\"<a style=\"word-wrap:", "expected', ( [ notify_letter_preview_markdown, '<p>something important</p>' ], [ notify_email_markdown, '<p", "href=\"{}\">{}</a>'.format(url, url) assert (notify_email_markdown(url) == ( '<p style=\"Margin: 0 0", "bar \"\"\", ' \\u180E\\u200B \\u200C bar \\u200D \\u2060\\uFEFF ', ])", "[ notify_plain_text_email_markdown, ( '\\n' '\\ninset text' ), ], )) def", "\"\"\") == (\"\"\" line one’s quote first.o'<EMAIL> is someone’s email", "| hi', 'bonjour | hi', ), ]) def test_removing_whitespace_before_punctuation(dirty, clean):", "remove_whitespace_before_punctuation, make_quotes_smart, replace_hyphens_with_en_dashes, tweak_dvla_list_markup, nl2li, strip_whitespace, strip_and_remove_obscure_whitespace, remove_smart_quotes_from_email_addresses, strip_unsupported_characters, normalise_whitespace", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '{}'", "is in brackets ' '(<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>)'", "template_content, 'subject': ''})) @pytest.mark.parametrize( \"subject,expected\", [ (\"bonjour | hi\", \"bonjour", "assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dirty, clean', [ ( 'Hello ((name))", "], [ notify_email_markdown, 'http://example.com', ( '<p style=\"Margin: 0 0 20px", "test_doesnt_make_links_out_of_invalid_urls(url): assert notify_email_markdown(url) == ( '<p style=\"Margin: 0 0 20px", "notify_email_markdown, ( '<h2 style=\"Margin: 0 0 20px 0; padding: 0;", "break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>'\"\"\", # noqa \"\"\"<a style=\"word-wrap: break-word; color:", "expected): assert markdown_function(heading) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>‘)\"\"\", # noqa ), ( \"\"\"https://example.com\"style='text-decoration:blink'\"\"\", \"\"\"<a", "line-height: 25px; color: #0B0C0C;\">Strike</p>' ], [ notify_plain_text_email_markdown, '\\n\\nStrike' ], ))", "expected_output', [ ([1], {}, '‘1’'), ([1, 2], {}, '‘1’ and", "dash. ' ), ), ( 'double -- dash', 'double \\u2013", "is a message' ), ( 'Hello Jo .\\n\\nThis is a", "formatted_list, strip_dvla_markup, strip_pipes, escape_html, remove_whitespace_before_punctuation, make_quotes_smart, replace_hyphens_with_en_dashes, tweak_dvla_list_markup, nl2li, strip_whitespace,", "(['&'], {'before_each': '<i>', 'after_each': '</i>'}, '<i>&amp;</i>'), ([1, 2, 3], {'before_each':", "called thing</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0 20px", ") def test_makes_links_out_of_URLs(url): link = '<a style=\"word-wrap: break-word; color: #005ea5;\"", "'heading' '</h2>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\n' '\\nheading'", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">foo ****** bar</p>'", "'</a>' ) in str(HTMLEmailTemplate({'content': ( 'You’ve been invited to a", "( 'a', 'a', ), ( 'before<p><cr><p><cr>after', 'before<p><cr>after', ), ( 'before<cr><cr><np>after',", "'</table>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\n• one' '\\n•", "== expected assert expected in str(PlainTextEmailTemplate({'content': template_content, 'subject': ''})) assert", "\"http://example.com\", \"http://www.gov.uk/\", \"https://www.gov.uk/\", \"http://service.gov.uk\", \"http://service.gov.uk/blah.ext?q=a%20b%20c&order=desc#fragment\", pytest.param(\"http://service.gov.uk/blah.ext?q=one two three\", marks=pytest.mark.xfail), ]", "test_sms_message_adds_prefix(prefix, body, expected): template = SMSMessageTemplate({'content': body}) template.prefix = prefix", "body, expected\", [ (\"a\", \"b\", \"a: b\"), (None, \"b\", \"b\"),", "href=\"https://example.com%22onclick=%22alert%28%27hi\">' 'https://example.com\"onclick=\"alert(\\'hi' '</a>\\')' '</p>' ) ], [ notify_plain_text_email_markdown, 'http://example.com', (", "URL\")' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>Strike</p>'", "' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' ' in the", "'\\nhttps://example.com' '\\n' '\\nNext paragraph' )), ]) def test_preserves_whitespace_when_making_links( markdown_function, expected_output", "test_escaping_govuk_in_email_templates(template_content, expected): assert unlink_govuk_escaped(template_content) == expected assert expected in str(PlainTextEmailTemplate({'content':", "paragraph' ) == expected_output @pytest.mark.parametrize( \"template_content,expected\", [ (\"gov.uk\", u\"gov.\\u200Buk\"), (\"GOV.UK\",", "25px; color: #0B0C0C;\">a</p>' '<hr style=\"border: 0; height: 1px; background: #BFC1C3;", "' words \\n over multiple lines with \\ttabs\\t ' assert", "((name)),\\n\\nThis is a message' ), ( 'Hello Jo ,\\n\\nThis is", ") ], [ notify_email_markdown, ( '<table role=\"presentation\" style=\"padding: 0 0", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' '</p>' ) ], [ notify_email_markdown,", "'</h2>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\n' '\\nheading' '\\n-----------------------------------------------------------------'", "] ) def test_sms_message_adds_prefix(prefix, body, expected): template = SMSMessageTemplate({'content': body})", "[ notify_letter_preview_markdown, '<p>inset text</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0", "0 0 20px 0;\">' '<tr>' '<td style=\"font-family: Helvetica, Arial, sans-serif;\">'", "5px; padding: 0 0 0 5px; font-size: 19px;' 'line-height: 25px;", "assert strip_whitespace(value) == 'bar' @pytest.mark.parametrize('value', [ 'notifications-email', ' \\tnotifications-email \\x0c", "expected_output): assert formatted_list(items, **kwargs) == expected_output def test_formatted_list_returns_markup(): assert isinstance(formatted_list([0]),", "), ( 'bonjour | hi', 'bonjour | hi', ), ])", "\"\"\"}) template.prefix = None template.sender = None assert '<br>' in", "'foo', 'prefix_plural': 'bar'}, 'foo ‘1’'), ([1, 2, 3], {'before_each': 'a',", "[ notify_email_markdown, '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown )) def test_image(markdown_function): assert markdown_function( '![alt text](http://example.com/image.png)'", "'Hello ((name)) .\\n\\nThis is a message', 'Hello ((name)).\\n\\nThis is a", "- and the spaced em dash both have a certain", "20px; padding: 0; list-style-type: disc;\">' '<li style=\"Margin: 5px 0 5px;", ").format(expected_html) assert expected_html_in_template in str(HTMLEmailTemplate({'content': url, 'subject': ''})) def test_HTML_template_has_URLs_replaced_with_links():", "'bar', ' bar ', \"\"\" \\t bar \"\"\", ' \\u180E\\u200B", "en_dash_replacement_sequence == space + en_dash assert non_breaking_space not in en_dash_replacement_sequence", "assert markdown_function( 'before\\n\\n\\n\\n\\n\\nafter' ) == expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown,", "'<p>' 'line one<br>' 'line two' '</p>' '<p>' 'new paragraph' '</p>'", ", word', '\\n, word', ), ( 'bonjour | hi', 'bonjour", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">variable called", "some more <words>' def test_removing_pipes(): assert strip_pipes('|a|b|c') == 'abc' def", ") @pytest.mark.parametrize( \"url, expected_html, expected_html_in_template\", [ ( \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", \"\"\"<a style=\"word-wrap:", "]) def test_strip_and_remove_obscure_whitespace(value): assert strip_and_remove_obscure_whitespace(value) == 'notifications-email' def test_strip_and_remove_obscure_whitespace_only_removes_normal_whitespace_from_ends(): sentence", "test_multiple_newlines_get_truncated(markdown_function, expected): assert markdown_function( 'before\\n\\n\\n\\n\\n\\nafter' ) == expected @pytest.mark.parametrize('markdown_function', (", "'<p>something important</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0 20px", "( [ notify_letter_preview_markdown, ( '<p>a</p>' '<div class=\"page-break\">&nbsp;</div>' '<p>b</p>' ) ],", "color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>‘)\"\"\", # noqa ), ( \"\"\"https://example.com\"style='text-decoration:blink'\"\"\", \"\"\"<a style=\"word-wrap:", "markdown_function( '1.one\\n' '2.two\\n' '3.three\\n' ) == expected @pytest.mark.parametrize('markdown', ( (", "25px; color: #0B0C0C;\">' 'Next paragraph' '</p>' )), (notify_plain_text_email_markdown, ( '\\n'", ") == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>'", "'* three\\n' ), ( # two spaces '* one\\n' '*", "two\\n' '- three\\n' ), pytest.param(( # plus as bullet '+", "( '<p>Example: <strong>example.com</strong></p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin:", "brown fox \"\"\"}) template.prefix = None template.sender = None assert", "None assert '<br>' in str(template) @pytest.mark.parametrize( 'markdown_function, expected', ( [", "'–' space = ' ' non_breaking_space = ' ' assert", "\"template_content,expected\", [ (\"gov.uk\", u\"gov.\\u200Buk\"), (\"GOV.UK\", u\"GOV.\\u200BUK\"), (\"Gov.uk\", u\"Gov.\\u200Buk\"), (\"https://gov.uk\", \"https://gov.uk\"),", "notify_plain_text_email_markdown, ( '\\n' '\\nExample: http://example.com' ), ], )) def test_link(markdown_function,", "@pytest.mark.parametrize( 'markdown_function, expected', ( [ notify_letter_preview_markdown, 'print(\"hello\")' ], [ notify_email_markdown,", "'<cr><h1><h2><p><normal><op><np><bul><tab>' '<CR><H1><H2><P><NORMAL><OP><NP><BUL><TAB>' '<tAb>' ) ) == 'some words & some", "{'before_each': 'a', 'after_each': 'b'}, 'a1b, a2b and a3b'), ([1, 2,", "nice): assert replace_hyphens_with_en_dashes(nasty) == nice def test_unicode_dash_lookup(): en_dash_replacement_sequence = '\\u0020\\u2013'", "one\\n' '+ two\\n' '+ three\\n' ) == expected @pytest.mark.parametrize('markdown_function, expected',", "is a message', 'Hello ((name)).\\n\\nThis is a message' ), (", "color: #0B0C0C;\">something **important**</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething **important**', ], ))", "expected @pytest.mark.parametrize('markdown', ( ( # no space '*one\\n' '*two\\n' '*three\\n'", "'<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ul>\\n' ) ], [ notify_email_markdown, ( '<table", "( # tab '* one\\n' '* two\\n' '* three\\n' ),", "assert escape_html( \"<to cancel daily cat facts reply 'cancel'>\" )", "over multiple lines with \\ttabs\\t ' assert strip_and_remove_obscure_whitespace(sentence) == 'words", "'before<cr><np>after', ), ( 'before{}<np>after'.format('<cr>' * 4), 'before{}<np>after'.format('<cr>' * 3), ),", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>a</p>' '<div class=\"page-break\">&nbsp;</div>' '<p>b</p>'", "– dash', ), ( 'already\\u0020–\\u0020correct', # \\u0020 is a normal", "'double -- dash', 'double \\u2013 dash', ), ( 'triple ---", "0 0 0 20px; padding: 0; list-style-type: disc;\">' '<li style=\"Margin:", "quote first.o’<EMAIL> is someone’s email address line ‘three’ \"\"\") ==", "color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>'\"\"\", # noqa \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\"", "line-height: 25px; color: #0B0C0C;\">+ one</p>' '<p style=\"Margin: 0 0 20px", "(\"line oneline two\") def test_normalise_whitespace(): assert normalise_whitespace('\\u200C Your tax is\\ndue\\n\\n')", "], [ notify_email_markdown, ( '<p style=\"Margin: 0 0 20px 0;", "'</a>\\')' '</p>' ) ], [ notify_plain_text_email_markdown, 'http://example.com', ( '\\n' '\\nhttp://example.com'", "2, 3], {'conjunction': 'foo'}, '‘1’, ‘2’ foo ‘3’'), (['&'], {'before_each':", "], )) def test_strikethrough(markdown_function, expected): assert markdown_function('~~Strike~~') == expected def", "text when, as ' 'discussed in this section, indicating a", "notify_letter_preview_markdown, ( '<ul>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ul>\\n' ) ], [", "\"&lt;to cancel daily cat facts reply 'cancel'&gt;\" ) @pytest.mark.parametrize('dirty, clean',", "str(HTMLEmailTemplate({'content': ( 'You’ve been invited to a service. Click this", "= prefix template.sender = None assert str(template) == expected def", ") == expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown )) def", ") @pytest.mark.parametrize('markdown_function, link, expected', ( [ notify_letter_preview_markdown, 'http://example.com', '<p><strong>example.com</strong></p>' ],", "from flask import Markup from notifications_utils.formatters import ( unlink_govuk_escaped, notify_email_markdown,", ") @pytest.mark.parametrize( \"url\", [ \"http://example.com\", \"http://www.gov.uk/\", \"https://www.gov.uk/\", \"http://service.gov.uk\", \"http://service.gov.uk/blah.ext?q=a%20b%20c&order=desc#fragment\", pytest.param(\"http://service.gov.uk/blah.ext?q=one", "dash', 'em – dash', ), ( 'already\\u0020–\\u0020correct', # \\u0020 is", "( [ notify_letter_preview_markdown, '<p>something important</p>' ], [ notify_email_markdown, '<p style=\"Margin:", "test_en_dashes(nasty, nice): assert replace_hyphens_with_en_dashes(nasty) == nice def test_unicode_dash_lookup(): en_dash_replacement_sequence =", "notifications_utils.template import ( HTMLEmailTemplate, PlainTextEmailTemplate, SMSMessageTemplate, SMSPreviewTemplate ) @pytest.mark.parametrize( \"url\",", "def test_handles_placeholders_in_urls(): assert notify_email_markdown( \"http://example.com/?token=<span class='placeholder'>((token))</span>&key=1\" ) == ( '<p", "cat facts reply 'cancel'>\" ) == ( \"&lt;to cancel daily", ")) def test_link_with_title(markdown_function, expected): assert markdown_function( '[Example](http://example.com \"An example URL\")'", "30px 0;\">' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "'\\nline two' '\\n' '\\nnew paragraph' ), ], )) def test_paragraphs(markdown_function,", "), ( 'Hello Jo ,\\n\\nThis is a message', 'Hello Jo,\\n\\nThis", "href=\"http://example.com/?token=\">' 'http://example.com/?token=' '</a>' '<span class=\\'placeholder\\'>((token))</span>&amp;key=1' '</p>' ) @pytest.mark.parametrize( \"url, expected_html,", "one\\u2028line two\") == (\"line oneline two\") def test_normalise_whitespace(): assert normalise_whitespace('\\u200C", "25px;' '\">' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "<strong>example.com</strong></p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin: 0 0", "0; font-size: 27px; ' 'line-height: 35px; font-weight: bold; color: #0B0C0C;\">'", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">' 'https://example.com\"onclick=\"alert(\\'hi' '</a>\\')' '</p>' ) ],", "output', [ ( ( 'this is some text with a", "# noqa ), ( \"\"\"https://example.com\"style='text-decoration:blink'\"\"\", \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\"", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">b</p>' ) ], [", "strip_unsupported_characters, normalise_whitespace ) from notifications_utils.template import ( HTMLEmailTemplate, PlainTextEmailTemplate, SMSMessageTemplate,", "expected): assert markdown_function('^ inset text') == expected @pytest.mark.parametrize('heading', ( '#", "plus as bullet '+ one\\n' '+ two\\n' '+ three\\n' ),", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">variable called thing</p>'", "hyphen = '-' en_dash = '–' space = ' '", "[ notify_plain_text_email_markdown, ( '\\n\\n+ one' '\\n\\n+ two' '\\n\\n+ three' ),", "one\\n' '+ two\\n' '+ three\\n' ), marks=pytest.mark.xfail(raises=AssertionError)), ( # bullet", "'\\n' '\\nbefore' '\\n' '\\nafter' ), ], )) def test_multiple_newlines_get_truncated(markdown_function, expected):", "(http://example.com)' ), ( 'this link is in brackets ' '(<a", "is a message' ), ( 'Hello Jo ,\\n\\nThis is a", "'\\nExample: http://example.com' ), ], )) def test_link(markdown_function, expected): assert markdown_function(", "flask import Markup from notifications_utils.formatters import ( unlink_govuk_escaped, notify_email_markdown, notify_letter_preview_markdown,", "\"\"\", \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", ), ]) def test_smart_quotes(dumb, smart):", "a message', 'Hello Jo,\\n\\nThis is a message' ), ( '\\n", "'</p>' ).format(url) def test_handles_placeholders_in_urls(): assert notify_email_markdown( \"http://example.com/?token=<span class='placeholder'>((token))</span>&key=1\" ) ==", "normal space character 'already\\u0020–\\u0020correct', ), ( '2004-2008', '2004-2008', # no", "\"https://www.gov.uk/\", \"http://service.gov.uk\", \"http://service.gov.uk/blah.ext?q=a%20b%20c&order=desc#fragment\", pytest.param(\"http://service.gov.uk/blah.ext?q=one two three\", marks=pytest.mark.xfail), ] ) def", "template = SMSPreviewTemplate({'content': \"\"\" the quick brown fox \"\"\"}) template.prefix", ") ], [ notify_email_markdown, ( '<p style=\"Margin: 0 0 20px", "11pt; line-height: 25px; color: #0B0C0C;\">new paragraph</p>' ) ], [ notify_plain_text_email_markdown,", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">b</p>' ) ], [ notify_plain_text_email_markdown,", "dash', ), ( 'em — dash', 'em – dash', ),", "u\"Gov.\\u200Buk\"), (\"https://gov.uk\", \"https://gov.uk\"), (\"https://www.gov.uk\", \"https://www.gov.uk\"), (\"www.gov.uk\", \"www.gov.uk\"), (\"gov.uk/register-to-vote\", \"gov.uk/register-to-vote\"), (\"gov.uk?q=\",", "'2. two\\n' '3. three\\n' ) == expected assert markdown_function( '1.one\\n'", "decimal;\">' '<li style=\"Margin: 5px 0 5px; padding: 0 0 0", "], )) def test_level_2_header(markdown_function, expected): assert markdown_function('## inset text') ==", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">b</p>'", "0; list-style-type: disc;\">' '<li style=\"Margin: 5px 0 5px; padding: 0", "[ (notify_email_markdown, ( '<p style=\"Margin: 0 0 20px 0; font-size:", "non_breaking_space = ' ' assert en_dash_replacement_sequence == space + en_dash", "a service. Click this link:\\n' 'https://service.example.com/accept_invite/a1b2c3d4\\n' '\\n' 'Thanks\\n' ), 'subject':", "#0B0C0C;\">+ three</p>' ), ], [ notify_plain_text_email_markdown, ( '\\n\\n+ one' '\\n\\n+", "strip_pipes('|a|b|c') == 'abc' def test_bleach_doesnt_try_to_make_valid_html_before_cleaning(): assert escape_html( \"<to cancel daily", "markdown_function(link) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>variable called", "— dash', 'em – dash', ), ( 'already\\u0020–\\u0020correct', # \\u0020", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>‘)\"\"\", # noqa ), ( \"\"\"https://example.com\"style='text-decoration:blink'\"\"\",", "space '*one\\n' '*two\\n' '*three\\n' ), ( # single space '*", "assert strip_dvla_markup( ( 'some words & some more <words>' '<cr><h1><h2><p><normal><op><np><bul><tab>'", "\"b\"), ] ) def test_sms_message_adds_prefix(prefix, body, expected): template = SMSMessageTemplate({'content':", "), ( # single space '* one\\n' '* two\\n' '*", "' 'color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\" title=\"An", "Jo ,\\n\\nThis is a message', 'Hello Jo,\\n\\nThis is a message'", "<a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", ), ]) def test_smart_quotes(dumb, smart): assert make_quotes_smart(dumb)", "'2004-2008', # no replacement ), ( 'bonjour | hi', 'bonjour", "\\u200D \\u2060\\uFEFF ', ]) def test_strip_whitespace(value): assert strip_whitespace(value) == 'bar'", "25px; color: #0B0C0C;\">three</li>' '</ul>' '</td>' '</tr>' '</table>' ) ], [", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">line one<br />' 'line two</p>'", "'\\n1. one' '\\n2. two' '\\n3. three' ), ], )) def", "(notify_email_markdown(url) == ( '<p style=\"Margin: 0 0 20px 0; font-size:", "some text with a link ' '<a style=\"word-wrap: break-word; color:", "= SMSPreviewTemplate({'content': \"\"\" the quick brown fox \"\"\"}) template.prefix =", "\"ftp://example.com\", \"<EMAIL>\", \"mailto:<EMAIL>\", \"<a href=\\\"https://example.com\\\">Example</a>\", ] ) def test_doesnt_make_links_out_of_invalid_urls(url): assert", "11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(expected_html) assert expected_html_in_template", "markdown_function('^ inset text') == expected @pytest.mark.parametrize('heading', ( '# heading', '#heading',", "str(HTMLEmailTemplate({'content': url, 'subject': ''})) def test_HTML_template_has_URLs_replaced_with_links(): assert ( '<a style=\"word-wrap:", "'</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nExample (An example", "link http://example.com in the middle' ), ( 'this is some", "'\\n\\n+ three' ), ], )) def test_pluses_dont_render_as_lists(markdown_function, expected): assert markdown_function(", "style=\"Margin: 0 0 20px 0; font-size: 11pt; line-height: 25px; color:", "'a', 'a', ), ( 'before<p><cr><p><cr>after', 'before<p><cr>after', ), ( 'before<cr><cr><np>after', 'before<cr><np>after',", "(notify_email_markdown, ( '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">Strike</p>'", "color: #0B0C0C;\">' '{}' '</p>' ).format(expected_html) assert expected_html_in_template in str(HTMLEmailTemplate({'content': url,", "list-style-type: disc;\">' '<li style=\"Margin: 5px 0 5px; padding: 0 0", "'<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' ' in the middle'", "two\\n' '3. three\\n' ) == expected assert markdown_function( '1.one\\n' '2.two\\n'", "def test_nested_emphasis(markdown_function, expected): assert markdown_function( 'foo ****** bar' ) ==", "SMSPreviewTemplate({'content': \"\"\" the quick brown fox \"\"\"}) template.prefix = None", "dash. ' ), ( 'The en dash \\u2013 always with", "25px; color: #0B0C0C;\">' '{}' '</p>' ).format(output) @pytest.mark.parametrize( \"url\", [ \"example.com\",", ") @pytest.mark.parametrize('dirty, clean', [ ( 'Hello ((name)) ,\\n\\nThis is a", "'padding: 15px 0 0.1px 15px; font-size: 19px; line-height: 25px;' '\">'", "[ notify_letter_preview_markdown, '<h2>heading</h2>\\n' ], [ notify_email_markdown, ( '<h2 style=\"Margin: 0", "message', 'Hello Jo.\\n\\nThis is a message' ), ( '\\n \\t", "a link ' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' '", "Arial, sans-serif;\">' '<ol style=\"Margin: 0 0 0 20px; padding: 0;", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(output) @pytest.mark.parametrize(", "], [ notify_plain_text_email_markdown, '\\n\\nStrike' ], )) def test_strikethrough(markdown_function, expected): assert", "val\\n' ) == ( '' ) @pytest.mark.parametrize('markdown_function, link, expected', (", "expected): assert markdown_function('## inset text') == (expected) @pytest.mark.parametrize('markdown_function, expected', (", "30px 0 30px 0;\">' '<p style=\"Margin: 0 0 20px 0;", "message' ), ( 'Hello Jo ,\\n\\nThis is a message', 'Hello", "def test_sms_message_adds_prefix(prefix, body, expected): template = SMSMessageTemplate({'content': body}) template.prefix =", "'\\n' '\\n' '\\nheading' '\\n-----------------------------------------------------------------' ), ], ) ) def test_level_1_header(markdown_function,", "), ( ( 'this link is in brackets (http://example.com)' ),", "[ notify_email_markdown, ( '<p style=\"Margin: 0 0 20px 0; font-size:", "( '<table role=\"presentation\" style=\"padding: 0 0 20px 0;\">' '<tr>' '<td", "line-height: 25px; color: #0B0C0C;\">inset text</p>' '</blockquote>' ) ], [ notify_plain_text_email_markdown,", "Click this link:\\n' 'https://service.example.com/accept_invite/a1b2c3d4\\n' '\\n' 'Thanks\\n' ), 'subject': ''})) @pytest.mark.parametrize('markdown_function,", "'Hello Jo ,\\n\\nThis is a message', 'Hello Jo,\\n\\nThis is a", "| hi', ), ]) def test_removing_whitespace_before_punctuation(dirty, clean): assert remove_whitespace_before_punctuation(dirty) ==", "( 'quadruple ---- dash', 'quadruple ---- dash', ), ( 'em", "break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>)' ), ) ]) def test_makes_links_out_of_URLs_in_context(input, output):", "def test_strip_unsupported_characters(): assert strip_unsupported_characters(\"line one\\u2028line two\") == (\"line oneline two\")", "], [ notify_plain_text_email_markdown, '\\n\\nsomething **important**', ], )) def test_double_emphasis(markdown_function, expected):", "'new paragraph' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>Example: <strong>example.com</strong></p>' ) ],", "paragraph' )), ]) def test_preserves_whitespace_when_making_links( markdown_function, expected_output ): assert markdown_function(", "\"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", ), ]) def test_smart_quotes(dumb, smart): assert", "template.sender = None assert '<br>' in str(template) @pytest.mark.parametrize( 'markdown_function, expected',", "assert expected in str(HTMLEmailTemplate({'content': template_content, 'subject': ''})) @pytest.mark.parametrize( \"subject,expected\", [", "], [ notify_plain_text_email_markdown, '\\n\\nvariable called thing', ], )) def test_codespan(markdown_function,", "#0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com\">' 'https://example.com' '</a>' '</p>'", "= None assert str(template) == expected def test_sms_preview_adds_newlines(): template =", ")) def test_double_emphasis(markdown_function, expected): assert markdown_function( 'something **important**' ) ==", "col\\n' '----|----\\n' 'val | val\\n' ) == ( '' )", "Jo,\\n\\nThis is a message' ), ( '\\n \\t , word',", "'[Example](http://example.com)' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, (", "this section, indicating a parenthesis or ' 'pause \\u2013 and", "test_URLs_get_escaped(url, expected_html, expected_html_in_template): assert notify_email_markdown(url) == ( '<p style=\"Margin: 0", "'<tr>' '<td style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ul style=\"Margin: 0 0", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">variable called thing</p>' ],", "notify_plain_text_email_markdown, ( '\\n' '\\ninset text' ), ], )) def test_block_quote(markdown_function,", ")) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<ul>\\n' '<li>one</li>\\n' '<li>two</li>\\n'", "with spaces in running text when, as ' 'discussed in", "multiple lines with \\ttabs\\t ' assert strip_and_remove_obscure_whitespace(sentence) == 'words \\n", "notify_plain_text_email_markdown, ( '\\n' '\\n1. one' '\\n2. two' '\\n3. three' ),", "hyphen not in en_dash_replacement_sequence @pytest.mark.parametrize('markup, expected_fixed', [ ( 'a', 'a',", "'</blockquote>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\ninset text' ),", ")) def test_nested_emphasis(markdown_function, expected): assert markdown_function( 'foo ****** bar' )", "{}, '‘1’'), ([1, 2], {}, '‘1’ and ‘2’'), ([1, 2,", "[ ( ( 'The en dash - always with spaces", "certain ' 'technical advantage over the unspaced em dash. '", "been invited to a service. Click this link:\\n' 'https://service.example.com/accept_invite/a1b2c3d4\\n' '\\n'", "'\\n' '\\nnew paragraph' ), ], )) def test_paragraphs(markdown_function, expected): assert", "assert markdown_function('a\\n\\n***\\n\\nb') == expected assert markdown_function('a\\n\\n---\\n\\nb') == expected @pytest.mark.parametrize('markdown_function, expected',", "'</a>' '</p>' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "'2004-2008', '2004-2008', # no replacement ), ( 'bonjour | hi',", "assert sms_encode('aàá…') == 'aàa...' @pytest.mark.parametrize('items, kwargs, expected_output', [ ([1], {},", "words \\n over multiple lines with \\ttabs\\t ' assert strip_and_remove_obscure_whitespace(sentence)", "as bullet '+ one\\n' '+ two\\n' '+ three\\n' ), marks=pytest.mark.xfail(raises=AssertionError)),", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">after</p>'", "'triple \\u2013 dash', ), ( 'quadruple ---- dash', 'quadruple ----", "expected): assert markdown_function( 'something *important*' ) == expected @pytest.mark.parametrize('markdown_function, expected',", "\"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>')\"\"\", # noqa \"\"\"<a style=\"word-wrap:", "line-height: 25px; color: #0B0C0C;\">inset text</p>' ], [ notify_plain_text_email_markdown, ( '\\n'", "test_unordered_list(markdown, markdown_function, expected): assert markdown_function(markdown) == expected @pytest.mark.parametrize('markdown_function, expected', (", "two' '</p>' '<p>' 'new paragraph' '</p>' ) ], [ notify_email_markdown,", "a message' ), ( 'Hello Jo .\\n\\nThis is a message',", "11pt; line-height: 25px; color: #0B0C0C;\">Strike</p>' ], [ notify_plain_text_email_markdown, '\\n\\nStrike' ],", "] ) def test_makes_links_out_of_URLs(url): link = '<a style=\"word-wrap: break-word; color:", "clean @pytest.mark.parametrize('dumb, smart', [ ( \"\"\"And I said, \"what about", "'technical advantage over the unspaced em dash. ' ), (", "( '\\n' '\\nExample (An example URL): http://example.com' ), ], ))", "paragraph' ), ], )) def test_paragraphs(markdown_function, expected): assert markdown_function( 'line", "25px; color: #0B0C0C;\">b</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\na'", "), ]) def test_removing_whitespace_before_full_stops(dirty, clean): assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dumb,", "( [ notify_email_markdown, '<p style=\"Margin: 0 0 20px 0; font-size:", "strip_pipes, escape_html, remove_whitespace_before_punctuation, make_quotes_smart, replace_hyphens_with_en_dashes, tweak_dvla_list_markup, nl2li, strip_whitespace, strip_and_remove_obscure_whitespace, remove_smart_quotes_from_email_addresses,", "assert markdown_function('^ inset text') == expected @pytest.mark.parametrize('heading', ( '# heading',", "'https://service.example.com/accept_invite/a1b2c3d4\\n' '\\n' 'Thanks\\n' ), 'subject': ''})) @pytest.mark.parametrize('markdown_function, expected_output', [ (notify_email_markdown,", "''})) @pytest.mark.parametrize('markdown_function, expected_output', [ (notify_email_markdown, ( '<p style=\"Margin: 0 0", "color: #0B0C0C;\">something *important*</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething *important*', ], ))", ")) def test_image(markdown_function): assert markdown_function( '![alt text](http://example.com/image.png)' ) == (", "'<CR><H1><H2><P><NORMAL><OP><NP><BUL><TAB>' '<tAb>' ) ) == 'some words & some more", "'quadruple ---- dash', ), ( 'em — dash', 'em –", "pytest from flask import Markup from notifications_utils.formatters import ( unlink_govuk_escaped,", "expected', ( [ notify_letter_preview_markdown, '<p>inset text</p>' ], [ notify_email_markdown, '<p", "'foo', 'prefix_plural': 'bar'}, 'bar ‘1’, ‘2’ and ‘3’'), ([1], {'prefix':", "/>' 'line two</p>' '<p style=\"Margin: 0 0 20px 0; font-size:", "assert tweak_dvla_list_markup(markup) == expected_fixed def test_make_list_from_linebreaks(): assert nl2li( 'a\\n' 'b\\n'", "'</p>' ) ], [ notify_plain_text_email_markdown, 'http://example.com', ( '\\n' '\\nhttp://example.com' ),", "--- dash', 'triple \\u2013 dash', ), ( 'quadruple ---- dash',", "'this link is in brackets (http://example.com)' ), ( 'this link", "' 'pause \\u2013 and the spaced em dash both have", "as bullet '- one\\n' '- two\\n' '- three\\n' ), pytest.param((", "clean): assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dumb, smart', [ ( \"\"\"And", "a message', 'Hello ((name)),\\n\\nThis is a message' ), ( 'Hello", "(\"gov.uk?q=\", \"gov.uk?q=\") ] ) def test_escaping_govuk_in_email_templates(template_content, expected): assert unlink_govuk_escaped(template_content) ==", "in str(HTMLEmailTemplate({'content': template_content, 'subject': ''})) @pytest.mark.parametrize( \"subject,expected\", [ (\"bonjour |", "( '\\n' '\\na' '\\n' '\\n=================================================================' '\\n' '\\nb' ), ], ))", "three\\n' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, (", "brackets (http://example.com)' ), ( 'this link is in brackets '", "about breakfast at Tiffany's\"?\"\"\", \"\"\"And I said, “what about breakfast", "| hi', ), ]) def test_en_dashes(nasty, nice): assert replace_hyphens_with_en_dashes(nasty) ==", ")) def test_ordered_list(markdown_function, expected): assert markdown_function( '1. one\\n' '2. two\\n'", "a message' ), ( '\\n \\t . word', '\\n. word',", "expected', ( [ notify_letter_preview_markdown, 'http://example.com', '<p><strong>example.com</strong></p>' ], [ notify_email_markdown, 'http://example.com',", "assert markdown_function('```\\nprint(\"hello\")\\n```') == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, (", "no space '*one\\n' '*two\\n' '*three\\n' ), ( # single space", "'print(\"hello\")' ], [ notify_email_markdown, 'print(\"hello\")' ], [ notify_plain_text_email_markdown, 'print(\"hello\")' ],", "'</p>' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt; line-height:", "text with a link http://example.com in the middle' ), (", "kwargs, expected_output', [ ([1], {}, '‘1’'), ([1, 2], {}, '‘1’", "[ ( 'Hello ((name)) .\\n\\nThis is a message', 'Hello ((name)).\\n\\nThis", "in str(template) @pytest.mark.parametrize( 'markdown_function, expected', ( [ notify_letter_preview_markdown, 'print(\"hello\")' ],", "#0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">' 'https://example.com\"onclick=\"alert(\\'hi' '</a>\\')' '</p>'", "[ notify_letter_preview_markdown, ( '<p>before</p>' '<p>after</p>' ) ], [ notify_email_markdown, (", "assert notify_email_markdown( \"http://example.com/?token=<span class='placeholder'>((token))</span>&key=1\" ) == ( '<p style=\"Margin: 0", "( 'You’ve been invited to a service. Click this link:\\n'", "'pause - and the spaced em dash both have a", "'The en dash - always with spaces in running text", "one\\n' '• two\\n' '• three\\n' ), )) @pytest.mark.parametrize('markdown_function, expected', (", "[ notify_letter_preview_markdown, 'http://example.com', '<p><strong>example.com</strong></p>' ], [ notify_email_markdown, 'http://example.com', ( '<p", "'</ol>\\n' ) ], [ notify_email_markdown, ( '<table role=\"presentation\" style=\"padding: 0", "expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>+ one</p><p>+ two</p><p>+ three</p>',", "as bullet '• one\\n' '• two\\n' '• three\\n' ), ))", "] ) def test_escaping_govuk_in_email_templates(template_content, expected): assert unlink_govuk_escaped(template_content) == expected assert", ".\\n\\nThis is a message', 'Hello ((name)).\\n\\nThis is a message' ),", "\"\"\"And I said, \"what about breakfast at Tiffany's\"?\"\"\", \"\"\"And I", "+ en_dash assert non_breaking_space not in en_dash_replacement_sequence assert hyphen not", "0 20px; padding: 0; list-style-type: decimal;\">' '<li style=\"Margin: 5px 0", "'already\\u0020–\\u0020correct', # \\u0020 is a normal space character 'already\\u0020–\\u0020correct', ),", "2], {}, '‘1’ and ‘2’'), ([1, 2, 3], {}, '‘1’,", "| val\\n' ) == ( '' ) @pytest.mark.parametrize('markdown_function, link, expected',", "'foo'}, '‘1’, ‘2’ foo ‘3’'), (['&'], {'before_each': '<i>', 'after_each': '</i>'},", "([1, 2, 3], {'conjunction': 'foo'}, '‘1’, ‘2’ foo ‘3’'), (['&'],", "en dash - always with spaces in running text when,", "notify_email_markdown, 'print(\"hello\")' ], [ notify_plain_text_email_markdown, 'print(\"hello\")' ], ) ) def", "[ notify_email_markdown, 'print(\"hello\")' ], [ notify_plain_text_email_markdown, 'print(\"hello\")' ], ) )", "'</table>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\n1. one' '\\n2.", "25px; color: #0B0C0C;\">foo ****** bar</p>' ], [ notify_plain_text_email_markdown, '\\n\\nfoo ******", "color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' '</p>' ) ], [ notify_email_markdown, \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", (", "assert markdown_function('a\\n\\n---\\n\\nb') == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, (", "( '\\n' '\\nbefore' '\\n' '\\nafter' ), ], )) def test_multiple_newlines_get_truncated(markdown_function,", "( ( # no space '*one\\n' '*two\\n' '*three\\n' ), (", "padding: 0 0 0 5px; font-size: 19px;' 'line-height: 25px; color:", "11pt; line-height: 25px; color: #0B0C0C;\">after</p>' ) ], [ notify_plain_text_email_markdown, (", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">after</p>' ) ], [", "], )) def test_link(markdown_function, expected): assert markdown_function( '[Example](http://example.com)' ) ==", "'<p>inset text</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0 20px", "notify_plain_text_email_markdown, ( '\\n' '\\na' '\\n' '\\n=================================================================' '\\n' '\\nb' ), ],", "[ notify_letter_preview_markdown, ( '<ol>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ol>\\n' ) ],", "border-left: 10px solid #BFC1C3;' 'padding: 15px 0 0.1px 15px; font-size:", "'before<p><cr><p><cr>after', 'before<p><cr>after', ), ( 'before<cr><cr><np>after', 'before<cr><np>after', ), ( 'before{}<np>after'.format('<cr>' *", "], [ notify_plain_text_email_markdown, ( '\\n' '\\n1. one' '\\n2. two' '\\n3.", "notify_letter_preview_markdown, ( '<p>before</p>' '<p>after</p>' ) ], [ notify_email_markdown, ( '<p", "padding: 0; list-style-type: disc;\">' '<li style=\"Margin: 5px 0 5px; padding:", "paragraph</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nline one' '\\nline", "expected): assert markdown_function( 'variable called `thing`' ) == expected @pytest.mark.parametrize('markdown_function,", "test_formatted_list_returns_markup(): assert isinstance(formatted_list([0]), Markup) def test_removing_dvla_markup(): assert strip_dvla_markup( ( 'some", "@pytest.mark.parametrize('nasty, nice', [ ( ( 'The en dash - always", "'<li>c</li>' '</ul>' ) @pytest.mark.parametrize('value', [ 'bar', ' bar ', \"\"\"", "both have a certain ' 'technical advantage over the unspaced", "line ‘three’ \"\"\") == (\"\"\" line one’s quote first.o'<EMAIL> is", "#0B0C0C;\">Strike</p>' ], [ notify_plain_text_email_markdown, '\\n\\nStrike' ], )) def test_strikethrough(markdown_function, expected):", "'markdown_function, expected', ( [ notify_letter_preview_markdown, 'print(\"hello\")' ], [ notify_email_markdown, 'print(\"hello\")'", ")) def test_hrule(markdown_function, expected): assert markdown_function('a\\n\\n***\\n\\nb') == expected assert markdown_function('a\\n\\n---\\n\\nb')", "color: #0B0C0C;\">three</li>' '</ol>' '</td>' '</tr>' '</table>' ) ], [ notify_plain_text_email_markdown,", "'<li>b</li>' '<li>c</li>' '</ul>' ) @pytest.mark.parametrize('value', [ 'bar', ' bar ',", "test_level_2_header(markdown_function, expected): assert markdown_function('## inset text') == (expected) @pytest.mark.parametrize('markdown_function, expected',", "\\u2060\\uFEFF ', ]) def test_strip_whitespace(value): assert strip_whitespace(value) == 'bar' @pytest.mark.parametrize('value',", "'<p>' 'new paragraph' '</p>' ) ], [ notify_email_markdown, ( '<p", "([1], {}, '‘1’'), ([1, 2], {}, '‘1’ and ‘2’'), ([1,", "in str(HTMLEmailTemplate({'content': ( 'You’ve been invited to a service. Click", "'\\ninset text' ), ], )) def test_level_2_header(markdown_function, expected): assert markdown_function('##", "hi\"), (\"bonjour .\", \"bonjour.\"), ('double -- dash', 'double \\u2013 dash'),", "expected): assert markdown_function('```\\nprint(\"hello\")\\n```') == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "dash', 'double \\u2013 dash'), ] ) def test_subject_is_cleaned_up(subject, expected): assert", "subject}).subject @pytest.mark.parametrize( \"prefix, body, expected\", [ (\"a\", \"b\", \"a: b\"),", "'\\n' '\\nheading' '\\n-----------------------------------------------------------------' ), ], ) ) def test_level_1_header(markdown_function, heading,", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>+ one</p><p>+ two</p><p>+ three</p>', ],", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '<a", "message' ), ( 'Hello Jo .\\n\\nThis is a message', 'Hello", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>something important</p>' ], [ notify_email_markdown,", "], )) def test_double_emphasis(markdown_function, expected): assert markdown_function( 'something **important**' )", ") @pytest.mark.parametrize('value', [ 'bar', ' bar ', \"\"\" \\t bar", "( 'em — dash', 'em – dash', ), ( 'already\\u0020–\\u0020correct',", "two\\n' '* three\\n' ), ( # two spaces '* one\\n'", "<i>2</i> and <i>3</i>'), ]) def test_formatted_list(items, kwargs, expected_output): assert formatted_list(items,", "notify_plain_text_email_markdown, '\\n\\nfoo ****** bar', ], )) def test_nested_emphasis(markdown_function, expected): assert", "expected_html_in_template\", [ ( \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>')\"\"\",", "color: #005ea5;\" href=\"http://example.com/?token=\">' 'http://example.com/?token=' '</a>' '<span class=\\'placeholder\\'>((token))</span>&amp;key=1' '</p>' ) @pytest.mark.parametrize(", "line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(expected_html) assert expected_html_in_template in", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>’\"\"\", # noqa ), ] )", "\"\"\") def test_strip_unsupported_characters(): assert strip_unsupported_characters(\"line one\\u2028line two\") == (\"line oneline", "== ( '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "'\\n \\t , word', '\\n, word', ), ( 'bonjour |", "two spaces '* one\\n' '* two\\n' '* three\\n' ), (", "notify_plain_text_email_markdown, ( '\\n' '\\nline one' '\\nline two' '\\n' '\\nnew paragraph'", "'{}' '</p>' ).format(output) @pytest.mark.parametrize( \"url\", [ \"example.com\", \"www.example.com\", \"ftp://example.com\", \"<EMAIL>\",", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">inset text</p>' '</blockquote>' ) ],", "strip_and_remove_obscure_whitespace(value) == 'notifications-email' def test_strip_and_remove_obscure_whitespace_only_removes_normal_whitespace_from_ends(): sentence = ' words \\n", "reply 'cancel'>\" ) == ( \"&lt;to cancel daily cat facts", "remove_smart_quotes_from_email_addresses(\"\"\" line one’s quote first.o’<EMAIL> is someone’s email address line", "== space + en_dash assert non_breaking_space not in en_dash_replacement_sequence assert", "'# heading', '#heading', )) @pytest.mark.parametrize( 'markdown_function, expected', ( [ notify_letter_preview_markdown,", ",\\n\\nThis is a message', 'Hello Jo,\\n\\nThis is a message' ),", "one\\n' 'line two\\n' '\\n' 'new paragraph' ) == expected @pytest.mark.parametrize('markdown_function,", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">something", "reply 'cancel'&gt;\" ) @pytest.mark.parametrize('dirty, clean', [ ( 'Hello ((name)) ,\\n\\nThis", "( '<p>inset text</p>' ) ], [ notify_email_markdown, ( '<blockquote '", "], [ notify_email_markdown, '<p style=\"Margin: 0 0 20px 0; font-size:", "test_image(markdown_function): assert markdown_function( '![alt text](http://example.com/image.png)' ) == ( '' )", "), ]) def test_removing_whitespace_before_punctuation(dirty, clean): assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dirty,", "#0B0C0C;\">a</p>' '<hr style=\"border: 0; height: 1px; background: #BFC1C3; Margin: 30px", "test_removing_whitespace_before_punctuation(dirty, clean): assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dirty, clean', [ (", "assert markdown_function( 'line one\\n' 'line two\\n' '\\n' 'new paragraph' )", "class='placeholder'>((token))</span>&key=1\" ) == ( '<p style=\"Margin: 0 0 20px 0;", "25px; ' 'color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\"", "'</i>'}, '<i>1</i>, <i>2</i> and <i>3</i>'), ]) def test_formatted_list(items, kwargs, expected_output):", "not in en_dash_replacement_sequence @pytest.mark.parametrize('markup, expected_fixed', [ ( 'a', 'a', ),", "'col | col\\n' '----|----\\n' 'val | val\\n' ) == (", "'+ one\\n' '+ two\\n' '+ three\\n' ) == expected @pytest.mark.parametrize('markdown_function,", "\"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", ), ])", "en_dash assert non_breaking_space not in en_dash_replacement_sequence assert hyphen not in", "\"<to cancel daily cat facts reply 'cancel'>\" ) == (", "' 'style=\"Margin: 0 0 20px 0; border-left: 10px solid #BFC1C3;'", "*important*</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething *important*', ], )) def test_emphasis(markdown_function,", "line-height: 25px; color: #0B0C0C;\">something **important**</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething **important**',", "'* one\\n' '* two\\n' '* three\\n' ), ( # two", "\"gov.uk?q=\") ] ) def test_escaping_govuk_in_email_templates(template_content, expected): assert unlink_govuk_escaped(template_content) == expected", "( \"\"\"And I said, \"what about breakfast at Tiffany's\"?\"\"\", \"\"\"And", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>)' ), ) ]) def test_makes_links_out_of_URLs_in_context(input,", "'before<cr><cr><np>after', 'before<cr><np>after', ), ( 'before{}<np>after'.format('<cr>' * 4), 'before{}<np>after'.format('<cr>' * 3),", "'</p>' ).format(link)) @pytest.mark.parametrize('input, output', [ ( ( 'this is some", "expected @pytest.mark.parametrize('heading', ( '# heading', '#heading', )) @pytest.mark.parametrize( 'markdown_function, expected',", "( '<p>before</p>' '<p>after</p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin:", "def test_strip_and_remove_obscure_whitespace_only_removes_normal_whitespace_from_ends(): sentence = ' words \\n over multiple lines", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">after</p>' ) ], [ notify_plain_text_email_markdown,", "25px; color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">' 'https://example.com\"onclick=\"alert(\\'hi'", "assert strip_pipes('|a|b|c') == 'abc' def test_bleach_doesnt_try_to_make_valid_html_before_cleaning(): assert escape_html( \"<to cancel", "'<table role=\"presentation\" style=\"padding: 0 0 20px 0;\">' '<tr>' '<td style=\"font-family:", "text') == expected @pytest.mark.parametrize('heading', ( '# heading', '#heading', )) @pytest.mark.parametrize(", "markdown_function, expected_output ): assert markdown_function( 'https://example.com\\n' '\\n' 'Next paragraph' )", "noqa ), ] ) def test_URLs_get_escaped(url, expected_html, expected_html_in_template): assert notify_email_markdown(url)", "([1, 2, 3], {'before_each': '<i>', 'after_each': '</i>'}, '<i>1</i>, <i>2</i> and", "'\\n• three' ), ], )) def test_unordered_list(markdown, markdown_function, expected): assert", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">before</p>'", "Arial, sans-serif;\">' '<ul style=\"Margin: 0 0 0 20px; padding: 0;", "'<ol style=\"Margin: 0 0 0 20px; padding: 0; list-style-type: decimal;\">'", "'<h2>heading</h2>\\n' ], [ notify_email_markdown, ( '<h2 style=\"Margin: 0 0 20px", "notify_email_markdown, '<p style=\"Margin: 0 0 20px 0; font-size: 11pt; line-height:", "\"mailto:<EMAIL>\", \"<a href=\\\"https://example.com\\\">Example</a>\", ] ) def test_doesnt_make_links_out_of_invalid_urls(url): assert notify_email_markdown(url) ==", "([1, 2, 3], {'before_each': 'a', 'after_each': 'b'}, 'a1b, a2b and", "breakfast at Tiffany’s”?\"\"\", ), ( \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", \"\"\"", "27px; ' 'line-height: 35px; font-weight: bold; color: #0B0C0C;\">' 'heading' '</h2>'", "with a link http://example.com in the middle' ), ( 'this", "25px; color: #0B0C0C;\">+ two</p>' '<p style=\"Margin: 0 0 20px 0;", "( 'before<cr><cr><np>after', 'before<cr><np>after', ), ( 'before{}<np>after'.format('<cr>' * 4), 'before{}<np>after'.format('<cr>' *", "@pytest.mark.parametrize( \"template_content,expected\", [ (\"gov.uk\", u\"gov.\\u200Buk\"), (\"GOV.UK\", u\"GOV.\\u200BUK\"), (\"Gov.uk\", u\"Gov.\\u200Buk\"), (\"https://gov.uk\",", "email address line ‘three’ \"\"\") == (\"\"\" line one’s quote", "role=\"presentation\" style=\"padding: 0 0 20px 0;\">' '<tr>' '<td style=\"font-family: Helvetica,", "smart @pytest.mark.parametrize('nasty, nice', [ ( ( 'The en dash -", "template.prefix = prefix template.sender = None assert str(template) == expected", "[ notify_email_markdown, ( '<blockquote ' 'style=\"Margin: 0 0 20px 0;", "], [ notify_email_markdown, ( '<table role=\"presentation\" style=\"padding: 0 0 20px", "two\\n' '+ three\\n' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [", "== 'bar' @pytest.mark.parametrize('value', [ 'notifications-email', ' \\tnotifications-email \\x0c ', '\\rn\\u200Coti\\u200Dfi\\u200Bcati\\u2060ons-\\u180Eemai\\uFEFFl\\uFEFF',", "( '<p style=\"Margin: 0 0 20px 0; font-size: 11pt; line-height:", "‘three’ \"\"\") def test_strip_unsupported_characters(): assert strip_unsupported_characters(\"line one\\u2028line two\") == (\"line", "smart', [ ( \"\"\"And I said, \"what about breakfast at", "****** bar</p>' ], [ notify_plain_text_email_markdown, '\\n\\nfoo ****** bar', ], ))", "make_quotes_smart, replace_hyphens_with_en_dashes, tweak_dvla_list_markup, nl2li, strip_whitespace, strip_and_remove_obscure_whitespace, remove_smart_quotes_from_email_addresses, strip_unsupported_characters, normalise_whitespace )", "\"b\", \"a: b\"), (None, \"b\", \"b\"), ] ) def test_sms_message_adds_prefix(prefix,", "= '–' space = ' ' non_breaking_space = ' '", "color: #0B0C0C;\">variable called thing</p>' ], [ notify_plain_text_email_markdown, '\\n\\nvariable called thing',", "' 'color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">Example</a>' '</p>'", "expected_html, expected_html_in_template\", [ ( \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\"", "'already\\u0020–\\u0020correct', ), ( '2004-2008', '2004-2008', # no replacement ), (", "strip_unsupported_characters(\"line one\\u2028line two\") == (\"line oneline two\") def test_normalise_whitespace(): assert", "), ], )) def test_autolink(markdown_function, link, expected): assert markdown_function(link) ==", "'<li>two</li>\\n' '<li>three</li>\\n' '</ol>\\n' ) ], [ notify_email_markdown, ( '<table role=\"presentation\"", "def test_tweaking_dvla_list_markup(markup, expected_fixed): assert tweak_dvla_list_markup(markup) == expected_fixed def test_make_list_from_linebreaks(): assert", "strip_and_remove_obscure_whitespace, remove_smart_quotes_from_email_addresses, strip_unsupported_characters, normalise_whitespace ) from notifications_utils.template import ( HTMLEmailTemplate,", "0 0 20px; padding: 0; list-style-type: decimal;\">' '<li style=\"Margin: 5px", "'Hello Jo,\\n\\nThis is a message' ), ( '\\n \\t ,", "break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' ' in the middle' ), ),", "@pytest.mark.parametrize('markdown', ( ( # no space '*one\\n' '*two\\n' '*three\\n' ),", "0; list-style-type: decimal;\">' '<li style=\"Margin: 5px 0 5px; padding: 0", "`thing`' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>something", "'‘1’, ‘2’ foo ‘3’'), (['&'], {'before_each': '<i>', 'after_each': '</i>'}, '<i>&amp;</i>'),", "said, \"what about breakfast at Tiffany's\"?\"\"\", \"\"\"And I said, “what", "( 'before{}<np>after'.format('<cr>' * 4), 'before{}<np>after'.format('<cr>' * 3), ), ]) def", "]) def test_strip_whitespace(value): assert strip_whitespace(value) == 'bar' @pytest.mark.parametrize('value', [ 'notifications-email',", "'discussed in this section, indicating a parenthesis or ' 'pause", "' ' assert en_dash_replacement_sequence == space + en_dash assert non_breaking_space", "expected_html_in_template): assert notify_email_markdown(url) == ( '<p style=\"Margin: 0 0 20px", "'\\n' '\\nhttps://example.com' '\\n' '\\nNext paragraph' )), ]) def test_preserves_whitespace_when_making_links( markdown_function,", "expected', ( [ notify_letter_preview_markdown, ( '<p>' 'line one<br>' 'line two'", "test_makes_links_out_of_URLs_in_context(input, output): assert notify_email_markdown(input) == ( '<p style=\"Margin: 0 0", "style=\"Margin: 5px 0 5px; padding: 0 0 0 5px; font-size:", "'You’ve been invited to a service. Click this link:\\n' 'https://service.example.com/accept_invite/a1b2c3d4\\n'", "0 20px 0; padding: 0; font-size: 27px; ' 'line-height: 35px;", "\"url, expected_html, expected_html_in_template\", [ ( \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", \"\"\"<a style=\"word-wrap: break-word; color:", "def test_formatted_list_returns_markup(): assert isinstance(formatted_list([0]), Markup) def test_removing_dvla_markup(): assert strip_dvla_markup( (", "markdown_function('## inset text') == (expected) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "how to test this pass def test_sms_encode(): assert sms_encode('aàá…') ==", "= '-' en_dash = '–' space = ' ' non_breaking_space", "), )) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<ul>\\n' '<li>one</li>\\n'", "), ( 'before{}<np>after'.format('<cr>' * 4), 'before{}<np>after'.format('<cr>' * 3), ), ])", "'1.one\\n' '2.two\\n' '3.three\\n' ) == expected @pytest.mark.parametrize('markdown', ( ( #", "), ( 'double -- dash', 'double \\u2013 dash', ), (", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '<a style=\"word-wrap:", "11pt; line-height: 25px; color: #0B0C0C;\">inset text</p>' '</blockquote>' ) ], [", "three\\n' ), ( # two spaces '* one\\n' '* two\\n'", "( '\\n \\t , word', '\\n, word', ), ( 'bonjour", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">something **important**</p>' ], [ notify_plain_text_email_markdown,", "expected\", [ (\"a\", \"b\", \"a: b\"), (None, \"b\", \"b\"), ]", "- always with spaces in running text when, as '", "19px;' 'line-height: 25px; color: #0B0C0C;\">one</li>' '<li style=\"Margin: 5px 0 5px;", "[ ( \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>')\"\"\", #", "\"what about breakfast at Tiffany's\"?\"\"\", \"\"\"And I said, “what about", "expected_fixed): assert tweak_dvla_list_markup(markup) == expected_fixed def test_make_list_from_linebreaks(): assert nl2li( 'a\\n'", "test_strikethrough(markdown_function, expected): assert markdown_function('~~Strike~~') == expected def test_footnotes(): # Can’t", "test_removing_whitespace_before_full_stops(dirty, clean): assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dumb, smart', [ (", "), ( 'before<cr><cr><np>after', 'before<cr><np>after', ), ( 'before{}<np>after'.format('<cr>' * 4), 'before{}<np>after'.format('<cr>'", "== 'some words & some more <words>' def test_removing_pipes(): assert", "space + en_dash assert non_breaking_space not in en_dash_replacement_sequence assert hyphen", "url, 'subject': ''})) def test_HTML_template_has_URLs_replaced_with_links(): assert ( '<a style=\"word-wrap: break-word;", "color: #0B0C0C;\">+ two</p>' '<p style=\"Margin: 0 0 20px 0; font-size:", "(\"GOV.UK\", u\"GOV.\\u200BUK\"), (\"Gov.uk\", u\"Gov.\\u200Buk\"), (\"https://gov.uk\", \"https://gov.uk\"), (\"https://www.gov.uk\", \"https://www.gov.uk\"), (\"www.gov.uk\", \"www.gov.uk\"),", "assert markdown_function( '1. one\\n' '2. two\\n' '3. three\\n' ) ==", "'3.three\\n' ) == expected @pytest.mark.parametrize('markdown', ( ( # no space", "'#heading', )) @pytest.mark.parametrize( 'markdown_function, expected', ( [ notify_letter_preview_markdown, '<h2>heading</h2>\\n' ],", "and ‘3’'), ([1, 2, 3], {'prefix': 'foo', 'prefix_plural': 'bar'}, 'bar", "(\"gov.uk\", u\"gov.\\u200Buk\"), (\"GOV.UK\", u\"GOV.\\u200BUK\"), (\"Gov.uk\", u\"Gov.\\u200Buk\"), (\"https://gov.uk\", \"https://gov.uk\"), (\"https://www.gov.uk\", \"https://www.gov.uk\"),", "out how to test this pass def test_sms_encode(): assert sms_encode('aàá…')", "( '' ) @pytest.mark.parametrize('markdown_function, link, expected', ( [ notify_letter_preview_markdown, 'http://example.com',", "font-size: 11pt; line-height: 25px; ' 'color: #0B0C0C;\">' '<a style=\"word-wrap: break-word;", "0 0 5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">two</li>' '<li", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ three</p>'", "-- dash', 'double \\u2013 dash'), ] ) def test_subject_is_cleaned_up(subject, expected):", "u\"gov.\\u200Buk\"), (\"GOV.UK\", u\"GOV.\\u200BUK\"), (\"Gov.uk\", u\"Gov.\\u200Buk\"), (\"https://gov.uk\", \"https://gov.uk\"), (\"https://www.gov.uk\", \"https://www.gov.uk\"), (\"www.gov.uk\",", "\"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", ( '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">variable", "en_dash = '–' space = ' ' non_breaking_space = '", "20px 0;\">' '<tr>' '<td style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ol style=\"Margin:", "one\\n' '2. two\\n' '3. three\\n' ) == expected assert markdown_function(", "href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>’\"\"\", # noqa ), ] ) def test_URLs_get_escaped(url, expected_html, expected_html_in_template):", "http://example.com in the middle' ), ( 'this is some text", "\\n over multiple lines with \\ttabs\\t ' assert strip_and_remove_obscure_whitespace(sentence) ==", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">something **important**</p>'", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ two</p>' '<p style=\"Margin:", "#005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">' 'https://example.com\"onclick=\"alert(\\'hi' '</a>\\')' '</p>' ) ], [ notify_plain_text_email_markdown, 'http://example.com',", "'<tAb>' ) ) == 'some words & some more <words>'", "template.sender = None assert str(template) == expected def test_sms_preview_adds_newlines(): template", "assert expected in str(PlainTextEmailTemplate({'content': template_content, 'subject': ''})) assert expected in", "or ' 'pause \\u2013 and the spaced em dash both", "expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>before</p>' '<p>after</p>' )", "[ notify_plain_text_email_markdown, ( '\\n' '\\n• one' '\\n• two' '\\n• three'", "expected_output ): assert markdown_function( 'https://example.com\\n' '\\n' 'Next paragraph' ) ==", "expected', ( [ notify_letter_preview_markdown, ( '<p>inset text</p>' ) ], [", "-- dash', 'double \\u2013 dash', ), ( 'triple --- dash',", "'notifications-email', ' \\tnotifications-email \\x0c ', '\\rn\\u200Coti\\u200Dfi\\u200Bcati\\u2060ons-\\u180Eemai\\uFEFFl\\uFEFF', ]) def test_strip_and_remove_obscure_whitespace(value): assert", "'line-height: 25px; color: #0B0C0C;\">two</li>' '<li style=\"Margin: 5px 0 5px; padding:", "PlainTextEmailTemplate, SMSMessageTemplate, SMSPreviewTemplate ) @pytest.mark.parametrize( \"url\", [ \"http://example.com\", \"http://www.gov.uk/\", \"https://www.gov.uk/\",", "#0B0C0C;\">b</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\na' '\\n' '\\n================================================================='", "text' ), ], )) def test_level_2_header(markdown_function, expected): assert markdown_function('## inset", ") ) == 'some words & some more <words>' def", "'\\n2. two' '\\n3. three' ), ], )) def test_ordered_list(markdown_function, expected):", "expected_output', [ (notify_email_markdown, ( '<p style=\"Margin: 0 0 20px 0;", "( [ notify_letter_preview_markdown, '<p>Strike</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0", "35px; font-weight: bold; color: #0B0C0C;\">' 'heading' '</h2>' ) ], [", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">inset text</p>' ],", "11pt; line-height: 25px; color: #0B0C0C;\">' 'Next paragraph' '</p>' )), (notify_plain_text_email_markdown,", "make_quotes_smart(dumb) == smart @pytest.mark.parametrize('nasty, nice', [ ( ( 'The en", "'3. three\\n' ) == expected assert markdown_function( '1.one\\n' '2.two\\n' '3.three\\n'", "@pytest.mark.parametrize('dirty, clean', [ ( 'Hello ((name)) ,\\n\\nThis is a message',", ") == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>Example:", "== (expected) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>a</p>' '<div", "( [ notify_letter_preview_markdown, 'http://example.com', '<p><strong>example.com</strong></p>' ], [ notify_email_markdown, 'http://example.com', (", "hi', 'bonjour | hi', ), ]) def test_en_dashes(nasty, nice): assert", "HTMLEmailTemplate({'content': '', 'subject': subject}).subject @pytest.mark.parametrize( \"prefix, body, expected\", [ (\"a\",", "' bar ', \"\"\" \\t bar \"\"\", ' \\u180E\\u200B \\u200C", "‘2’ and ‘3’'), ([1], {'prefix': 'foo', 'prefix_plural': 'bar'}, 'foo ‘1’'),", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>'", "def test_make_list_from_linebreaks(): assert nl2li( 'a\\n' 'b\\n' 'c\\n' ) == (", "\\u200C bar \\u200D \\u2060\\uFEFF ', ]) def test_strip_whitespace(value): assert strip_whitespace(value)", "'</i>'}, '<i>&amp;</i>'), ([1, 2, 3], {'before_each': '<i>', 'after_each': '</i>'}, '<i>1</i>,", "href=\\\"https://example.com\\\">Example</a>\", ] ) def test_doesnt_make_links_out_of_invalid_urls(url): assert notify_email_markdown(url) == ( '<p", "'words \\n over multiple lines with \\ttabs' def test_remove_smart_quotes_from_email_addresses(): assert", ")) def test_codespan(markdown_function, expected): assert markdown_function( 'variable called `thing`' )", "@pytest.mark.parametrize( 'markdown_function, expected', ( [ notify_letter_preview_markdown, '<h2>heading</h2>\\n' ], [ notify_email_markdown,", "notify_email_markdown, notify_plain_text_email_markdown )) def test_image(markdown_function): assert markdown_function( '![alt text](http://example.com/image.png)' )", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' 'Next paragraph'", "quote first.o'<EMAIL> is someone’s email address line ‘three’ \"\"\") def", "two three\", marks=pytest.mark.xfail), ] ) def test_makes_links_out_of_URLs(url): link = '<a", "with a link ' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>'", "#0B0C0C;\">+ one</p>' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(url) def", "== expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>+ one</p><p>+ two</p><p>+", "line ‘three’ \"\"\") def test_strip_unsupported_characters(): assert strip_unsupported_characters(\"line one\\u2028line two\") ==", "\"\"\", ' \\u180E\\u200B \\u200C bar \\u200D \\u2060\\uFEFF ', ]) def", "'Next paragraph' ) == expected_output @pytest.mark.parametrize( \"template_content,expected\", [ (\"gov.uk\", u\"gov.\\u200Buk\"),", "'<li>three</li>\\n' '</ul>\\n' ) ], [ notify_email_markdown, ( '<table role=\"presentation\" style=\"padding:", "font-size: 19px; line-height: 25px;' '\">' '<p style=\"Margin: 0 0 20px", "line-height: 25px; color: #0B0C0C;\">+ three</p>' ), ], [ notify_plain_text_email_markdown, (", "@pytest.mark.parametrize('items, kwargs, expected_output', [ ([1], {}, '‘1’'), ([1, 2], {},", "def test_makes_links_out_of_URLs_in_context(input, output): assert notify_email_markdown(input) == ( '<p style=\"Margin: 0", "this section, indicating a parenthesis or ' 'pause - and", "], [ notify_plain_text_email_markdown, ( '\\n' '\\na' '\\n' '\\n=================================================================' '\\n' '\\nb'", "link = '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"{}\">{}</a>'.format(url, url) assert", "), ], )) def test_pluses_dont_render_as_lists(markdown_function, expected): assert markdown_function( '+ one\\n'", "'\\nhttp://example.com' ), ], )) def test_autolink(markdown_function, link, expected): assert markdown_function(link)", "prefix template.sender = None assert str(template) == expected def test_sms_preview_adds_newlines():", "[ (\"a\", \"b\", \"a: b\"), (None, \"b\", \"b\"), ] )", "def test_unicode_dash_lookup(): en_dash_replacement_sequence = '\\u0020\\u2013' hyphen = '-' en_dash =", "( '# heading', '#heading', )) @pytest.mark.parametrize( 'markdown_function, expected', ( [", "' 'discussed in this section, indicating a parenthesis or '", "class=\"page-break\">&nbsp;</div>' '<p>b</p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin: 0", "[ notify_plain_text_email_markdown, ( '\\n' '\\nline one' '\\nline two' '\\n' '\\nnew", "assert ( '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://service.example.com/accept_invite/a1b2c3d4\">' 'https://service.example.com/accept_invite/a1b2c3d4' '</a>'", ")) def test_link(markdown_function, expected): assert markdown_function( '[Example](http://example.com)' ) == expected", "line-height: 25px; color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com/?token=\">'", "), ( 'this link is in brackets ' '(<a style=\"word-wrap:", "11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(url) def test_handles_placeholders_in_urls():", "[ notify_email_markdown, ( '<table role=\"presentation\" style=\"padding: 0 0 20px 0;\">'", "'<div class=\"page-break\">&nbsp;</div>' '<p>b</p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin:", "], )) def test_hrule(markdown_function, expected): assert markdown_function('a\\n\\n***\\n\\nb') == expected assert", "#0B0C0C;\">new paragraph</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nline one'", "( 'this link is in brackets ' '(<a style=\"word-wrap: break-word;", "= ' ' non_breaking_space = ' ' assert en_dash_replacement_sequence ==", "'\\nafter' ), ], )) def test_multiple_newlines_get_truncated(markdown_function, expected): assert markdown_function( 'before\\n\\n\\n\\n\\n\\nafter'", "hi', ), ]) def test_en_dashes(nasty, nice): assert replace_hyphens_with_en_dashes(nasty) == nice", "[ notify_letter_preview_markdown, ( '<ul>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ul>\\n' ) ],", "@pytest.mark.parametrize( \"prefix, body, expected\", [ (\"a\", \"b\", \"a: b\"), (None,", "‘1’, ‘2’ and ‘3’'), ([1], {'prefix': 'foo', 'prefix_plural': 'bar'}, 'foo", "is some text with a link ' '<a style=\"word-wrap: break-word;", "test_handles_placeholders_in_urls(): assert notify_email_markdown( \"http://example.com/?token=<span class='placeholder'>((token))</span>&key=1\" ) == ( '<p style=\"Margin:", "'style=\"Margin: 0 0 20px 0; border-left: 10px solid #BFC1C3;' 'padding:", "about breakfast at Tiffany’s”?\"\"\", ), ( \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\",", "markdown_function( 'col | col\\n' '----|----\\n' 'val | val\\n' ) ==", "example URL\">' 'Example' '</a>' '</p>' ) ], [ notify_plain_text_email_markdown, (", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">b</p>' ) ],", "], [ notify_email_markdown, 'print(\"hello\")' ], [ notify_plain_text_email_markdown, 'print(\"hello\")' ], )", "remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dirty, clean', [ ( 'Hello ((name)) .\\n\\nThis", "def test_remove_smart_quotes_from_email_addresses(): assert remove_smart_quotes_from_email_addresses(\"\"\" line one’s quote first.o’<EMAIL> is someone’s", "== 'notifications-email' def test_strip_and_remove_obscure_whitespace_only_removes_normal_whitespace_from_ends(): sentence = ' words \\n over", "'http://example.com', '<p><strong>example.com</strong></p>' ], [ notify_email_markdown, 'http://example.com', ( '<p style=\"Margin: 0", "markdown_function(heading) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>inset text</p>'", "example URL\")' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "a normal space character 'already\\u0020–\\u0020correct', ), ( '2004-2008', '2004-2008', #", "25px; color: #0B0C0C;\">after</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nbefore'", "#0B0C0C;\">line one<br />' 'line two</p>' '<p style=\"Margin: 0 0 20px", "is a message', 'Hello Jo,\\n\\nThis is a message' ), (", "noqa \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>’\"\"\", # noqa ),", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ three</p>' ),", "), ]) def test_en_dashes(nasty, nice): assert replace_hyphens_with_en_dashes(nasty) == nice def", "always with spaces in running text when, as ' 'discussed", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ one</p>' '<p", "' non_breaking_space = ' ' assert en_dash_replacement_sequence == space +", "def test_strikethrough(markdown_function, expected): assert markdown_function('~~Strike~~') == expected def test_footnotes(): #", "#005ea5;\" href=\"http://example.com\">http://example.com</a>' '</p>' ) ], [ notify_email_markdown, \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", ( '<p", "more <words>' def test_removing_pipes(): assert strip_pipes('|a|b|c') == 'abc' def test_bleach_doesnt_try_to_make_valid_html_before_cleaning():", "bar \\u200D \\u2060\\uFEFF ', ]) def test_strip_whitespace(value): assert strip_whitespace(value) ==", "notify_email_markdown, ( '<blockquote ' 'style=\"Margin: 0 0 20px 0; border-left:", "assert make_quotes_smart(dumb) == smart @pytest.mark.parametrize('nasty, nice', [ ( ( 'The", "break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>’\"\"\", # noqa ), ] ) def", "sans-serif;\">' '<ul style=\"Margin: 0 0 0 20px; padding: 0; list-style-type:", "assert non_breaking_space not in en_dash_replacement_sequence assert hyphen not in en_dash_replacement_sequence", "\"https://www.gov.uk\"), (\"www.gov.uk\", \"www.gov.uk\"), (\"gov.uk/register-to-vote\", \"gov.uk/register-to-vote\"), (\"gov.uk?q=\", \"gov.uk?q=\") ] ) def", "multiple lines with \\ttabs' def test_remove_smart_quotes_from_email_addresses(): assert remove_smart_quotes_from_email_addresses(\"\"\" line one’s", "assert markdown_function( 'foo ****** bar' ) == expected @pytest.mark.parametrize('markdown_function', (", "color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">' 'https://example.com\"onclick=\"alert(\\'hi' '</a>\\')' '</p>' ) ], [ notify_plain_text_email_markdown,", "break-word; color: #005ea5;\" href=\"http://example.com/?token=\">' 'http://example.com/?token=' '</a>' '<span class=\\'placeholder\\'>((token))</span>&amp;key=1' '</p>' )", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(expected_html) assert", "'<td style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ol style=\"Margin: 0 0 0", "in this section, indicating a parenthesis or ' 'pause \\u2013", "#0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' '</p>' ) ],", "over the unspaced em dash. ' ), ( 'The en", "== ( '' ) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, (", "0; font-size: 11pt; line-height: 25px; ' 'color: #0B0C0C;\">' '<a style=\"word-wrap:", "'• two\\n' '• three\\n' ), )) @pytest.mark.parametrize('markdown_function, expected', ( [", "[ notify_letter_preview_markdown, 'print(\"hello\")' ], [ notify_email_markdown, 'print(\"hello\")' ], [ notify_plain_text_email_markdown,", "<filename>tests/test_formatters.py import pytest from flask import Markup from notifications_utils.formatters import", ")) def test_pluses_dont_render_as_lists(markdown_function, expected): assert markdown_function( '+ one\\n' '+ two\\n'", "'\\n' '\\nExample (An example URL): http://example.com' ), ], )) def", "#0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">Example</a>' '</p>' ) ],", "notify_letter_preview_markdown, 'http://example.com', '<p><strong>example.com</strong></p>' ], [ notify_email_markdown, 'http://example.com', ( '<p style=\"Margin:", ") def test_escaping_govuk_in_email_templates(template_content, expected): assert unlink_govuk_escaped(template_content) == expected assert expected", "\"www.example.com\", \"ftp://example.com\", \"<EMAIL>\", \"mailto:<EMAIL>\", \"<a href=\\\"https://example.com\\\">Example</a>\", ] ) def test_doesnt_make_links_out_of_invalid_urls(url):", "color: #0B0C0C;\">b</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\na' '\\n'", "( ( 'The en dash - always with spaces in", "line-height: 25px; color: #0B0C0C;\">variable called thing</p>' ], [ notify_plain_text_email_markdown, '\\n\\nvariable", "#0B0C0C;\">' '{}' '</p>' ).format(expected_html) assert expected_html_in_template in str(HTMLEmailTemplate({'content': url, 'subject':", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<ol>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n'", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">before</p>' '<p", "'this link is in brackets ' '(<a style=\"word-wrap: break-word; color:", "0 0 0 5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">three</li>'", "expected): assert markdown_function( '[Example](http://example.com)' ) == expected @pytest.mark.parametrize('markdown_function, expected', (", "(\"https://www.gov.uk\", \"https://www.gov.uk\"), (\"www.gov.uk\", \"www.gov.uk\"), (\"gov.uk/register-to-vote\", \"gov.uk/register-to-vote\"), (\"gov.uk?q=\", \"gov.uk?q=\") ] )", "5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">three</li>' '</ol>' '</td>' '</tr>'", "{'before_each': '<i>', 'after_each': '</i>'}, '<i>&amp;</i>'), ([1, 2, 3], {'before_each': '<i>',", "[ notify_plain_text_email_markdown, '\\n\\nsomething *important*', ], )) def test_emphasis(markdown_function, expected): assert", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">line", "test_makes_links_out_of_URLs(url): link = '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"{}\">{}</a>'.format(url, url)", "line-height: 25px; color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">'", "font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">three</li>' '</ul>' '</td>' '</tr>' '</table>'", "href=\"http://example.com\">http://example.com</a>)' ), ) ]) def test_makes_links_out_of_URLs_in_context(input, output): assert notify_email_markdown(input) ==", "test_strip_and_remove_obscure_whitespace(value): assert strip_and_remove_obscure_whitespace(value) == 'notifications-email' def test_strip_and_remove_obscure_whitespace_only_removes_normal_whitespace_from_ends(): sentence = '", "'aàa...' @pytest.mark.parametrize('items, kwargs, expected_output', [ ([1], {}, '‘1’'), ([1, 2],", "break-word; color: #005ea5;\" href=\"http://example.com\">Example</a>' '</p>' ) ], [ notify_plain_text_email_markdown, (", "style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ul style=\"Margin: 0 0 0 20px;", "markdown_function( '1. one\\n' '2. two\\n' '3. three\\n' ) == expected", "Jo .\\n\\nThis is a message', 'Hello Jo.\\n\\nThis is a message'", "import pytest from flask import Markup from notifications_utils.formatters import (", "[ notify_plain_text_email_markdown, ( '\\n' '\\n' '\\nheading' '\\n-----------------------------------------------------------------' ), ], )", "'</td>' '</tr>' '</table>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\n1.", "'* one\\n' '* two\\n' '* three\\n' ), ( # tab", "[ notify_plain_text_email_markdown, ( '\\n' '\\nbefore' '\\n' '\\nafter' ), ], ))", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"{}\">{}</a>'.format(url, url) assert (notify_email_markdown(url) == (", "( 'this is some text with a link ' '<a", "'‘1’ and ‘2’'), ([1, 2, 3], {}, '‘1’, ‘2’ and", "test_removing_dvla_markup(): assert strip_dvla_markup( ( 'some words & some more <words>'", "Jo.\\n\\nThis is a message' ), ( '\\n \\t . word',", "u\"GOV.\\u200BUK\"), (\"Gov.uk\", u\"Gov.\\u200Buk\"), (\"https://gov.uk\", \"https://gov.uk\"), (\"https://www.gov.uk\", \"https://www.gov.uk\"), (\"www.gov.uk\", \"www.gov.uk\"), (\"gov.uk/register-to-vote\",", "), ( # two spaces '* one\\n' '* two\\n' '*", "indicating a parenthesis or ' 'pause - and the spaced", "( ( 'this is some text with a link http://example.com", "not in en_dash_replacement_sequence assert hyphen not in en_dash_replacement_sequence @pytest.mark.parametrize('markup, expected_fixed',", "( '\\n' '\\nline one' '\\nline two' '\\n' '\\nnew paragraph' ),", "'<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com\">' 'https://example.com' '</a>' '</p>' '<p", "test_remove_smart_quotes_from_email_addresses(): assert remove_smart_quotes_from_email_addresses(\"\"\" line one’s quote first.o’<EMAIL> is someone’s email", "style=\"border: 0; height: 1px; background: #BFC1C3; Margin: 30px 0 30px", "25px; color: #0B0C0C;\">one</li>' '<li style=\"Margin: 5px 0 5px; padding: 0", "0;\">' '<tr>' '<td style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ul style=\"Margin: 0", "url) assert (notify_email_markdown(url) == ( '<p style=\"Margin: 0 0 20px", "assert strip_and_remove_obscure_whitespace(sentence) == 'words \\n over multiple lines with \\ttabs'", "'line-height: 25px; color: #0B0C0C;\">one</li>' '<li style=\"Margin: 5px 0 5px; padding:", "assert '<br>' in str(template) @pytest.mark.parametrize( 'markdown_function, expected', ( [ notify_letter_preview_markdown,", "], ) ) def test_level_1_header(markdown_function, heading, expected): assert markdown_function(heading) ==", "), ), ( ( 'this link is in brackets (http://example.com)'", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ one</p>'", "= SMSMessageTemplate({'content': body}) template.prefix = prefix template.sender = None assert", "test_HTML_template_has_URLs_replaced_with_links(): assert ( '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://service.example.com/accept_invite/a1b2c3d4\">' 'https://service.example.com/accept_invite/a1b2c3d4'", "#005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>‘)\"\"\", # noqa ), ( \"\"\"https://example.com\"style='text-decoration:blink'\"\"\", \"\"\"<a style=\"word-wrap: break-word;", "color: #0B0C0C;\">' 'Next paragraph' '</p>' )), (notify_plain_text_email_markdown, ( '\\n' '\\nhttps://example.com'", "'\\n, word', ), ( 'bonjour | hi', 'bonjour | hi',", "# dash as bullet '- one\\n' '- two\\n' '- three\\n'", ") == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>Strike</p>' ],", "25px; color: #0B0C0C;\">' '{}' '</p>' ).format(link)) @pytest.mark.parametrize('input, output', [ (", "], )) def test_link_with_title(markdown_function, expected): assert markdown_function( '[Example](http://example.com \"An example", "one</p>' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt; line-height:", "'\\ninset text' ), ], )) def test_block_quote(markdown_function, expected): assert markdown_function('^", "a message' ), ( '\\n \\t , word', '\\n, word',", "\"gov.uk/register-to-vote\"), (\"gov.uk?q=\", \"gov.uk?q=\") ] ) def test_escaping_govuk_in_email_templates(template_content, expected): assert unlink_govuk_escaped(template_content)", "'* three\\n' ), ( # dash as bullet '- one\\n'", "'cancel'&gt;\" ) @pytest.mark.parametrize('dirty, clean', [ ( 'Hello ((name)) ,\\n\\nThis is", "| hi', 'bonjour | hi', ), ]) def test_en_dashes(nasty, nice):", "color: #0B0C0C;\">new paragraph</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nline", "'\\n' '\\nafter' ), ], )) def test_multiple_newlines_get_truncated(markdown_function, expected): assert markdown_function(", "#0B0C0C;\">' '{}' '</p>' ).format(output) @pytest.mark.parametrize( \"url\", [ \"example.com\", \"www.example.com\", \"ftp://example.com\",", "line-height: 25px; color: #0B0C0C;\">' 'Next paragraph' '</p>' )), (notify_plain_text_email_markdown, (", "heading, expected): assert markdown_function(heading) == expected @pytest.mark.parametrize('markdown_function, expected', ( [", "== expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_email_markdown, '<p style=\"Margin: 0", "sans-serif;\">' '<ol style=\"Margin: 0 0 0 20px; padding: 0; list-style-type:", "# no space '*one\\n' '*two\\n' '*three\\n' ), ( # single", "line-height: 25px; color: #0B0C0C;\">new paragraph</p>' ) ], [ notify_plain_text_email_markdown, (", "SMSMessageTemplate, SMSPreviewTemplate ) @pytest.mark.parametrize( \"url\", [ \"http://example.com\", \"http://www.gov.uk/\", \"https://www.gov.uk/\", \"http://service.gov.uk\",", "color: #0B0C0C;\">before</p>' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "color: #0B0C0C;\">inset text</p>' ], [ notify_plain_text_email_markdown, ( '\\n' '\\ninset text'", "( '\\n' '\\nhttps://example.com' '\\n' '\\nNext paragraph' )), ]) def test_preserves_whitespace_when_making_links(", "' 'technical advantage over the unspaced em dash. ' ),", "---- dash', 'quadruple ---- dash', ), ( 'em — dash',", "[ 'notifications-email', ' \\tnotifications-email \\x0c ', '\\rn\\u200Coti\\u200Dfi\\u200Bcati\\u2060ons-\\u180Eemai\\uFEFFl\\uFEFF', ]) def test_strip_and_remove_obscure_whitespace(value):", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">line one<br", "str(HTMLEmailTemplate({'content': template_content, 'subject': ''})) @pytest.mark.parametrize( \"subject,expected\", [ (\"bonjour | hi\",", "‘3’'), ([1], {'prefix': 'foo', 'prefix_plural': 'bar'}, 'foo ‘1’'), ([1, 2,", "cancel daily cat facts reply 'cancel'>\" ) == ( \"&lt;to", "#005ea5;\" href=\"https://example.com\">' 'https://example.com' '</a>' '</p>' '<p style=\"Margin: 0 0 20px", "'quadruple ---- dash', 'quadruple ---- dash', ), ( 'em —", "'<li>two</li>\\n' '<li>three</li>\\n' '</ul>\\n' ) ], [ notify_email_markdown, ( '<table role=\"presentation\"", "Markup from notifications_utils.formatters import ( unlink_govuk_escaped, notify_email_markdown, notify_letter_preview_markdown, notify_plain_text_email_markdown, sms_encode,", "'</a>' '<span class=\\'placeholder\\'>((token))</span>&amp;key=1' '</p>' ) @pytest.mark.parametrize( \"url, expected_html, expected_html_in_template\", [", "19px; line-height: 25px;' '\">' '<p style=\"Margin: 0 0 20px 0;", "'<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"{}\">{}</a>'.format(url, url) assert (notify_email_markdown(url) ==", "message' ), ( '\\n \\t . word', '\\n. word', ),", "kwargs, expected_output): assert formatted_list(items, **kwargs) == expected_output def test_formatted_list_returns_markup(): assert", "href=\"https://service.example.com/accept_invite/a1b2c3d4\">' 'https://service.example.com/accept_invite/a1b2c3d4' '</a>' ) in str(HTMLEmailTemplate({'content': ( 'You’ve been invited", "], [ notify_plain_text_email_markdown, ( '\\n\\n+ one' '\\n\\n+ two' '\\n\\n+ three'", "message', 'Hello ((name)).\\n\\nThis is a message' ), ( 'Hello Jo", "[ notify_plain_text_email_markdown, '\\n\\nvariable called thing', ], )) def test_codespan(markdown_function, expected):", "expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>variable called thing</p>' ],", "notify_email_markdown, ( '<table role=\"presentation\" style=\"padding: 0 0 20px 0;\">' '<tr>'", "color: #0B0C0C;\">' '{}' '</p>' ).format(output) @pytest.mark.parametrize( \"url\", [ \"example.com\", \"www.example.com\",", "markdown_function( 'line one\\n' 'line two\\n' '\\n' 'new paragraph' ) ==", "b\"), (None, \"b\", \"b\"), ] ) def test_sms_message_adds_prefix(prefix, body, expected):", ")) def test_block_quote(markdown_function, expected): assert markdown_function('^ inset text') == expected", "assert markdown_function( '+ one\\n' '+ two\\n' '+ three\\n' ) ==", "'\\na' '\\n' '\\n=================================================================' '\\n' '\\nb' ), ], )) def test_hrule(markdown_function,", "( '<ul>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ul>\\n' ) ], [ notify_email_markdown,", ". word', '\\n. word', ), ]) def test_removing_whitespace_before_full_stops(dirty, clean): assert", "], [ notify_plain_text_email_markdown, 'http://example.com', ( '\\n' '\\nhttp://example.com' ), ], ))", "expected in str(HTMLEmailTemplate({'content': template_content, 'subject': ''})) @pytest.mark.parametrize( \"subject,expected\", [ (\"bonjour", "( '<h2 style=\"Margin: 0 0 20px 0; padding: 0; font-size:", "'Next paragraph' '</p>' )), (notify_plain_text_email_markdown, ( '\\n' '\\nhttps://example.com' '\\n' '\\nNext", "notify_email_markdown, \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", ( '<p style=\"Margin: 0 0 20px 0; font-size:", "# noqa ), ] ) def test_URLs_get_escaped(url, expected_html, expected_html_in_template): assert", "], [ notify_plain_text_email_markdown, '\\n\\nfoo ****** bar', ], )) def test_nested_emphasis(markdown_function,", "dash as bullet '- one\\n' '- two\\n' '- three\\n' ),", "20px 0;\">' '<tr>' '<td style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ul style=\"Margin:", ") == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_email_markdown, '<p style=\"Margin:", "#0B0C0C;\">before</p>' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt; line-height:", "'<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com/?token=\">' 'http://example.com/?token=' '</a>' '<span class=\\'placeholder\\'>((token))</span>&amp;key=1'", "color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>')\"\"\", # noqa \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\"", "thing</p>' ], [ notify_plain_text_email_markdown, '\\n\\nvariable called thing', ], )) def", "notify_letter_preview_markdown, '<h2>heading</h2>\\n' ], [ notify_email_markdown, ( '<h2 style=\"Margin: 0 0", "color: #0B0C0C;\">' '{}' '</p>' ).format(link)) @pytest.mark.parametrize('input, output', [ ( (", "'color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">Example</a>' '</p>' )", "), ], )) def test_paragraphs(markdown_function, expected): assert markdown_function( 'line one\\n'", "first.o'<EMAIL> is someone’s email address line ‘three’ \"\"\") def test_strip_unsupported_characters():", "two\\n' '• three\\n' ), )) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "'- one\\n' '- two\\n' '- three\\n' ), pytest.param(( # plus", "three</p>', ], [ notify_email_markdown, ( '<p style=\"Margin: 0 0 20px", "'Hello Jo.\\n\\nThis is a message' ), ( '\\n \\t .", ")) def test_unordered_list(markdown, markdown_function, expected): assert markdown_function(markdown) == expected @pytest.mark.parametrize('markdown_function,", "'<p>before</p>' '<p>after</p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin: 0", "\\u2013 dash'), ] ) def test_subject_is_cleaned_up(subject, expected): assert expected ==", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://service.example.com/accept_invite/a1b2c3d4\">' 'https://service.example.com/accept_invite/a1b2c3d4' '</a>' ) in str(HTMLEmailTemplate({'content':", "# bullet as bullet '• one\\n' '• two\\n' '• three\\n'", "color: #0B0C0C;\">+ one</p>' '<p style=\"Margin: 0 0 20px 0; font-size:", "color: #005ea5;\" href=\"http://example.com\">Example</a>' '</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n'", "color: #005ea5;\" href=\"{}\">{}</a>'.format(url, url) assert (notify_email_markdown(url) == ( '<p style=\"Margin:", "0 20px; padding: 0; list-style-type: disc;\">' '<li style=\"Margin: 5px 0", "( # dash as bullet '- one\\n' '- two\\n' '-", "http://example.com' ), ], )) def test_link_with_title(markdown_function, expected): assert markdown_function( '[Example](http://example.com", "#005ea5;\" href=\"http://example.com\">http://example.com</a>)' ), ) ]) def test_makes_links_out_of_URLs_in_context(input, output): assert notify_email_markdown(input)", "@pytest.mark.parametrize('markdown_function, link, expected', ( [ notify_letter_preview_markdown, 'http://example.com', '<p><strong>example.com</strong></p>' ], [", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">before</p>' '<p style=\"Margin: 0 0", "1px; background: #BFC1C3; Margin: 30px 0 30px 0;\">' '<p style=\"Margin:", "in str(PlainTextEmailTemplate({'content': template_content, 'subject': ''})) assert expected in str(HTMLEmailTemplate({'content': template_content,", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">b</p>' )", "'<p style=\"Margin: 0 0 20px 0; font-size: 11pt; line-height: 25px;", "] ) def test_doesnt_make_links_out_of_invalid_urls(url): assert notify_email_markdown(url) == ( '<p style=\"Margin:", ") ], [ notify_plain_text_email_markdown, ( '\\n' '\\ninset text' ), ],", "def test_escaping_govuk_in_email_templates(template_content, expected): assert unlink_govuk_escaped(template_content) == expected assert expected in", "and ‘2’'), ([1, 2, 3], {}, '‘1’, ‘2’ and ‘3’'),", "line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(output) @pytest.mark.parametrize( \"url\", [", "test_hrule(markdown_function, expected): assert markdown_function('a\\n\\n***\\n\\nb') == expected assert markdown_function('a\\n\\n---\\n\\nb') == expected", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>Strike</p>' ], [ notify_email_markdown, '<p", "{'prefix': 'foo', 'prefix_plural': 'bar'}, 'bar ‘1’, ‘2’ and ‘3’'), ([1],", "expected): assert unlink_govuk_escaped(template_content) == expected assert expected in str(PlainTextEmailTemplate({'content': template_content,", "11pt; line-height: 25px; color: #0B0C0C;\">variable called thing</p>' ], [ notify_plain_text_email_markdown,", "some more <words>' '<cr><h1><h2><p><normal><op><np><bul><tab>' '<CR><H1><H2><P><NORMAL><OP><NP><BUL><TAB>' '<tAb>' ) ) == 'some", "[ ( 'a', 'a', ), ( 'before<p><cr><p><cr>after', 'before<p><cr>after', ), (", "\"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>')\"\"\", # noqa \"\"\"<a", "), pytest.param(( # plus as bullet '+ one\\n' '+ two\\n'", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">after</p>' )", "**important**', ], )) def test_double_emphasis(markdown_function, expected): assert markdown_function( 'something **important**'", "\\u0020 is a normal space character 'already\\u0020–\\u0020correct', ), ( '2004-2008',", "'<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">' 'https://example.com\"onclick=\"alert(\\'hi' '</a>\\')' '</p>' )", "pass def test_sms_encode(): assert sms_encode('aàá…') == 'aàa...' @pytest.mark.parametrize('items, kwargs, expected_output',", "test_subject_is_cleaned_up(subject, expected): assert expected == HTMLEmailTemplate({'content': '', 'subject': subject}).subject @pytest.mark.parametrize(", ") ], [ notify_email_markdown, ( '<blockquote ' 'style=\"Margin: 0 0", "a message', 'Hello ((name)).\\n\\nThis is a message' ), ( 'Hello", "#0B0C0C;\">' '{}' '</p>' ).format(link)) @pytest.mark.parametrize('input, output', [ ( ( 'this", "), ] ) def test_URLs_get_escaped(url, expected_html, expected_html_in_template): assert notify_email_markdown(url) ==", "test_pluses_dont_render_as_lists(markdown_function, expected): assert markdown_function( '+ one\\n' '+ two\\n' '+ three\\n'", ")) def test_strikethrough(markdown_function, expected): assert markdown_function('~~Strike~~') == expected def test_footnotes():", "strip_and_remove_obscure_whitespace(sentence) == 'words \\n over multiple lines with \\ttabs' def", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">a</p>' '<hr", "line-height: 25px; color: #0B0C0C;\">line one<br />' 'line two</p>' '<p style=\"Margin:", "line-height: 25px; color: #0B0C0C;\">something *important*</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething *important*',", "'• one\\n' '• two\\n' '• three\\n' ), )) @pytest.mark.parametrize('markdown_function, expected',", "@pytest.mark.parametrize('dirty, clean', [ ( 'Hello ((name)) .\\n\\nThis is a message',", "\"a: b\"), (None, \"b\", \"b\"), ] ) def test_sms_message_adds_prefix(prefix, body,", "color: #0B0C0C;\">one</li>' '<li style=\"Margin: 5px 0 5px; padding: 0 0", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' 'Next", "Helvetica, Arial, sans-serif;\">' '<ul style=\"Margin: 0 0 0 20px; padding:", "'\\n\\nfoo ****** bar', ], )) def test_nested_emphasis(markdown_function, expected): assert markdown_function(", "and a3b'), ([1, 2, 3], {'conjunction': 'foo'}, '‘1’, ‘2’ foo", "lines with \\ttabs\\t ' assert strip_and_remove_obscure_whitespace(sentence) == 'words \\n over", "] ) def test_subject_is_cleaned_up(subject, expected): assert expected == HTMLEmailTemplate({'content': '',", "'variable called `thing`' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [", "color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com/?token=\">' 'http://example.com/?token=' '</a>'", "( '\\n' '\\ninset text' ), ], )) def test_block_quote(markdown_function, expected):", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">something *important*</p>'", "20px; padding: 0; list-style-type: decimal;\">' '<li style=\"Margin: 5px 0 5px;", "], ) ) def test_block_code(markdown_function, expected): assert markdown_function('```\\nprint(\"hello\")\\n```') == expected", "0; height: 1px; background: #BFC1C3; Margin: 30px 0 30px 0;\">'", "25px; color: #0B0C0C;\">line one<br />' 'line two</p>' '<p style=\"Margin: 0", "== clean @pytest.mark.parametrize('dirty, clean', [ ( 'Hello ((name)) .\\n\\nThis is", "10px solid #BFC1C3;' 'padding: 15px 0 0.1px 15px; font-size: 19px;", "line-height: 25px;' '\">' '<p style=\"Margin: 0 0 20px 0; font-size:", ") ) def test_level_1_header(markdown_function, heading, expected): assert markdown_function(heading) == expected", "expected): assert markdown_function( 'before\\n\\n\\n\\n\\n\\nafter' ) == expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown,", "two\\n' '* three\\n' ), ( # tab '* one\\n' '*", "]) def test_smart_quotes(dumb, smart): assert make_quotes_smart(dumb) == smart @pytest.mark.parametrize('nasty, nice',", "( 'before<p><cr><p><cr>after', 'before<p><cr>after', ), ( 'before<cr><cr><np>after', 'before<cr><np>after', ), ( 'before{}<np>after'.format('<cr>'", "[ (\"bonjour | hi\", \"bonjour | hi\"), (\"bonjour .\", \"bonjour.\"),", "\"http://service.gov.uk/blah.ext?q=a%20b%20c&order=desc#fragment\", pytest.param(\"http://service.gov.uk/blah.ext?q=one two three\", marks=pytest.mark.xfail), ] ) def test_makes_links_out_of_URLs(url): link", "', '\\rn\\u200Coti\\u200Dfi\\u200Bcati\\u2060ons-\\u180Eemai\\uFEFFl\\uFEFF', ]) def test_strip_and_remove_obscure_whitespace(value): assert strip_and_remove_obscure_whitespace(value) == 'notifications-email' def", "link ' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' ' in", "def test_URLs_get_escaped(url, expected_html, expected_html_in_template): assert notify_email_markdown(url) == ( '<p style=\"Margin:", "'+ three\\n' ), marks=pytest.mark.xfail(raises=AssertionError)), ( # bullet as bullet '•", "('double -- dash', 'double \\u2013 dash'), ] ) def test_subject_is_cleaned_up(subject,", "\\u2013 always with spaces in running text when, as '", "11pt; line-height: 25px; color: #0B0C0C;\">something **important**</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething", "notify_letter_preview_markdown, '<p>inset text</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0", "color: #0B0C0C;\">+ three</p>' ), ], [ notify_plain_text_email_markdown, ( '\\n\\n+ one'", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ three</p>' ), ], [", "'some words & some more <words>' '<cr><h1><h2><p><normal><op><np><bul><tab>' '<CR><H1><H2><P><NORMAL><OP><NP><BUL><TAB>' '<tAb>' )", "'----|----\\n' 'val | val\\n' ) == ( '' ) @pytest.mark.parametrize('markdown_function,", "], [ notify_plain_text_email_markdown, ( '\\n' '\\ninset text' ), ], ))", "color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com\">' 'https://example.com' '</a>'", ")) @pytest.mark.parametrize( 'markdown_function, expected', ( [ notify_letter_preview_markdown, '<h2>heading</h2>\\n' ], [", "markdown_function(markdown) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>+ one</p><p>+", "line-height: 25px; ' 'color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\"", "[ notify_plain_text_email_markdown, ( '\\n' '\\nExample: http://example.com' ), ], )) def", "assert markdown_function(heading) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>inset", "expected): assert markdown_function('~~Strike~~') == expected def test_footnotes(): # Can’t work", "SMSMessageTemplate({'content': body}) template.prefix = prefix template.sender = None assert str(template)", "def test_sms_encode(): assert sms_encode('aàá…') == 'aàa...' @pytest.mark.parametrize('items, kwargs, expected_output', [", "0 5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">three</li>' '</ol>' '</td>'", "'https://service.example.com/accept_invite/a1b2c3d4' '</a>' ) in str(HTMLEmailTemplate({'content': ( 'You’ve been invited to", "] ) def test_URLs_get_escaped(url, expected_html, expected_html_in_template): assert notify_email_markdown(url) == (", "notify_plain_text_email_markdown, 'print(\"hello\")' ], ) ) def test_block_code(markdown_function, expected): assert markdown_function('```\\nprint(\"hello\")\\n```')", "== smart @pytest.mark.parametrize('nasty, nice', [ ( ( 'The en dash", "I said, \"what about breakfast at Tiffany's\"?\"\"\", \"\"\"And I said,", "'* two\\n' '* three\\n' ), ( # two spaces '*", "''})) @pytest.mark.parametrize( \"subject,expected\", [ (\"bonjour | hi\", \"bonjour | hi\"),", "sentence = ' words \\n over multiple lines with \\ttabs\\t", "@pytest.mark.parametrize('heading', ( '# heading', '#heading', )) @pytest.mark.parametrize( 'markdown_function, expected', (", "one\\n' '* two\\n' '* three\\n' ), ( # dash as", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ two</p>' '<p", "service. Click this link:\\n' 'https://service.example.com/accept_invite/a1b2c3d4\\n' '\\n' 'Thanks\\n' ), 'subject': ''}))", "is someone’s email address line ‘three’ \"\"\") def test_strip_unsupported_characters(): assert", "25px; color: #0B0C0C;\">new paragraph</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n'", "'technical advantage over the unspaced em dash. ' ), ),", "), ( 'quadruple ---- dash', 'quadruple ---- dash', ), (", "#005ea5;\" href=\"http://example.com\">http://example.com</a>' ' in the middle' ), ), ( (", "notify_letter_preview_markdown, '<p>variable called thing</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0", "25px; color: #0B0C0C;\">+ one</p>' '<p style=\"Margin: 0 0 20px 0;", "[ \"http://example.com\", \"http://www.gov.uk/\", \"https://www.gov.uk/\", \"http://service.gov.uk\", \"http://service.gov.uk/blah.ext?q=a%20b%20c&order=desc#fragment\", pytest.param(\"http://service.gov.uk/blah.ext?q=one two three\", marks=pytest.mark.xfail),", "11pt; line-height: 25px; color: #0B0C0C;\">line one<br />' 'line two</p>' '<p", "middle' ), ), ( ( 'this link is in brackets", "'notifications-email' def test_strip_and_remove_obscure_whitespace_only_removes_normal_whitespace_from_ends(): sentence = ' words \\n over multiple", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color:", "'\\n\\nsomething **important**', ], )) def test_double_emphasis(markdown_function, expected): assert markdown_function( 'something", "line-height: 25px; color: #0B0C0C;\">b</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n'", "one<br>' 'line two' '</p>' '<p>' 'new paragraph' '</p>' ) ],", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">a</p>' '<hr style=\"border: 0; height:", "\\t , word', '\\n, word', ), ( 'bonjour | hi',", "notify_email_markdown(input) == ( '<p style=\"Margin: 0 0 20px 0; font-size:", "], [ notify_plain_text_email_markdown, ( '\\n' '\\n' '\\nheading' '\\n-----------------------------------------------------------------' ), ],", "== clean @pytest.mark.parametrize('dumb, smart', [ ( \"\"\"And I said, \"what", "== (\"line oneline two\") def test_normalise_whitespace(): assert normalise_whitespace('\\u200C Your tax", "[ notify_letter_preview_markdown, ( '<p>inset text</p>' ) ], [ notify_email_markdown, (", "Can’t work out how to test this pass def test_sms_encode():", "assert remove_smart_quotes_from_email_addresses(\"\"\" line one’s quote first.o’<EMAIL> is someone’s email address", ").format(link)) @pytest.mark.parametrize('input, output', [ ( ( 'this is some text", "notify_plain_text_email_markdown, '\\n\\nvariable called thing', ], )) def test_codespan(markdown_function, expected): assert", "<words>' def test_removing_pipes(): assert strip_pipes('|a|b|c') == 'abc' def test_bleach_doesnt_try_to_make_valid_html_before_cleaning(): assert", "' ' non_breaking_space = ' ' assert en_dash_replacement_sequence == space", "dash', ), ( 'quadruple ---- dash', 'quadruple ---- dash', ),", "\"bonjour | hi\"), (\"bonjour .\", \"bonjour.\"), ('double -- dash', 'double", "25px; color: #0B0C0C;\">something **important**</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething **important**', ],", "'\\rn\\u200Coti\\u200Dfi\\u200Bcati\\u2060ons-\\u180Eemai\\uFEFFl\\uFEFF', ]) def test_strip_and_remove_obscure_whitespace(value): assert strip_and_remove_obscure_whitespace(value) == 'notifications-email' def test_strip_and_remove_obscure_whitespace_only_removes_normal_whitespace_from_ends():", "[ notify_letter_preview_markdown, ( '<p>Example: <strong>example.com</strong></p>' ) ], [ notify_email_markdown, (", "bar', ], )) def test_nested_emphasis(markdown_function, expected): assert markdown_function( 'foo ******", "dash', 'triple \\u2013 dash', ), ( 'quadruple ---- dash', 'quadruple", "( '2004-2008', '2004-2008', # no replacement ), ( 'bonjour |", "'Hello ((name)).\\n\\nThis is a message' ), ( 'Hello Jo .\\n\\nThis", "strip_dvla_markup( ( 'some words & some more <words>' '<cr><h1><h2><p><normal><op><np><bul><tab>' '<CR><H1><H2><P><NORMAL><OP><NP><BUL><TAB>'", "def test_removing_whitespace_before_punctuation(dirty, clean): assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dirty, clean', [", "25px; color: #0B0C0C;\">+ three</p>' ), ], [ notify_plain_text_email_markdown, ( '\\n\\n+", "'\\n' '\\ninset text' ), ], )) def test_level_2_header(markdown_function, expected): assert", "15px; font-size: 19px; line-height: 25px;' '\">' '<p style=\"Margin: 0 0", "expected_output def test_formatted_list_returns_markup(): assert isinstance(formatted_list([0]), Markup) def test_removing_dvla_markup(): assert strip_dvla_markup(", "no replacement ), ( 'bonjour | hi', 'bonjour | hi',", "], )) def test_multiple_newlines_get_truncated(markdown_function, expected): assert markdown_function( 'before\\n\\n\\n\\n\\n\\nafter' ) ==", "), ], )) def test_link_with_title(markdown_function, expected): assert markdown_function( '[Example](http://example.com \"An", "| hi\"), (\"bonjour .\", \"bonjour.\"), ('double -- dash', 'double \\u2013", "notify_letter_preview_markdown, ( '<p>inset text</p>' ) ], [ notify_email_markdown, ( '<blockquote", "lines with \\ttabs' def test_remove_smart_quotes_from_email_addresses(): assert remove_smart_quotes_from_email_addresses(\"\"\" line one’s quote", "break-word; color: #005ea5;\" href=\"http://example.com\" title=\"An example URL\">' 'Example' '</a>' '</p>'", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>' 'line one<br>' 'line", "def test_removing_dvla_markup(): assert strip_dvla_markup( ( 'some words & some more", "'Thanks\\n' ), 'subject': ''})) @pytest.mark.parametrize('markdown_function, expected_output', [ (notify_email_markdown, ( '<p", "a3b'), ([1, 2, 3], {'conjunction': 'foo'}, '‘1’, ‘2’ foo ‘3’'),", "expected_html, expected_html_in_template): assert notify_email_markdown(url) == ( '<p style=\"Margin: 0 0", "'c\\n' ) == ( '<ul>' '<li>a</li>' '<li>b</li>' '<li>c</li>' '</ul>' )", "def test_footnotes(): # Can’t work out how to test this", "color: #0B0C0C;\">foo ****** bar</p>' ], [ notify_plain_text_email_markdown, '\\n\\nfoo ****** bar',", "]) def test_preserves_whitespace_when_making_links( markdown_function, expected_output ): assert markdown_function( 'https://example.com\\n' '\\n'", "parenthesis or ' 'pause \\u2013 and the spaced em dash", "#0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\" title=\"An example URL\">'", "smart): assert make_quotes_smart(dumb) == smart @pytest.mark.parametrize('nasty, nice', [ ( (", "'\\n' 'new paragraph' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [", ")), (notify_plain_text_email_markdown, ( '\\n' '\\nhttps://example.com' '\\n' '\\nNext paragraph' )), ])", "template = SMSMessageTemplate({'content': body}) template.prefix = prefix template.sender = None", "#0B0C0C;\">something **important**</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething **important**', ], )) def", "''})) assert expected in str(HTMLEmailTemplate({'content': template_content, 'subject': ''})) @pytest.mark.parametrize( \"subject,expected\",", "25px; color: #0B0C0C;\">inset text</p>' ], [ notify_plain_text_email_markdown, ( '\\n' '\\ninset", "[ ([1], {}, '‘1’'), ([1, 2], {}, '‘1’ and ‘2’'),", "padding: 0; list-style-type: decimal;\">' '<li style=\"Margin: 5px 0 5px; padding:", "2, 3], {'before_each': '<i>', 'after_each': '</i>'}, '<i>1</i>, <i>2</i> and <i>3</i>'),", "'after_each': 'b'}, 'a1b, a2b and a3b'), ([1, 2, 3], {'conjunction':", "'<p>after</p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin: 0 0", "20px 0; padding: 0; font-size: 27px; ' 'line-height: 35px; font-weight:", "notify_plain_text_email_markdown, ( '\\n' '\\n' '\\nheading' '\\n-----------------------------------------------------------------' ), ], ) )", "def test_subject_is_cleaned_up(subject, expected): assert expected == HTMLEmailTemplate({'content': '', 'subject': subject}).subject", "text</p>' ) ], [ notify_email_markdown, ( '<blockquote ' 'style=\"Margin: 0", "' ), ( 'The en dash \\u2013 always with spaces", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' ' in the middle' ),", "two</p><p>+ three</p>', ], [ notify_email_markdown, ( '<p style=\"Margin: 0 0", "0 0.1px 15px; font-size: 19px; line-height: 25px;' '\">' '<p style=\"Margin:", "def test_doesnt_make_links_out_of_invalid_urls(url): assert notify_email_markdown(url) == ( '<p style=\"Margin: 0 0", "def test_emphasis(markdown_function, expected): assert markdown_function( 'something *important*' ) == expected", "], [ notify_plain_text_email_markdown, '\\n\\nsomething *important*', ], )) def test_emphasis(markdown_function, expected):", "\\tnotifications-email \\x0c ', '\\rn\\u200Coti\\u200Dfi\\u200Bcati\\u2060ons-\\u180Eemai\\uFEFFl\\uFEFF', ]) def test_strip_and_remove_obscure_whitespace(value): assert strip_and_remove_obscure_whitespace(value) ==", "expected', ( [ notify_letter_preview_markdown, ( '<p>Example: <strong>example.com</strong></p>' ) ], [", "expected in str(PlainTextEmailTemplate({'content': template_content, 'subject': ''})) assert expected in str(HTMLEmailTemplate({'content':", "one\\n' '- two\\n' '- three\\n' ), pytest.param(( # plus as", "\"https://gov.uk\"), (\"https://www.gov.uk\", \"https://www.gov.uk\"), (\"www.gov.uk\", \"www.gov.uk\"), (\"gov.uk/register-to-vote\", \"gov.uk/register-to-vote\"), (\"gov.uk?q=\", \"gov.uk?q=\") ]", "two\\n' '\\n' 'new paragraph' ) == expected @pytest.mark.parametrize('markdown_function, expected', (", "\"www.gov.uk\"), (\"gov.uk/register-to-vote\", \"gov.uk/register-to-vote\"), (\"gov.uk?q=\", \"gov.uk?q=\") ] ) def test_escaping_govuk_in_email_templates(template_content, expected):", "font-size: 27px; ' 'line-height: 35px; font-weight: bold; color: #0B0C0C;\">' 'heading'", ") == expected assert markdown_function( '1.one\\n' '2.two\\n' '3.three\\n' ) ==", "), ( \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\",", "'<hr style=\"border: 0; height: 1px; background: #BFC1C3; Margin: 30px 0", "= ' ' assert en_dash_replacement_sequence == space + en_dash assert", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">variable called thing</p>' ], [", "( \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", ),", "three\", marks=pytest.mark.xfail), ] ) def test_makes_links_out_of_URLs(url): link = '<a style=\"word-wrap:", "[ ( 'Hello ((name)) ,\\n\\nThis is a message', 'Hello ((name)),\\n\\nThis", "#005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>’\"\"\", # noqa ), ] ) def test_URLs_get_escaped(url, expected_html,", "assert markdown_function( '[Example](http://example.com \"An example URL\")' ) == expected @pytest.mark.parametrize('markdown_function,", "the middle' ), ), ( ( 'this link is in", "‘3’'), (['&'], {'before_each': '<i>', 'after_each': '</i>'}, '<i>&amp;</i>'), ([1, 2, 3],", "0 0 20px 0; border-left: 10px solid #BFC1C3;' 'padding: 15px", "oneline two\") def test_normalise_whitespace(): assert normalise_whitespace('\\u200C Your tax is\\ndue\\n\\n') ==", "strip_whitespace(value) == 'bar' @pytest.mark.parametrize('value', [ 'notifications-email', ' \\tnotifications-email \\x0c ',", "template_content, 'subject': ''})) assert expected in str(HTMLEmailTemplate({'content': template_content, 'subject': ''}))", "*important*' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_email_markdown, '<p", "href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", ), ]) def test_smart_quotes(dumb,", "as ' 'discussed in this section, indicating a parenthesis or", "'*three\\n' ), ( # single space '* one\\n' '* two\\n'", "0 5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">one</li>' '<li style=\"Margin:", "== 'words \\n over multiple lines with \\ttabs' def test_remove_smart_quotes_from_email_addresses():", "\"http://www.gov.uk/\", \"https://www.gov.uk/\", \"http://service.gov.uk\", \"http://service.gov.uk/blah.ext?q=a%20b%20c&order=desc#fragment\", pytest.param(\"http://service.gov.uk/blah.ext?q=one two three\", marks=pytest.mark.xfail), ] )", "'2.two\\n' '3.three\\n' ) == expected @pytest.mark.parametrize('markdown', ( ( # no", "assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dumb, smart', [ ( \"\"\"And I", "three\\n' ), )) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<ul>\\n'", "0; border-left: 10px solid #BFC1C3;' 'padding: 15px 0 0.1px 15px;", "‘2’ and ‘3’'), ([1, 2, 3], {'prefix': 'foo', 'prefix_plural': 'bar'},", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">line one<br />' 'line", "( HTMLEmailTemplate, PlainTextEmailTemplate, SMSMessageTemplate, SMSPreviewTemplate ) @pytest.mark.parametrize( \"url\", [ \"http://example.com\",", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">something **important**</p>' ], [", "{}, '‘1’ and ‘2’'), ([1, 2, 3], {}, '‘1’, ‘2’", "over multiple lines with \\ttabs' def test_remove_smart_quotes_from_email_addresses(): assert remove_smart_quotes_from_email_addresses(\"\"\" line", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">after</p>' ) ],", "test_strip_unsupported_characters(): assert strip_unsupported_characters(\"line one\\u2028line two\") == (\"line oneline two\") def", "expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>' 'line one<br>'", "def test_HTML_template_has_URLs_replaced_with_links(): assert ( '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://service.example.com/accept_invite/a1b2c3d4\">'", "( # single space '* one\\n' '* two\\n' '* three\\n'", "== expected_output @pytest.mark.parametrize( \"template_content,expected\", [ (\"gov.uk\", u\"gov.\\u200Buk\"), (\"GOV.UK\", u\"GOV.\\u200BUK\"), (\"Gov.uk\",", "HTMLEmailTemplate, PlainTextEmailTemplate, SMSMessageTemplate, SMSPreviewTemplate ) @pytest.mark.parametrize( \"url\", [ \"http://example.com\", \"http://www.gov.uk/\",", "two</p>' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt; line-height:", "expected): template = SMSMessageTemplate({'content': body}) template.prefix = prefix template.sender =", "== expected @pytest.mark.parametrize('markdown', ( ( # no space '*one\\n' '*two\\n'", ") from notifications_utils.template import ( HTMLEmailTemplate, PlainTextEmailTemplate, SMSMessageTemplate, SMSPreviewTemplate )", "quick brown fox \"\"\"}) template.prefix = None template.sender = None", "( 'triple --- dash', 'triple \\u2013 dash', ), ( 'quadruple", "expected', ( [ notify_letter_preview_markdown, ( '<ul>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ul>\\n'", "'\\nExample (An example URL): http://example.com' ), ], )) def test_link_with_title(markdown_function,", "'subject': subject}).subject @pytest.mark.parametrize( \"prefix, body, expected\", [ (\"a\", \"b\", \"a:", "def test_block_code(markdown_function, expected): assert markdown_function('```\\nprint(\"hello\")\\n```') == expected @pytest.mark.parametrize('markdown_function, expected', (", "(\"Gov.uk\", u\"Gov.\\u200Buk\"), (\"https://gov.uk\", \"https://gov.uk\"), (\"https://www.gov.uk\", \"https://www.gov.uk\"), (\"www.gov.uk\", \"www.gov.uk\"), (\"gov.uk/register-to-vote\", \"gov.uk/register-to-vote\"),", "expected): assert markdown_function('a\\n\\n***\\n\\nb') == expected assert markdown_function('a\\n\\n---\\n\\nb') == expected @pytest.mark.parametrize('markdown_function,", "invited to a service. Click this link:\\n' 'https://service.example.com/accept_invite/a1b2c3d4\\n' '\\n' 'Thanks\\n'", "'\\n\\nStrike' ], )) def test_strikethrough(markdown_function, expected): assert markdown_function('~~Strike~~') == expected", "Margin: 30px 0 30px 0;\">' '<p style=\"Margin: 0 0 20px", "assert markdown_function( '![alt text](http://example.com/image.png)' ) == ( '' ) @pytest.mark.parametrize('markdown_function,", "expected): assert markdown_function(link) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "'bar ‘1’, ‘2’ and ‘3’'), ([1], {'prefix': 'foo', 'prefix_plural': 'bar'},", "'<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' '</p>' ) ], [", "'before\\n\\n\\n\\n\\n\\nafter' ) == expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown ))", "' 'pause - and the spaced em dash both have", "and ‘3’'), ([1], {'prefix': 'foo', 'prefix_plural': 'bar'}, 'foo ‘1’'), ([1,", "expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>Strike</p>' ], [ notify_email_markdown,", "foo ‘3’'), (['&'], {'before_each': '<i>', 'after_each': '</i>'}, '<i>&amp;</i>'), ([1, 2,", "), ( 'Hello Jo .\\n\\nThis is a message', 'Hello Jo.\\n\\nThis", "notifications_utils.formatters import ( unlink_govuk_escaped, notify_email_markdown, notify_letter_preview_markdown, notify_plain_text_email_markdown, sms_encode, formatted_list, strip_dvla_markup,", "expected_output @pytest.mark.parametrize( \"template_content,expected\", [ (\"gov.uk\", u\"gov.\\u200Buk\"), (\"GOV.UK\", u\"GOV.\\u200BUK\"), (\"Gov.uk\", u\"Gov.\\u200Buk\"),", "'\\nbefore' '\\n' '\\nafter' ), ], )) def test_multiple_newlines_get_truncated(markdown_function, expected): assert", "( 'Hello Jo .\\n\\nThis is a message', 'Hello Jo.\\n\\nThis is", "def test_autolink(markdown_function, link, expected): assert markdown_function(link) == expected @pytest.mark.parametrize('markdown_function, expected',", "notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown )) def test_table(markdown_function): assert markdown_function( 'col |", "\"url\", [ \"http://example.com\", \"http://www.gov.uk/\", \"https://www.gov.uk/\", \"http://service.gov.uk\", \"http://service.gov.uk/blah.ext?q=a%20b%20c&order=desc#fragment\", pytest.param(\"http://service.gov.uk/blah.ext?q=one two three\",", "markdown_function('a\\n\\n***\\n\\nb') == expected assert markdown_function('a\\n\\n---\\n\\nb') == expected @pytest.mark.parametrize('markdown_function, expected', (", "== expected_fixed def test_make_list_from_linebreaks(): assert nl2li( 'a\\n' 'b\\n' 'c\\n' )", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">Strike</p>' ], [ notify_plain_text_email_markdown, '\\n\\nStrike'", "'bonjour | hi', ), ]) def test_en_dashes(nasty, nice): assert replace_hyphens_with_en_dashes(nasty)", "], [ notify_email_markdown, ( '<h2 style=\"Margin: 0 0 20px 0;", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>inset text</p>' ) ],", "test_autolink(markdown_function, link, expected): assert markdown_function(link) == expected @pytest.mark.parametrize('markdown_function, expected', (", "4), 'before{}<np>after'.format('<cr>' * 3), ), ]) def test_tweaking_dvla_list_markup(markup, expected_fixed): assert", "parenthesis or ' 'pause - and the spaced em dash", "import ( HTMLEmailTemplate, PlainTextEmailTemplate, SMSMessageTemplate, SMSPreviewTemplate ) @pytest.mark.parametrize( \"url\", [", "11pt; line-height: 25px; color: #0B0C0C;\">+ three</p>' ), ], [ notify_plain_text_email_markdown,", "'<td style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ul style=\"Margin: 0 0 0", "one’s quote first.o’<EMAIL> is someone’s email address line ‘three’ \"\"\")", "# noqa \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>‘)\"\"\", # noqa", ") ]) def test_makes_links_out_of_URLs_in_context(input, output): assert notify_email_markdown(input) == ( '<p", "( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown )) def test_table(markdown_function): assert markdown_function( 'col", "25px; color: #0B0C0C;\">Strike</p>' ], [ notify_plain_text_email_markdown, '\\n\\nStrike' ], )) def", "\\u180E\\u200B \\u200C bar \\u200D \\u2060\\uFEFF ', ]) def test_strip_whitespace(value): assert", "'\\n' '\\n• one' '\\n• two' '\\n• three' ), ], ))", "'- two\\n' '- three\\n' ), pytest.param(( # plus as bullet", ") ], [ notify_email_markdown, \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", ( '<p style=\"Margin: 0 0", "' 'line-height: 35px; font-weight: bold; color: #0B0C0C;\">' 'heading' '</h2>' )", "bold; color: #0B0C0C;\">' 'heading' '</h2>' ) ], [ notify_plain_text_email_markdown, (", "test_normalise_whitespace(): assert normalise_whitespace('\\u200C Your tax is\\ndue\\n\\n') == 'Your tax is", "* 3), ), ]) def test_tweaking_dvla_list_markup(markup, expected_fixed): assert tweak_dvla_list_markup(markup) ==", "example URL): http://example.com' ), ], )) def test_link_with_title(markdown_function, expected): assert", "at Tiffany's\"?\"\"\", \"\"\"And I said, “what about breakfast at Tiffany’s”?\"\"\",", ") == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>before</p>'", "11pt; line-height: 25px; color: #0B0C0C;\">before</p>' '<p style=\"Margin: 0 0 20px", "link, expected): assert markdown_function(link) == expected @pytest.mark.parametrize('markdown_function, expected', ( [", "'bonjour | hi', 'bonjour | hi', ), ]) def test_removing_whitespace_before_punctuation(dirty,", "'\\n\\nsomething *important*', ], )) def test_emphasis(markdown_function, expected): assert markdown_function( 'something", "color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>’\"\"\", # noqa ), ] ) def test_URLs_get_escaped(url,", "'<p>variable called thing</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0", "thing', ], )) def test_codespan(markdown_function, expected): assert markdown_function( 'variable called", "]) def test_en_dashes(nasty, nice): assert replace_hyphens_with_en_dashes(nasty) == nice def test_unicode_dash_lookup():", "@pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown )) def test_image(markdown_function): assert markdown_function(", "markdown_function( 'https://example.com\\n' '\\n' 'Next paragraph' ) == expected_output @pytest.mark.parametrize( \"template_content,expected\",", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">before</p>' '<p style=\"Margin: 0", "href=\"http://example.com\">Example</a>' '</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nExample: http://example.com'", "class=\\'placeholder\\'>((token))</span>&amp;key=1' '</p>' ) @pytest.mark.parametrize( \"url, expected_html, expected_html_in_template\", [ ( \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\",", "def test_bleach_doesnt_try_to_make_valid_html_before_cleaning(): assert escape_html( \"<to cancel daily cat facts reply", "'https://example.com\"onclick=\"alert(\\'hi' '</a>\\')' '</p>' ) ], [ notify_plain_text_email_markdown, 'http://example.com', ( '\\n'", ") == expected_output @pytest.mark.parametrize( \"template_content,expected\", [ (\"gov.uk\", u\"gov.\\u200Buk\"), (\"GOV.UK\", u\"GOV.\\u200BUK\"),", "\"\"\"And I said, “what about breakfast at Tiffany’s”?\"\"\", ), (", "three' ), ], )) def test_unordered_list(markdown, markdown_function, expected): assert markdown_function(markdown)", "'after_each': '</i>'}, '<i>&amp;</i>'), ([1, 2, 3], {'before_each': '<i>', 'after_each': '</i>'},", "one' '\\n• two' '\\n• three' ), ], )) def test_unordered_list(markdown,", "== HTMLEmailTemplate({'content': '', 'subject': subject}).subject @pytest.mark.parametrize( \"prefix, body, expected\", [", "# single space '* one\\n' '* two\\n' '* three\\n' ),", "'\\n' 'Next paragraph' ) == expected_output @pytest.mark.parametrize( \"template_content,expected\", [ (\"gov.uk\",", "2, 3], {'prefix': 'foo', 'prefix_plural': 'bar'}, 'bar ‘1’, ‘2’ and", "), ( 'em — dash', 'em – dash', ), (", "test_smart_quotes(dumb, smart): assert make_quotes_smart(dumb) == smart @pytest.mark.parametrize('nasty, nice', [ (", "color: #005ea5;\" href=\"https://service.example.com/accept_invite/a1b2c3d4\">' 'https://service.example.com/accept_invite/a1b2c3d4' '</a>' ) in str(HTMLEmailTemplate({'content': ( 'You’ve", "expected): assert markdown_function( 'foo ****** bar' ) == expected @pytest.mark.parametrize('markdown_function',", "bar ', \"\"\" \\t bar \"\"\", ' \\u180E\\u200B \\u200C bar", "( '\\n \\t . word', '\\n. word', ), ]) def", "\"example.com\", \"www.example.com\", \"ftp://example.com\", \"<EMAIL>\", \"mailto:<EMAIL>\", \"<a href=\\\"https://example.com\\\">Example</a>\", ] ) def", "test_codespan(markdown_function, expected): assert markdown_function( 'variable called `thing`' ) == expected", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">new paragraph</p>' ) ],", "', ]) def test_strip_whitespace(value): assert strip_whitespace(value) == 'bar' @pytest.mark.parametrize('value', [", "bullet as bullet '• one\\n' '• two\\n' '• three\\n' ),", "two' '\\n3. three' ), ], )) def test_ordered_list(markdown_function, expected): assert", "( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown )) def test_image(markdown_function): assert markdown_function( '![alt", "assert markdown_function( '1.one\\n' '2.two\\n' '3.three\\n' ) == expected @pytest.mark.parametrize('markdown', (", "'[Example](http://example.com \"An example URL\")' ) == expected @pytest.mark.parametrize('markdown_function, expected', (", "two\\n' '* three\\n' ), ( # dash as bullet '-", "work out how to test this pass def test_sms_encode(): assert", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(link))", "assert expected_html_in_template in str(HTMLEmailTemplate({'content': url, 'subject': ''})) def test_HTML_template_has_URLs_replaced_with_links(): assert", "have a certain ' 'technical advantage over the unspaced em", "(\"bonjour | hi\", \"bonjour | hi\"), (\"bonjour .\", \"bonjour.\"), ('double", "expected', ( [ notify_letter_preview_markdown, '<h2>heading</h2>\\n' ], [ notify_email_markdown, ( '<h2", "markdown_function( 'foo ****** bar' ) == expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown,", "the middle' ), ( 'this is some text with a", "assert en_dash_replacement_sequence == space + en_dash assert non_breaking_space not in", "the unspaced em dash. ' ), ( 'The en dash", "def test_preserves_whitespace_when_making_links( markdown_function, expected_output ): assert markdown_function( 'https://example.com\\n' '\\n' 'Next", "href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>‘)\"\"\", # noqa ), ( \"\"\"https://example.com\"style='text-decoration:blink'\"\"\", \"\"\"<a style=\"word-wrap: break-word; color:", ") in str(HTMLEmailTemplate({'content': ( 'You’ve been invited to a service.", "'Hello ((name)) ,\\n\\nThis is a message', 'Hello ((name)),\\n\\nThis is a", "line-height: 25px; color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com\">'", "heading', '#heading', )) @pytest.mark.parametrize( 'markdown_function, expected', ( [ notify_letter_preview_markdown, '<h2>heading</h2>\\n'", "[ notify_letter_preview_markdown, '<p>+ one</p><p>+ two</p><p>+ three</p>', ], [ notify_email_markdown, (", "template.prefix = None template.sender = None assert '<br>' in str(template)", "' \\u180E\\u200B \\u200C bar \\u200D \\u2060\\uFEFF ', ]) def test_strip_whitespace(value):", "in brackets ' '(<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>)' ),", "disc;\">' '<li style=\"Margin: 5px 0 5px; padding: 0 0 0", "], )) def test_unordered_list(markdown, markdown_function, expected): assert markdown_function(markdown) == expected", "href=\"http://example.com\">http://example.com</a>' '</p>' ) ], [ notify_email_markdown, \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", ( '<p style=\"Margin:", "color: #0B0C0C;\">three</li>' '</ul>' '</td>' '</tr>' '</table>' ) ], [ notify_plain_text_email_markdown,", "'subject': ''})) @pytest.mark.parametrize('markdown_function, expected_output', [ (notify_email_markdown, ( '<p style=\"Margin: 0", "color: #0B0C0C;\">line one<br />' 'line two</p>' '<p style=\"Margin: 0 0", "'bonjour | hi', ), ]) def test_removing_whitespace_before_punctuation(dirty, clean): assert remove_whitespace_before_punctuation(dirty)", "one' '\\n\\n+ two' '\\n\\n+ three' ), ], )) def test_pluses_dont_render_as_lists(markdown_function,", "break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' '</p>' ) ], [ notify_email_markdown, \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\",", "hi', ), ]) def test_removing_whitespace_before_punctuation(dirty, clean): assert remove_whitespace_before_punctuation(dirty) == clean", "with \\ttabs' def test_remove_smart_quotes_from_email_addresses(): assert remove_smart_quotes_from_email_addresses(\"\"\" line one’s quote first.o’<EMAIL>", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">foo ******", "dash'), ] ) def test_subject_is_cleaned_up(subject, expected): assert expected == HTMLEmailTemplate({'content':", "address line ‘three’ \"\"\") == (\"\"\" line one’s quote first.o'<EMAIL>", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">Example</a>' '</p>' ) ], [ notify_plain_text_email_markdown,", "'' ) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>Example: <strong>example.com</strong></p>'", "'line one<br>' 'line two' '</p>' '<p>' 'new paragraph' '</p>' )", "dash', 'quadruple ---- dash', ), ( 'em — dash', 'em", "# Can’t work out how to test this pass def", "0; padding: 0; font-size: 27px; ' 'line-height: 35px; font-weight: bold;", "font-weight: bold; color: #0B0C0C;\">' 'heading' '</h2>' ) ], [ notify_plain_text_email_markdown,", "* 4), 'before{}<np>after'.format('<cr>' * 3), ), ]) def test_tweaking_dvla_list_markup(markup, expected_fixed):", "color: #005ea5;\" href=\"http://example.com\" title=\"An example URL\">' 'Example' '</a>' '</p>' )", "'line-height: 35px; font-weight: bold; color: #0B0C0C;\">' 'heading' '</h2>' ) ],", "], )) def test_block_quote(markdown_function, expected): assert markdown_function('^ inset text') ==", "en dash \\u2013 always with spaces in running text when,", "): assert markdown_function( 'https://example.com\\n' '\\n' 'Next paragraph' ) == expected_output", "'em — dash', 'em – dash', ), ( 'already\\u0020–\\u0020correct', #", "def test_makes_links_out_of_URLs(url): link = '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"{}\">{}</a>'.format(url,", "test_sms_preview_adds_newlines(): template = SMSPreviewTemplate({'content': \"\"\" the quick brown fox \"\"\"})", "@pytest.mark.parametrize('dumb, smart', [ ( \"\"\"And I said, \"what about breakfast", "'* one\\n' '* two\\n' '* three\\n' ), ( # dash", ") def test_subject_is_cleaned_up(subject, expected): assert expected == HTMLEmailTemplate({'content': '', 'subject':", "test_removing_pipes(): assert strip_pipes('|a|b|c') == 'abc' def test_bleach_doesnt_try_to_make_valid_html_before_cleaning(): assert escape_html( \"<to", "'bar'}, 'foo ‘1’'), ([1, 2, 3], {'before_each': 'a', 'after_each': 'b'},", "( [ notify_letter_preview_markdown, '<p>+ one</p><p>+ two</p><p>+ three</p>', ], [ notify_email_markdown,", "], [ notify_email_markdown, \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", ( '<p style=\"Margin: 0 0 20px", "(An example URL): http://example.com' ), ], )) def test_link_with_title(markdown_function, expected):", "dash', ), ( 'already\\u0020–\\u0020correct', # \\u0020 is a normal space", "(expected) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>a</p>' '<div class=\"page-break\">&nbsp;</div>'", "notify_email_markdown(url) == ( '<p style=\"Margin: 0 0 20px 0; font-size:", "( 'Hello ((name)) .\\n\\nThis is a message', 'Hello ((name)).\\n\\nThis is", "'<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">Example</a>' '</p>' ) ], [", "facts reply 'cancel'>\" ) == ( \"&lt;to cancel daily cat", "'\\n3. three' ), ], )) def test_ordered_list(markdown_function, expected): assert markdown_function(", "\\t bar \"\"\", ' \\u180E\\u200B \\u200C bar \\u200D \\u2060\\uFEFF ',", "someone’s email address line ‘three’ \"\"\") def test_strip_unsupported_characters(): assert strip_unsupported_characters(\"line", "( # two spaces '* one\\n' '* two\\n' '* three\\n'", "daily cat facts reply 'cancel'>\" ) == ( \"&lt;to cancel", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">inset text</p>'", "*important*', ], )) def test_emphasis(markdown_function, expected): assert markdown_function( 'something *important*'", "replacement ), ( 'bonjour | hi', 'bonjour | hi', ),", "'bonjour | hi', 'bonjour | hi', ), ]) def test_en_dashes(nasty,", "this link:\\n' 'https://service.example.com/accept_invite/a1b2c3d4\\n' '\\n' 'Thanks\\n' ), 'subject': ''})) @pytest.mark.parametrize('markdown_function, expected_output',", "'triple --- dash', 'triple \\u2013 dash', ), ( 'quadruple ----", "solid #BFC1C3;' 'padding: 15px 0 0.1px 15px; font-size: 19px; line-height:", "text</p>' ], [ notify_plain_text_email_markdown, ( '\\n' '\\ninset text' ), ],", "in str(HTMLEmailTemplate({'content': url, 'subject': ''})) def test_HTML_template_has_URLs_replaced_with_links(): assert ( '<a", "), ], )) def test_link(markdown_function, expected): assert markdown_function( '[Example](http://example.com)' )", "two\") def test_normalise_whitespace(): assert normalise_whitespace('\\u200C Your tax is\\ndue\\n\\n') == 'Your", "from notifications_utils.formatters import ( unlink_govuk_escaped, notify_email_markdown, notify_letter_preview_markdown, notify_plain_text_email_markdown, sms_encode, formatted_list,", "\\ttabs' def test_remove_smart_quotes_from_email_addresses(): assert remove_smart_quotes_from_email_addresses(\"\"\" line one’s quote first.o’<EMAIL> is", "{'prefix': 'foo', 'prefix_plural': 'bar'}, 'foo ‘1’'), ([1, 2, 3], {'before_each':", "one</p><p>+ two</p><p>+ three</p>', ], [ notify_email_markdown, ( '<p style=\"Margin: 0", "0 20px 0;\">' '<tr>' '<td style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ul", "hi', 'bonjour | hi', ), ]) def test_removing_whitespace_before_punctuation(dirty, clean): assert", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">Strike</p>' ], [", "def test_strip_and_remove_obscure_whitespace(value): assert strip_and_remove_obscure_whitespace(value) == 'notifications-email' def test_strip_and_remove_obscure_whitespace_only_removes_normal_whitespace_from_ends(): sentence =", "two' '\\n\\n+ three' ), ], )) def test_pluses_dont_render_as_lists(markdown_function, expected): assert", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' 'Next paragraph' '</p>' )),", "dash', ), ( 'triple --- dash', 'triple \\u2013 dash', ),", "link is in brackets (http://example.com)' ), ( 'this link is", "message' ), ( '\\n \\t , word', '\\n, word', ),", "'line two</p>' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "remove_smart_quotes_from_email_addresses, strip_unsupported_characters, normalise_whitespace ) from notifications_utils.template import ( HTMLEmailTemplate, PlainTextEmailTemplate,", "'</ul>' '</td>' '</tr>' '</table>' ) ], [ notify_plain_text_email_markdown, ( '\\n'", "(\"www.gov.uk\", \"www.gov.uk\"), (\"gov.uk/register-to-vote\", \"gov.uk/register-to-vote\"), (\"gov.uk?q=\", \"gov.uk?q=\") ] ) def test_escaping_govuk_in_email_templates(template_content,", "'\\n• two' '\\n• three' ), ], )) def test_unordered_list(markdown, markdown_function,", "escape_html, remove_whitespace_before_punctuation, make_quotes_smart, replace_hyphens_with_en_dashes, tweak_dvla_list_markup, nl2li, strip_whitespace, strip_and_remove_obscure_whitespace, remove_smart_quotes_from_email_addresses, strip_unsupported_characters,", "( 'already\\u0020–\\u0020correct', # \\u0020 is a normal space character 'already\\u0020–\\u0020correct',", "#BFC1C3;' 'padding: 15px 0 0.1px 15px; font-size: 19px; line-height: 25px;'", "inset text') == (expected) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, (", "11pt; line-height: 25px; color: #0B0C0C;\">a</p>' '<hr style=\"border: 0; height: 1px;", "#0B0C0C;\">+ two</p>' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "test_double_emphasis(markdown_function, expected): assert markdown_function( 'something **important**' ) == expected @pytest.mark.parametrize('markdown_function,", "notify_letter_preview_markdown, 'print(\"hello\")' ], [ notify_email_markdown, 'print(\"hello\")' ], [ notify_plain_text_email_markdown, 'print(\"hello\")'", "markdown_function, expected): assert markdown_function(markdown) == expected @pytest.mark.parametrize('markdown_function, expected', ( [", "em dash both have a certain ' 'technical advantage over", "0;\">' '<p style=\"Margin: 0 0 20px 0; font-size: 11pt; line-height:", "test_paragraphs(markdown_function, expected): assert markdown_function( 'line one\\n' 'line two\\n' '\\n' 'new", "'<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://service.example.com/accept_invite/a1b2c3d4\">' 'https://service.example.com/accept_invite/a1b2c3d4' '</a>' ) in", "color: #005ea5;\" href=\"https://example.com\">' 'https://example.com' '</a>' '</p>' '<p style=\"Margin: 0 0", "href=\"https://example.com\">' 'https://example.com' '</a>' '</p>' '<p style=\"Margin: 0 0 20px 0;", "notify_letter_preview_markdown, ( '<ol>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ol>\\n' ) ], [", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">new paragraph</p>' ) ], [", "'<li>a</li>' '<li>b</li>' '<li>c</li>' '</ul>' ) @pytest.mark.parametrize('value', [ 'bar', ' bar", "== nice def test_unicode_dash_lookup(): en_dash_replacement_sequence = '\\u0020\\u2013' hyphen = '-'", "test_block_quote(markdown_function, expected): assert markdown_function('^ inset text') == expected @pytest.mark.parametrize('heading', (", "0;\">' '<tr>' '<td style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ol style=\"Margin: 0", "notify_plain_text_email_markdown, ( '\\n\\n+ one' '\\n\\n+ two' '\\n\\n+ three' ), ],", "'</p>' ) @pytest.mark.parametrize( \"url, expected_html, expected_html_in_template\", [ ( \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", \"\"\"<a", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ one</p>' '<p style=\"Margin: 0", "), ( 'before<p><cr><p><cr>after', 'before<p><cr>after', ), ( 'before<cr><cr><np>after', 'before<cr><np>after', ), (", "0 20px 0;\">' '<tr>' '<td style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ol", "'Hello Jo .\\n\\nThis is a message', 'Hello Jo.\\n\\nThis is a", "color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' '</p>' )", "25px; color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com\">' 'https://example.com'", "in the middle' ), ), ( ( 'this link is", "\"\"\" \\t bar \"\"\", ' \\u180E\\u200B \\u200C bar \\u200D \\u2060\\uFEFF", "str(PlainTextEmailTemplate({'content': template_content, 'subject': ''})) assert expected in str(HTMLEmailTemplate({'content': template_content, 'subject':", "def test_double_emphasis(markdown_function, expected): assert markdown_function( 'something **important**' ) == expected", "space character 'already\\u0020–\\u0020correct', ), ( '2004-2008', '2004-2008', # no replacement", "( '<blockquote ' 'style=\"Margin: 0 0 20px 0; border-left: 10px", "((name)).\\n\\nThis is a message' ), ( 'Hello Jo .\\n\\nThis is", "'‘1’'), ([1, 2], {}, '‘1’ and ‘2’'), ([1, 2, 3],", "'</ul>\\n' ) ], [ notify_email_markdown, ( '<table role=\"presentation\" style=\"padding: 0", "two\") == (\"line oneline two\") def test_normalise_whitespace(): assert normalise_whitespace('\\u200C Your", "'\\nb' ), ], )) def test_hrule(markdown_function, expected): assert markdown_function('a\\n\\n***\\n\\nb') ==", "'subject': ''})) @pytest.mark.parametrize( \"subject,expected\", [ (\"bonjour | hi\", \"bonjour |", "( '\\n' '\\n' '\\nheading' '\\n-----------------------------------------------------------------' ), ], ) ) def", "color: #0B0C0C;\">two</li>' '<li style=\"Margin: 5px 0 5px; padding: 0 0", "@pytest.mark.parametrize( \"subject,expected\", [ (\"bonjour | hi\", \"bonjour | hi\"), (\"bonjour", "11pt; line-height: 25px; color: #0B0C0C;\">inset text</p>' ], [ notify_plain_text_email_markdown, (", "<words>' '<cr><h1><h2><p><normal><op><np><bul><tab>' '<CR><H1><H2><P><NORMAL><OP><NP><BUL><TAB>' '<tAb>' ) ) == 'some words &", "test_make_list_from_linebreaks(): assert nl2li( 'a\\n' 'b\\n' 'c\\n' ) == ( '<ul>'", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ two</p>' '<p style=\"Margin: 0", "'cancel'>\" ) == ( \"&lt;to cancel daily cat facts reply", "Tiffany’s”?\"\"\", ), ( \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a>", "'\\n' '\\n=================================================================' '\\n' '\\nb' ), ], )) def test_hrule(markdown_function, expected):", "# plus as bullet '+ one\\n' '+ two\\n' '+ three\\n'", "in en_dash_replacement_sequence @pytest.mark.parametrize('markup, expected_fixed', [ ( 'a', 'a', ), (", "== expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>inset text</p>' ],", "test_emphasis(markdown_function, expected): assert markdown_function( 'something *important*' ) == expected @pytest.mark.parametrize('markdown_function,", "test_link(markdown_function, expected): assert markdown_function( '[Example](http://example.com)' ) == expected @pytest.mark.parametrize('markdown_function, expected',", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>inset text</p>' ], [ notify_email_markdown,", "expected assert markdown_function('a\\n\\n---\\n\\nb') == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "( '\\n' '\\n1. one' '\\n2. two' '\\n3. three' ), ],", ".\\n\\nThis is a message', 'Hello Jo.\\n\\nThis is a message' ),", "'</p>' ).format(expected_html) assert expected_html_in_template in str(HTMLEmailTemplate({'content': url, 'subject': ''})) def", "color: #0B0C0C;\">after</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nbefore' '\\n'", "'em – dash', ), ( 'already\\u0020–\\u0020correct', # \\u0020 is a", "#0B0C0C;\">variable called thing</p>' ], [ notify_plain_text_email_markdown, '\\n\\nvariable called thing', ],", "'b\\n' 'c\\n' ) == ( '<ul>' '<li>a</li>' '<li>b</li>' '<li>c</li>' '</ul>'", "def test_removing_whitespace_before_full_stops(dirty, clean): assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dumb, smart', [", "bar</p>' ], [ notify_plain_text_email_markdown, '\\n\\nfoo ****** bar', ], )) def", "\"bonjour.\"), ('double -- dash', 'double \\u2013 dash'), ] ) def", "( 'Hello ((name)) ,\\n\\nThis is a message', 'Hello ((name)),\\n\\nThis is", "( [ notify_letter_preview_markdown, ( '<p>inset text</p>' ) ], [ notify_email_markdown,", "en_dash_replacement_sequence assert hyphen not in en_dash_replacement_sequence @pytest.mark.parametrize('markup, expected_fixed', [ (", "bullet '+ one\\n' '+ two\\n' '+ three\\n' ), marks=pytest.mark.xfail(raises=AssertionError)), (", "#0B0C0C;\">three</li>' '</ul>' '</td>' '</tr>' '</table>' ) ], [ notify_plain_text_email_markdown, (", ")) def test_emphasis(markdown_function, expected): assert markdown_function( 'something *important*' ) ==", "== (\"\"\" line one’s quote first.o'<EMAIL> is someone’s email address", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<ul>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n'", "inset text') == expected @pytest.mark.parametrize('heading', ( '# heading', '#heading', ))", "isinstance(formatted_list([0]), Markup) def test_removing_dvla_markup(): assert strip_dvla_markup( ( 'some words &", "(\"gov.uk/register-to-vote\", \"gov.uk/register-to-vote\"), (\"gov.uk?q=\", \"gov.uk?q=\") ] ) def test_escaping_govuk_in_email_templates(template_content, expected): assert", "#0B0C0C;\">inset text</p>' ], [ notify_plain_text_email_markdown, ( '\\n' '\\ninset text' ),", "expected): assert markdown_function( 'something **important**' ) == expected @pytest.mark.parametrize('markdown_function, expected',", "'double \\u2013 dash'), ] ) def test_subject_is_cleaned_up(subject, expected): assert expected", "def test_smart_quotes(dumb, smart): assert make_quotes_smart(dumb) == smart @pytest.mark.parametrize('nasty, nice', [", "assert markdown_function(markdown) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>+", "'\\n\\n+ two' '\\n\\n+ three' ), ], )) def test_pluses_dont_render_as_lists(markdown_function, expected):", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">something *important*</p>' ], [", "== expected assert markdown_function('a\\n\\n---\\n\\nb') == expected @pytest.mark.parametrize('markdown_function, expected', ( [", "cancel daily cat facts reply 'cancel'&gt;\" ) @pytest.mark.parametrize('dirty, clean', [", "'<p><strong>example.com</strong></p>' ], [ notify_email_markdown, 'http://example.com', ( '<p style=\"Margin: 0 0", "([1, 2, 3], {'prefix': 'foo', 'prefix_plural': 'bar'}, 'bar ‘1’, ‘2’", "[ notify_plain_text_email_markdown, ( '\\n' '\\n1. one' '\\n2. two' '\\n3. three'", "test_footnotes(): # Can’t work out how to test this pass", "href=\"http://example.com\">http://example.com</a>' ' in the middle' ), ), ( ( 'this", "'new paragraph' '</p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin:", "someone’s email address line ‘three’ \"\"\") == (\"\"\" line one’s", "= None template.sender = None assert '<br>' in str(template) @pytest.mark.parametrize(", "section, indicating a parenthesis or ' 'pause - and the", "dash \\u2013 always with spaces in running text when, as", "one\\n' '* two\\n' '* three\\n' ), ( # tab '*", "expected == HTMLEmailTemplate({'content': '', 'subject': subject}).subject @pytest.mark.parametrize( \"prefix, body, expected\",", ") ], [ notify_plain_text_email_markdown, ( '\\n' '\\n1. one' '\\n2. two'", "a message', 'Hello Jo.\\n\\nThis is a message' ), ( '\\n", "== expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>before</p>' '<p>after</p>'", "[ 'bar', ' bar ', \"\"\" \\t bar \"\"\", '", "paragraph' '</p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin: 0", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">line one<br />'", "markdown_function( 'something **important**' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [", "== expected_output def test_formatted_list_returns_markup(): assert isinstance(formatted_list([0]), Markup) def test_removing_dvla_markup(): assert", "notify_plain_text_email_markdown, '\\n\\nsomething *important*', ], )) def test_emphasis(markdown_function, expected): assert markdown_function(", ") == ( '' ) @pytest.mark.parametrize('markdown_function, link, expected', ( [", "'</p>' ) ], [ notify_email_markdown, \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", ( '<p style=\"Margin: 0", "'{}' '</p>' ).format(url) def test_handles_placeholders_in_urls(): assert notify_email_markdown( \"http://example.com/?token=<span class='placeholder'>((token))</span>&key=1\" )", "assert nl2li( 'a\\n' 'b\\n' 'c\\n' ) == ( '<ul>' '<li>a</li>'", "bullet '- one\\n' '- two\\n' '- three\\n' ), pytest.param(( #", "spaces '* one\\n' '* two\\n' '* three\\n' ), ( #", "Helvetica, Arial, sans-serif;\">' '<ol style=\"Margin: 0 0 0 20px; padding:", "character 'already\\u0020–\\u0020correct', ), ( '2004-2008', '2004-2008', # no replacement ),", "padding: 0; font-size: 27px; ' 'line-height: 35px; font-weight: bold; color:", "'\\n' '\\n1. one' '\\n2. two' '\\n3. three' ), ], ))", "[ ( \"\"\"And I said, \"what about breakfast at Tiffany's\"?\"\"\",", ") def test_level_1_header(markdown_function, heading, expected): assert markdown_function(heading) == expected @pytest.mark.parametrize('markdown_function,", "0 0 20px 0; padding: 0; font-size: 27px; ' 'line-height:", "middle' ), ( 'this is some text with a link", "href=\"http://example.com\" title=\"An example URL\">' 'Example' '</a>' '</p>' ) ], [", "assert unlink_govuk_escaped(template_content) == expected assert expected in str(PlainTextEmailTemplate({'content': template_content, 'subject':", "( \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>')\"\"\", # noqa", "], [ notify_plain_text_email_markdown, ( '\\n' '\\n• one' '\\n• two' '\\n•", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ one</p>' '<p style=\"Margin:", "unspaced em dash. ' ), ( 'The en dash \\u2013", "'https://example.com' '</a>' '</p>' '<p style=\"Margin: 0 0 20px 0; font-size:", "11pt; line-height: 25px; ' 'color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color:", "3], {}, '‘1’, ‘2’ and ‘3’'), ([1, 2, 3], {'prefix':", "marks=pytest.mark.xfail), ] ) def test_makes_links_out_of_URLs(url): link = '<a style=\"word-wrap: break-word;", "'before{}<np>after'.format('<cr>' * 3), ), ]) def test_tweaking_dvla_list_markup(markup, expected_fixed): assert tweak_dvla_list_markup(markup)", "in this section, indicating a parenthesis or ' 'pause -", "href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", ), ]) def test_smart_quotes(dumb, smart): assert make_quotes_smart(dumb) ==", "'bar'}, 'bar ‘1’, ‘2’ and ‘3’'), ([1], {'prefix': 'foo', 'prefix_plural':", "email address line ‘three’ \"\"\") def test_strip_unsupported_characters(): assert strip_unsupported_characters(\"line one\\u2028line", "assert normalise_whitespace('\\u200C Your tax is\\ndue\\n\\n') == 'Your tax is due'", ").format(url) def test_handles_placeholders_in_urls(): assert notify_email_markdown( \"http://example.com/?token=<span class='placeholder'>((token))</span>&key=1\" ) == (", "0 5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">three</li>' '</ul>' '</td>'", "[ notify_email_markdown, \"\"\"https://example.com\"onclick=\"alert('hi')\"\"\", ( '<p style=\"Margin: 0 0 20px 0;", "'a\\n' 'b\\n' 'c\\n' ) == ( '<ul>' '<li>a</li>' '<li>b</li>' '<li>c</li>'", "with \\ttabs\\t ' assert strip_and_remove_obscure_whitespace(sentence) == 'words \\n over multiple", "'a', ), ( 'before<p><cr><p><cr>after', 'before<p><cr>after', ), ( 'before<cr><cr><np>after', 'before<cr><np>after', ),", "three</p>' ), ], [ notify_plain_text_email_markdown, ( '\\n\\n+ one' '\\n\\n+ two'", "space '* one\\n' '* two\\n' '* three\\n' ), ( #", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">inset text</p>' ], [", "None template.sender = None assert '<br>' in str(template) @pytest.mark.parametrize( 'markdown_function,", "space = ' ' non_breaking_space = ' ' assert en_dash_replacement_sequence", "one<br />' 'line two</p>' '<p style=\"Margin: 0 0 20px 0;", "), ( # tab '* one\\n' '* two\\n' '* three\\n'", "expected', ( [ notify_letter_preview_markdown, 'print(\"hello\")' ], [ notify_email_markdown, 'print(\"hello\")' ],", "0.1px 15px; font-size: 19px; line-height: 25px;' '\">' '<p style=\"Margin: 0", "indicating a parenthesis or ' 'pause \\u2013 and the spaced", "http://example.com' ), ], )) def test_link(markdown_function, expected): assert markdown_function( '[Example](http://example.com)'", "---- dash', ), ( 'em — dash', 'em – dash',", "marks=pytest.mark.xfail(raises=AssertionError)), ( # bullet as bullet '• one\\n' '• two\\n'", "expected): assert markdown_function( 'line one\\n' 'line two\\n' '\\n' 'new paragraph'", "'pause \\u2013 and the spaced em dash both have a", "'before<p><cr>after', ), ( 'before<cr><cr><np>after', 'before<cr><np>after', ), ( 'before{}<np>after'.format('<cr>' * 4),", "\"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>‘)\"\"\", # noqa ), (", ")) def test_autolink(markdown_function, link, expected): assert markdown_function(link) == expected @pytest.mark.parametrize('markdown_function,", "[ notify_letter_preview_markdown, ( '<p>a</p>' '<div class=\"page-break\">&nbsp;</div>' '<p>b</p>' ) ], [", "15px 0 0.1px 15px; font-size: 19px; line-height: 25px;' '\">' '<p", "three\\n' ), ( # tab '* one\\n' '* two\\n' '*", "word', ), ( 'bonjour | hi', 'bonjour | hi', ),", "test_strip_and_remove_obscure_whitespace_only_removes_normal_whitespace_from_ends(): sentence = ' words \\n over multiple lines with", "paragraph' '</p>' )), (notify_plain_text_email_markdown, ( '\\n' '\\nhttps://example.com' '\\n' '\\nNext paragraph'", "\\ttabs\\t ' assert strip_and_remove_obscure_whitespace(sentence) == 'words \\n over multiple lines", "bar' ) == expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown ))", "( '<ul>' '<li>a</li>' '<li>b</li>' '<li>c</li>' '</ul>' ) @pytest.mark.parametrize('value', [ 'bar',", "'</p>' '<p>' 'new paragraph' '</p>' ) ], [ notify_email_markdown, (", "assert markdown_function( 'something *important*' ) == expected @pytest.mark.parametrize('markdown_function, expected', (", "\"\"\"https://example.com\"style='text-decoration:blink'\"\"\", \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>'\"\"\", # noqa \"\"\"<a", ") ], [ notify_plain_text_email_markdown, ( '\\n' '\\nline one' '\\nline two'", ") == ( \"&lt;to cancel daily cat facts reply 'cancel'&gt;\"", "notify_plain_text_email_markdown )) def test_table(markdown_function): assert markdown_function( 'col | col\\n' '----|----\\n'", "to test this pass def test_sms_encode(): assert sms_encode('aàá…') == 'aàa...'", "), ( 'this is some text with a link '", "a parenthesis or ' 'pause \\u2013 and the spaced em", "(\"\"\" line one’s quote first.o'<EMAIL> is someone’s email address line", "'<li style=\"Margin: 5px 0 5px; padding: 0 0 0 5px;", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">new paragraph</p>'", "break-word; color: #005ea5;\" href=\"{}\">{}</a>'.format(url, url) assert (notify_email_markdown(url) == ( '<p", "[ notify_plain_text_email_markdown, '\\n\\nStrike' ], )) def test_strikethrough(markdown_function, expected): assert markdown_function('~~Strike~~')", "#0B0C0C;\">something *important*</p>' ], [ notify_plain_text_email_markdown, '\\n\\nsomething *important*', ], )) def", "line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(link)) @pytest.mark.parametrize('input, output', [", ") def test_URLs_get_escaped(url, expected_html, expected_html_in_template): assert notify_email_markdown(url) == ( '<p", "test_block_code(markdown_function, expected): assert markdown_function('```\\nprint(\"hello\")\\n```') == expected @pytest.mark.parametrize('markdown_function, expected', ( [", "'+ two\\n' '+ three\\n' ), marks=pytest.mark.xfail(raises=AssertionError)), ( # bullet as", "( [ notify_letter_preview_markdown, '<p>inset text</p>' ], [ notify_email_markdown, '<p style=\"Margin:", "assert markdown_function(link) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>variable", "expected', ( [ notify_email_markdown, '<p style=\"Margin: 0 0 20px 0;", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">foo", "expected def test_footnotes(): # Can’t work out how to test", "'Example' '</a>' '</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nExample", "'print(\"hello\")' ], ) ) def test_block_code(markdown_function, expected): assert markdown_function('```\\nprint(\"hello\")\\n```') ==", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">before</p>' '<p style=\"Margin:", "), ], )) def test_unordered_list(markdown, markdown_function, expected): assert markdown_function(markdown) ==", ")) def test_paragraphs(markdown_function, expected): assert markdown_function( 'line one\\n' 'line two\\n'", "], )) def test_autolink(markdown_function, link, expected): assert markdown_function(link) == expected", "'\\n' '\\nhttp://example.com' ), ], )) def test_autolink(markdown_function, link, expected): assert", "'\\n\\n+ one' '\\n\\n+ two' '\\n\\n+ three' ), ], )) def", "clean): assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dirty, clean', [ ( 'Hello", "one\\n' '* two\\n' '* three\\n' ), ( # two spaces", "( 'Hello Jo ,\\n\\nThis is a message', 'Hello Jo,\\n\\nThis is", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">new", "\"b\", \"b\"), ] ) def test_sms_message_adds_prefix(prefix, body, expected): template =", "], [ notify_email_markdown, ( '<blockquote ' 'style=\"Margin: 0 0 20px", "5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">two</li>' '<li style=\"Margin: 5px", "'line two' '</p>' '<p>' 'new paragraph' '</p>' ) ], [", "escape_html( \"<to cancel daily cat facts reply 'cancel'>\" ) ==", "markdown_function('a\\n\\n---\\n\\nb') == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<ol>\\n'", "0 0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">'", "advantage over the unspaced em dash. ' ), ), (", "3), ), ]) def test_tweaking_dvla_list_markup(markup, expected_fixed): assert tweak_dvla_list_markup(markup) == expected_fixed", "background: #BFC1C3; Margin: 30px 0 30px 0;\">' '<p style=\"Margin: 0", "( [ notify_letter_preview_markdown, '<p>variable called thing</p>' ], [ notify_email_markdown, '<p", "#005ea5;\" href=\"https://service.example.com/accept_invite/a1b2c3d4\">' 'https://service.example.com/accept_invite/a1b2c3d4' '</a>' ) in str(HTMLEmailTemplate({'content': ( 'You’ve been", "facts reply 'cancel'&gt;\" ) @pytest.mark.parametrize('dirty, clean', [ ( 'Hello ((name))", "in the middle' ), ( 'this is some text with", "break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">' 'https://example.com\"onclick=\"alert(\\'hi' '</a>\\')' '</p>' ) ], [", "#005ea5;\" href=\"http://example.com/?token=\">' 'http://example.com/?token=' '</a>' '<span class=\\'placeholder\\'>((token))</span>&amp;key=1' '</p>' ) @pytest.mark.parametrize( \"url,", "#BFC1C3; Margin: 30px 0 30px 0;\">' '<p style=\"Margin: 0 0", "'http://example.com/?token=' '</a>' '<span class=\\'placeholder\\'>((token))</span>&amp;key=1' '</p>' ) @pytest.mark.parametrize( \"url, expected_html, expected_html_in_template\",", "#0B0C0C;\">' 'Next paragraph' '</p>' )), (notify_plain_text_email_markdown, ( '\\n' '\\nhttps://example.com' '\\n'", "import ( unlink_govuk_escaped, notify_email_markdown, notify_letter_preview_markdown, notify_plain_text_email_markdown, sms_encode, formatted_list, strip_dvla_markup, strip_pipes,", "color: #0B0C0C;\">' 'heading' '</h2>' ) ], [ notify_plain_text_email_markdown, ( '\\n'", "'1. one\\n' '2. two\\n' '3. three\\n' ) == expected assert", "'* two\\n' '* three\\n' ), ( # dash as bullet", "\\t . word', '\\n. word', ), ]) def test_removing_whitespace_before_full_stops(dirty, clean):", "'<blockquote ' 'style=\"Margin: 0 0 20px 0; border-left: 10px solid", "a message' ), ( 'Hello Jo ,\\n\\nThis is a message',", "#0B0C0C;\">foo ****** bar</p>' ], [ notify_plain_text_email_markdown, '\\n\\nfoo ****** bar', ],", "'abc' def test_bleach_doesnt_try_to_make_valid_html_before_cleaning(): assert escape_html( \"<to cancel daily cat facts", "is a message', 'Hello Jo.\\n\\nThis is a message' ), (", "# two spaces '* one\\n' '* two\\n' '* three\\n' ),", "], [ notify_plain_text_email_markdown, ( '\\n' '\\nExample: http://example.com' ), ], ))", "notify_plain_text_email_markdown, ( '\\n' '\\n• one' '\\n• two' '\\n• three' ),", "'<ul>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ul>\\n' ) ], [ notify_email_markdown, (", "is a message' ), ( '\\n \\t . word', '\\n.", "' assert en_dash_replacement_sequence == space + en_dash assert non_breaking_space not", "== ( '<ul>' '<li>a</li>' '<li>b</li>' '<li>c</li>' '</ul>' ) @pytest.mark.parametrize('value', [", "assert replace_hyphens_with_en_dashes(nasty) == nice def test_unicode_dash_lookup(): en_dash_replacement_sequence = '\\u0020\\u2013' hyphen", "test_level_1_header(markdown_function, heading, expected): assert markdown_function(heading) == expected @pytest.mark.parametrize('markdown_function, expected', (", "cat facts reply 'cancel'&gt;\" ) @pytest.mark.parametrize('dirty, clean', [ ( 'Hello", "11pt; line-height: 25px; color: #0B0C0C;\">+ two</p>' '<p style=\"Margin: 0 0", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">something **important**</p>' ],", "line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(url) def test_handles_placeholders_in_urls(): assert", "def test_pluses_dont_render_as_lists(markdown_function, expected): assert markdown_function( '+ one\\n' '+ two\\n' '+", "test_formatted_list(items, kwargs, expected_output): assert formatted_list(items, **kwargs) == expected_output def test_formatted_list_returns_markup():", "test_tweaking_dvla_list_markup(markup, expected_fixed): assert tweak_dvla_list_markup(markup) == expected_fixed def test_make_list_from_linebreaks(): assert nl2li(", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ three</p>' ), ],", "'foo ‘1’'), ([1, 2, 3], {'before_each': 'a', 'after_each': 'b'}, 'a1b,", "notify_letter_preview_markdown, '<p>Strike</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0 20px", "is some text with a link http://example.com in the middle'", "notify_plain_text_email_markdown, 'http://example.com', ( '\\n' '\\nhttp://example.com' ), ], )) def test_autolink(markdown_function,", "markdown_function( '[Example](http://example.com \"An example URL\")' ) == expected @pytest.mark.parametrize('markdown_function, expected',", ") == ( '<p style=\"Margin: 0 0 20px 0; font-size:", "text</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0 20px 0;", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(expected_html)", "0 0 5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">one</li>' '<li", "), ( \"\"\"https://example.com\"style='text-decoration:blink'\"\"\", \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>'\"\"\", #", "def test_multiple_newlines_get_truncated(markdown_function, expected): assert markdown_function( 'before\\n\\n\\n\\n\\n\\nafter' ) == expected @pytest.mark.parametrize('markdown_function',", "strip_whitespace, strip_and_remove_obscure_whitespace, remove_smart_quotes_from_email_addresses, strip_unsupported_characters, normalise_whitespace ) from notifications_utils.template import (", "]) def test_tweaking_dvla_list_markup(markup, expected_fixed): assert tweak_dvla_list_markup(markup) == expected_fixed def test_make_list_from_linebreaks():", "0 0 20px 0; font-size: 11pt; line-height: 25px; ' 'color:", "dash - always with spaces in running text when, as", "), ]) def test_tweaking_dvla_list_markup(markup, expected_fixed): assert tweak_dvla_list_markup(markup) == expected_fixed def", "SMSPreviewTemplate ) @pytest.mark.parametrize( \"url\", [ \"http://example.com\", \"http://www.gov.uk/\", \"https://www.gov.uk/\", \"http://service.gov.uk\", \"http://service.gov.uk/blah.ext?q=a%20b%20c&order=desc#fragment\",", "]) def test_removing_whitespace_before_full_stops(dirty, clean): assert remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dumb, smart',", ") == ( '' ) @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "I said, “what about breakfast at Tiffany’s”?\"\"\", ), ( \"\"\"", "clean @pytest.mark.parametrize('dirty, clean', [ ( 'Hello ((name)) .\\n\\nThis is a", "is someone’s email address line ‘three’ \"\"\") == (\"\"\" line", "'a', 'after_each': 'b'}, 'a1b, a2b and a3b'), ([1, 2, 3],", "[ notify_letter_preview_markdown, '<p>Strike</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0", "notify_plain_text_email_markdown, sms_encode, formatted_list, strip_dvla_markup, strip_pipes, escape_html, remove_whitespace_before_punctuation, make_quotes_smart, replace_hyphens_with_en_dashes, tweak_dvla_list_markup,", "“what about breakfast at Tiffany’s”?\"\"\", ), ( \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a>", "a certain ' 'technical advantage over the unspaced em dash.", "), 'subject': ''})) @pytest.mark.parametrize('markdown_function, expected_output', [ (notify_email_markdown, ( '<p style=\"Margin:", "'', 'subject': subject}).subject @pytest.mark.parametrize( \"prefix, body, expected\", [ (\"a\", \"b\",", ".\", \"bonjour.\"), ('double -- dash', 'double \\u2013 dash'), ] )", "text' ), ], )) def test_block_quote(markdown_function, expected): assert markdown_function('^ inset", "expected): assert expected == HTMLEmailTemplate({'content': '', 'subject': subject}).subject @pytest.mark.parametrize( \"prefix,", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">something *important*</p>' ], [ notify_plain_text_email_markdown,", "#005ea5;\" href=\"http://example.com\">Example</a>' '</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nExample:", "'\\u0020\\u2013' hyphen = '-' en_dash = '–' space = '", "\\x0c ', '\\rn\\u200Coti\\u200Dfi\\u200Bcati\\u2060ons-\\u180Eemai\\uFEFFl\\uFEFF', ]) def test_strip_and_remove_obscure_whitespace(value): assert strip_and_remove_obscure_whitespace(value) == 'notifications-email'", "three\\n' ), ( # dash as bullet '- one\\n' '-", "'</p>' )), (notify_plain_text_email_markdown, ( '\\n' '\\nhttps://example.com' '\\n' '\\nNext paragraph' )),", "style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ol style=\"Margin: 0 0 0 20px;", "== expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>' 'line", "( # bullet as bullet '• one\\n' '• two\\n' '•", "[ notify_plain_text_email_markdown, ( '\\n' '\\na' '\\n' '\\n=================================================================' '\\n' '\\nb' ),", "hi\", \"bonjour | hi\"), (\"bonjour .\", \"bonjour.\"), ('double -- dash',", "markdown_function('```\\nprint(\"hello\")\\n```') == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>inset", "'</tr>' '</table>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\n• one'", "notify_email_markdown, notify_plain_text_email_markdown )) def test_table(markdown_function): assert markdown_function( 'col | col\\n'", "' ), ), ( 'double -- dash', 'double \\u2013 dash',", "[ notify_plain_text_email_markdown, '\\n\\nfoo ****** bar', ], )) def test_nested_emphasis(markdown_function, expected):", "[ notify_plain_text_email_markdown, 'print(\"hello\")' ], ) ) def test_block_code(markdown_function, expected): assert", "notify_email_markdown, notify_letter_preview_markdown, notify_plain_text_email_markdown, sms_encode, formatted_list, strip_dvla_markup, strip_pipes, escape_html, remove_whitespace_before_punctuation, make_quotes_smart,", "(\"https://gov.uk\", \"https://gov.uk\"), (\"https://www.gov.uk\", \"https://www.gov.uk\"), (\"www.gov.uk\", \"www.gov.uk\"), (\"gov.uk/register-to-vote\", \"gov.uk/register-to-vote\"), (\"gov.uk?q=\", \"gov.uk?q=\")", "#0B0C0C;\">' 'heading' '</h2>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\n'", "more <words>' '<cr><h1><h2><p><normal><op><np><bul><tab>' '<CR><H1><H2><P><NORMAL><OP><NP><BUL><TAB>' '<tAb>' ) ) == 'some words", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">a</p>' '<hr style=\"border:", ") == 'some words & some more <words>' def test_removing_pipes():", "normalise_whitespace ) from notifications_utils.template import ( HTMLEmailTemplate, PlainTextEmailTemplate, SMSMessageTemplate, SMSPreviewTemplate", "‘three’ \"\"\") == (\"\"\" line one’s quote first.o'<EMAIL> is someone’s", "style=\"padding: 0 0 20px 0;\">' '<tr>' '<td style=\"font-family: Helvetica, Arial,", ")), ]) def test_preserves_whitespace_when_making_links( markdown_function, expected_output ): assert markdown_function( 'https://example.com\\n'", "((name)) ,\\n\\nThis is a message', 'Hello ((name)),\\n\\nThis is a message'", "notify_plain_text_email_markdown, ( '\\n' '\\nExample (An example URL): http://example.com' ), ],", "markdown_function('~~Strike~~') == expected def test_footnotes(): # Can’t work out how", "expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown )) def test_table(markdown_function): assert", ") ], [ notify_plain_text_email_markdown, 'http://example.com', ( '\\n' '\\nhttp://example.com' ), ],", "''})) def test_HTML_template_has_URLs_replaced_with_links(): assert ( '<a style=\"word-wrap: break-word; color: #005ea5;\"", "'The en dash \\u2013 always with spaces in running text", "'</p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin: 0 0", "**kwargs) == expected_output def test_formatted_list_returns_markup(): assert isinstance(formatted_list([0]), Markup) def test_removing_dvla_markup():", "'*one\\n' '*two\\n' '*three\\n' ), ( # single space '* one\\n'", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>before</p>' '<p>after</p>' ) ],", "'\\n' '\\nExample: http://example.com' ), ], )) def test_link(markdown_function, expected): assert", "daily cat facts reply 'cancel'&gt;\" ) @pytest.mark.parametrize('dirty, clean', [ (", "| hi\", \"bonjour | hi\"), (\"bonjour .\", \"bonjour.\"), ('double --", "or ' 'pause - and the spaced em dash both", "bullet '• one\\n' '• two\\n' '• three\\n' ), )) @pytest.mark.parametrize('markdown_function,", "0 5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">two</li>' '<li style=\"Margin:", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">foo ****** bar</p>' ], [", "#005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>'\"\"\", # noqa \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>’\"\"\",", "strip_dvla_markup, strip_pipes, escape_html, remove_whitespace_before_punctuation, make_quotes_smart, replace_hyphens_with_en_dashes, tweak_dvla_list_markup, nl2li, strip_whitespace, strip_and_remove_obscure_whitespace,", "0 0 0 5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">two</li>'", "expected', ( [ notify_letter_preview_markdown, ( '<p>before</p>' '<p>after</p>' ) ], [", "called thing</p>' ], [ notify_plain_text_email_markdown, '\\n\\nvariable called thing', ], ))", "'\\n. word', ), ]) def test_removing_whitespace_before_full_stops(dirty, clean): assert remove_whitespace_before_punctuation(dirty) ==", "), ], )) def test_block_quote(markdown_function, expected): assert markdown_function('^ inset text')", "#0B0C0C;\">three</li>' '</ol>' '</td>' '</tr>' '</table>' ) ], [ notify_plain_text_email_markdown, (", "'{}' '</p>' ).format(link)) @pytest.mark.parametrize('input, output', [ ( ( 'this is", "nl2li( 'a\\n' 'b\\n' 'c\\n' ) == ( '<ul>' '<li>a</li>' '<li>b</li>'", "'print(\"hello\")' ], [ notify_plain_text_email_markdown, 'print(\"hello\")' ], ) ) def test_block_code(markdown_function,", "( [ notify_letter_preview_markdown, 'print(\"hello\")' ], [ notify_email_markdown, 'print(\"hello\")' ], [", "in brackets (http://example.com)' ), ( 'this link is in brackets", "== expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown )) def test_table(markdown_function):", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_email_markdown, '<p style=\"Margin: 0 0 20px", "#0B0C0C;\">inset text</p>' '</blockquote>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\ninset", "= ' words \\n over multiple lines with \\ttabs\\t '", "notify_plain_text_email_markdown, '\\n\\nsomething **important**', ], )) def test_double_emphasis(markdown_function, expected): assert markdown_function(", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">foo ****** bar</p>' ],", "@pytest.mark.parametrize('value', [ 'bar', ' bar ', \"\"\" \\t bar \"\"\",", "'\\n' '\\nNext paragraph' )), ]) def test_preserves_whitespace_when_making_links( markdown_function, expected_output ):", "'<br>' in str(template) @pytest.mark.parametrize( 'markdown_function, expected', ( [ notify_letter_preview_markdown, 'print(\"hello\")'", "\\u2013 dash', ), ( 'triple --- dash', 'triple \\u2013 dash',", "{}, '‘1’, ‘2’ and ‘3’'), ([1, 2, 3], {'prefix': 'foo',", "'\\n• one' '\\n• two' '\\n• three' ), ], )) def", "5px 0 5px; padding: 0 0 0 5px; font-size: 19px;'", "assert markdown_function( '[Example](http://example.com)' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">inset text</p>' '</blockquote>'", "text</p>' '</blockquote>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\ninset text'", "test_sms_encode(): assert sms_encode('aàá…') == 'aàa...' @pytest.mark.parametrize('items, kwargs, expected_output', [ ([1],", "‘1’'), ([1, 2, 3], {'before_each': 'a', 'after_each': 'b'}, 'a1b, a2b", "2, 3], {}, '‘1’, ‘2’ and ‘3’'), ([1, 2, 3],", ") == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>something important</p>'", "@pytest.mark.parametrize('markup, expected_fixed', [ ( 'a', 'a', ), ( 'before<p><cr><p><cr>after', 'before<p><cr>after',", "notify_letter_preview_markdown, '<p>+ one</p><p>+ two</p><p>+ three</p>', ], [ notify_email_markdown, ( '<p", "# no replacement ), ( 'bonjour | hi', 'bonjour |", "the quick brown fox \"\"\"}) template.prefix = None template.sender =", "nl2li, strip_whitespace, strip_and_remove_obscure_whitespace, remove_smart_quotes_from_email_addresses, strip_unsupported_characters, normalise_whitespace ) from notifications_utils.template import", "three' ), ], )) def test_ordered_list(markdown_function, expected): assert markdown_function( '1.", "unlink_govuk_escaped, notify_email_markdown, notify_letter_preview_markdown, notify_plain_text_email_markdown, sms_encode, formatted_list, strip_dvla_markup, strip_pipes, escape_html, remove_whitespace_before_punctuation,", "line-height: 25px; color: #0B0C0C;\">foo ****** bar</p>' ], [ notify_plain_text_email_markdown, '\\n\\nfoo", "], )) def test_codespan(markdown_function, expected): assert markdown_function( 'variable called `thing`'", "( [ notify_letter_preview_markdown, ( '<p>before</p>' '<p>after</p>' ) ], [ notify_email_markdown,", "'<span class=\\'placeholder\\'>((token))</span>&amp;key=1' '</p>' ) @pytest.mark.parametrize( \"url, expected_html, expected_html_in_template\", [ (", "0 0 0 5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">one</li>'", "def test_en_dashes(nasty, nice): assert replace_hyphens_with_en_dashes(nasty) == nice def test_unicode_dash_lookup(): en_dash_replacement_sequence", "19px;' 'line-height: 25px; color: #0B0C0C;\">three</li>' '</ul>' '</td>' '</tr>' '</table>' )", "], )) def test_paragraphs(markdown_function, expected): assert markdown_function( 'line one\\n' 'line", "test_bleach_doesnt_try_to_make_valid_html_before_cleaning(): assert escape_html( \"<to cancel daily cat facts reply 'cancel'>\"", "test_link_with_title(markdown_function, expected): assert markdown_function( '[Example](http://example.com \"An example URL\")' ) ==", "is a normal space character 'already\\u0020–\\u0020correct', ), ( '2004-2008', '2004-2008',", "assert markdown_function('## inset text') == (expected) @pytest.mark.parametrize('markdown_function, expected', ( [", "word', '\\n, word', ), ( 'bonjour | hi', 'bonjour |", "\\n over multiple lines with \\ttabs' def test_remove_smart_quotes_from_email_addresses(): assert remove_smart_quotes_from_email_addresses(\"\"\"", "brackets ' '(<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>)' ), )", "font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">one</li>' '<li style=\"Margin: 5px 0", "'<i>', 'after_each': '</i>'}, '<i>&amp;</i>'), ([1, 2, 3], {'before_each': '<i>', 'after_each':", "== expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown )) def test_image(markdown_function):", "pytest.param(\"http://service.gov.uk/blah.ext?q=one two three\", marks=pytest.mark.xfail), ] ) def test_makes_links_out_of_URLs(url): link =", "25px; color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' '</p>'", "# \\u0020 is a normal space character 'already\\u0020–\\u0020correct', ), (", "@pytest.mark.parametrize( \"url\", [ \"example.com\", \"www.example.com\", \"ftp://example.com\", \"<EMAIL>\", \"mailto:<EMAIL>\", \"<a href=\\\"https://example.com\\\">Example</a>\",", "test_ordered_list(markdown_function, expected): assert markdown_function( '1. one\\n' '2. two\\n' '3. three\\n'", "color: #0B0C0C;\">' '{}' '</p>' ).format(url) def test_handles_placeholders_in_urls(): assert notify_email_markdown( \"http://example.com/?token=<span", "def test_link(markdown_function, expected): assert markdown_function( '[Example](http://example.com)' ) == expected @pytest.mark.parametrize('markdown_function,", "'<i>1</i>, <i>2</i> and <i>3</i>'), ]) def test_formatted_list(items, kwargs, expected_output): assert", "= '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"{}\">{}</a>'.format(url, url) assert (notify_email_markdown(url)", "'bar' @pytest.mark.parametrize('value', [ 'notifications-email', ' \\tnotifications-email \\x0c ', '\\rn\\u200Coti\\u200Dfi\\u200Bcati\\u2060ons-\\u180Eemai\\uFEFFl\\uFEFF', ])", "( 'The en dash - always with spaces in running", "== expected assert markdown_function( '1.one\\n' '2.two\\n' '3.three\\n' ) == expected", "'<p>+ one</p><p>+ two</p><p>+ three</p>', ], [ notify_email_markdown, ( '<p style=\"Margin:", "'line one\\n' 'line two\\n' '\\n' 'new paragraph' ) == expected", "list-style-type: decimal;\">' '<li style=\"Margin: 5px 0 5px; padding: 0 0", "'+ two\\n' '+ three\\n' ) == expected @pytest.mark.parametrize('markdown_function, expected', (", "assert str(template) == expected def test_sms_preview_adds_newlines(): template = SMSPreviewTemplate({'content': \"\"\"", "' in the middle' ), ), ( ( 'this link", ",\\n\\nThis is a message', 'Hello ((name)),\\n\\nThis is a message' ),", "over the unspaced em dash. ' ), ), ( 'double", "color: #0B0C0C;\">inset text</p>' '</blockquote>' ) ], [ notify_plain_text_email_markdown, ( '\\n'", "in running text when, as ' 'discussed in this section,", "notify_plain_text_email_markdown )) def test_image(markdown_function): assert markdown_function( '![alt text](http://example.com/image.png)' ) ==", "], )) def test_nested_emphasis(markdown_function, expected): assert markdown_function( 'foo ****** bar'", "text with a link ' '<a style=\"word-wrap: break-word; color: #005ea5;\"", "first.o’<EMAIL> is someone’s email address line ‘three’ \"\"\") == (\"\"\"", "#005ea5;\" href=\"http://example.com\" title=\"An example URL\">' 'Example' '</a>' '</p>' ) ],", "remove_whitespace_before_punctuation(dirty) == clean @pytest.mark.parametrize('dumb, smart', [ ( \"\"\"And I said,", "20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">new paragraph</p>' )", "'![alt text](http://example.com/image.png)' ) == ( '' ) @pytest.mark.parametrize('markdown_function, expected', (", "'<p>b</p>' ) ], [ notify_email_markdown, ( '<p style=\"Margin: 0 0", "'prefix_plural': 'bar'}, 'foo ‘1’'), ([1, 2, 3], {'before_each': 'a', 'after_each':", ")) def test_multiple_newlines_get_truncated(markdown_function, expected): assert markdown_function( 'before\\n\\n\\n\\n\\n\\nafter' ) == expected", "[ notify_plain_text_email_markdown, ( '\\n' '\\nExample (An example URL): http://example.com' ),", "'foo ****** bar' ) == expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown,", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(link)) @pytest.mark.parametrize('input,", "[ \"example.com\", \"www.example.com\", \"ftp://example.com\", \"<EMAIL>\", \"mailto:<EMAIL>\", \"<a href=\\\"https://example.com\\\">Example</a>\", ] )", "def test_level_2_header(markdown_function, expected): assert markdown_function('## inset text') == (expected) @pytest.mark.parametrize('markdown_function,", ") ], [ notify_plain_text_email_markdown, ( '\\n' '\\nExample (An example URL):", "), ], )) def test_level_2_header(markdown_function, expected): assert markdown_function('## inset text')", "'\\n' '\\nb' ), ], )) def test_hrule(markdown_function, expected): assert markdown_function('a\\n\\n***\\n\\nb')", "'\\n' '\\ninset text' ), ], )) def test_block_quote(markdown_function, expected): assert", "25px; color: #0B0C0C;\">two</li>' '<li style=\"Margin: 5px 0 5px; padding: 0", "'* three\\n' ), ( # tab '* one\\n' '* two\\n'", "assert strip_unsupported_characters(\"line one\\u2028line two\") == (\"line oneline two\") def test_normalise_whitespace():", "body, expected): template = SMSMessageTemplate({'content': body}) template.prefix = prefix template.sender", "\"An example URL\")' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [", "three\\n' ), pytest.param(( # plus as bullet '+ one\\n' '+", "'{}' '</p>' ).format(expected_html) assert expected_html_in_template in str(HTMLEmailTemplate({'content': url, 'subject': ''}))", "( '<p>' 'line one<br>' 'line two' '</p>' '<p>' 'new paragraph'", "said, “what about breakfast at Tiffany’s”?\"\"\", ), ( \"\"\" <a", "25px; color: #0B0C0C;\">' '{}' '</p>' ).format(url) def test_handles_placeholders_in_urls(): assert notify_email_markdown(", "style=\"Margin: 0 0 0 20px; padding: 0; list-style-type: decimal;\">' '<li", "\"url\", [ \"example.com\", \"www.example.com\", \"ftp://example.com\", \"<EMAIL>\", \"mailto:<EMAIL>\", \"<a href=\\\"https://example.com\\\">Example</a>\", ]", "'</p>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\nExample: http://example.com' ),", "== expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>Example: <strong>example.com</strong></p>'", "), ], )) def test_multiple_newlines_get_truncated(markdown_function, expected): assert markdown_function( 'before\\n\\n\\n\\n\\n\\nafter' )", "\"subject,expected\", [ (\"bonjour | hi\", \"bonjour | hi\"), (\"bonjour .\",", "markdown_function( '+ one\\n' '+ two\\n' '+ three\\n' ) == expected", "nice', [ ( ( 'The en dash - always with", ") @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>Example: <strong>example.com</strong></p>' )", "'<i>', 'after_each': '</i>'}, '<i>1</i>, <i>2</i> and <i>3</i>'), ]) def test_formatted_list(items,", "expected_fixed def test_make_list_from_linebreaks(): assert nl2li( 'a\\n' 'b\\n' 'c\\n' ) ==", "0 0 0 20px; padding: 0; list-style-type: decimal;\">' '<li style=\"Margin:", "'b'}, 'a1b, a2b and a3b'), ([1, 2, 3], {'conjunction': 'foo'},", "'<ul style=\"Margin: 0 0 0 20px; padding: 0; list-style-type: disc;\">'", "expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<ol>\\n' '<li>one</li>\\n' '<li>two</li>\\n'", "assert isinstance(formatted_list([0]), Markup) def test_removing_dvla_markup(): assert strip_dvla_markup( ( 'some words", "assert notify_email_markdown(url) == ( '<p style=\"Margin: 0 0 20px 0;", "when, as ' 'discussed in this section, indicating a parenthesis", "([1, 2, 3], {}, '‘1’, ‘2’ and ‘3’'), ([1, 2,", "markdown_function( '[Example](http://example.com)' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "and the spaced em dash both have a certain '", "'<tr>' '<td style=\"font-family: Helvetica, Arial, sans-serif;\">' '<ol style=\"Margin: 0 0", "None assert str(template) == expected def test_sms_preview_adds_newlines(): template = SMSPreviewTemplate({'content':", "font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">two</li>' '<li style=\"Margin: 5px 0", "****** bar', ], )) def test_nested_emphasis(markdown_function, expected): assert markdown_function( 'foo", "(notify_plain_text_email_markdown, ( '\\n' '\\nhttps://example.com' '\\n' '\\nNext paragraph' )), ]) def", "break-word; color: #005ea5;\" href=\"https://example.com\">' 'https://example.com' '</a>' '</p>' '<p style=\"Margin: 0", "( '\\n' '\\nhttp://example.com' ), ], )) def test_autolink(markdown_function, link, expected):", "11pt; line-height: 25px; color: #0B0C0C;\">foo ****** bar</p>' ], [ notify_plain_text_email_markdown,", "0 0 20px; padding: 0; list-style-type: disc;\">' '<li style=\"Margin: 5px", "expected assert markdown_function( '1.one\\n' '2.two\\n' '3.three\\n' ) == expected @pytest.mark.parametrize('markdown',", "'* two\\n' '* three\\n' ), ( # tab '* one\\n'", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">Strike</p>' ], [ notify_plain_text_email_markdown,", "expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>Example: <strong>example.com</strong></p>' )", "== expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, ( '<p>inset text</p>'", "11pt; line-height: 25px; color: #0B0C0C;\">b</p>' ) ], [ notify_plain_text_email_markdown, (", ") def test_block_code(markdown_function, expected): assert markdown_function('```\\nprint(\"hello\")\\n```') == expected @pytest.mark.parametrize('markdown_function, expected',", "'*two\\n' '*three\\n' ), ( # single space '* one\\n' '*", "((name)) .\\n\\nThis is a message', 'Hello ((name)).\\n\\nThis is a message'", "section, indicating a parenthesis or ' 'pause \\u2013 and the", "def test_paragraphs(markdown_function, expected): assert markdown_function( 'line one\\n' 'line two\\n' '\\n'", "'\\nheading' '\\n-----------------------------------------------------------------' ), ], ) ) def test_level_1_header(markdown_function, heading, expected):", "'</ul>' ) @pytest.mark.parametrize('value', [ 'bar', ' bar ', \"\"\" \\t", "line one’s quote first.o’<EMAIL> is someone’s email address line ‘three’", "\"http://example.com/?token=<span class='placeholder'>((token))</span>&key=1\" ) == ( '<p style=\"Margin: 0 0 20px", "'subject': ''})) assert expected in str(HTMLEmailTemplate({'content': template_content, 'subject': ''})) @pytest.mark.parametrize(", "{'conjunction': 'foo'}, '‘1’, ‘2’ foo ‘3’'), (['&'], {'before_each': '<i>', 'after_each':", "‘3’'), ([1, 2, 3], {'prefix': 'foo', 'prefix_plural': 'bar'}, 'bar ‘1’,", "), ( 'already\\u0020–\\u0020correct', # \\u0020 is a normal space character", "(None, \"b\", \"b\"), ] ) def test_sms_message_adds_prefix(prefix, body, expected): template", "'\\n-----------------------------------------------------------------' ), ], ) ) def test_level_1_header(markdown_function, heading, expected): assert", "== 'aàa...' @pytest.mark.parametrize('items, kwargs, expected_output', [ ([1], {}, '‘1’'), ([1,", "\"http://service.gov.uk\", \"http://service.gov.uk/blah.ext?q=a%20b%20c&order=desc#fragment\", pytest.param(\"http://service.gov.uk/blah.ext?q=one two three\", marks=pytest.mark.xfail), ] ) def test_makes_links_out_of_URLs(url):", "[ notify_letter_preview_markdown, '<p>variable called thing</p>' ], [ notify_email_markdown, '<p style=\"Margin:", "\\u2013 and the spaced em dash both have a certain", "expected', ( [ notify_letter_preview_markdown, '<p>Strike</p>' ], [ notify_email_markdown, '<p style=\"Margin:", "str(template) @pytest.mark.parametrize( 'markdown_function, expected', ( [ notify_letter_preview_markdown, 'print(\"hello\")' ], [", "' \\tnotifications-email \\x0c ', '\\rn\\u200Coti\\u200Dfi\\u200Bcati\\u2060ons-\\u180Eemai\\uFEFFl\\uFEFF', ]) def test_strip_and_remove_obscure_whitespace(value): assert strip_and_remove_obscure_whitespace(value)", "0 30px 0;\">' '<p style=\"Margin: 0 0 20px 0; font-size:", "#0B0C0C;\">one</li>' '<li style=\"Margin: 5px 0 5px; padding: 0 0 0", "one’s quote first.o'<EMAIL> is someone’s email address line ‘three’ \"\"\")", "def test_level_1_header(markdown_function, heading, expected): assert markdown_function(heading) == expected @pytest.mark.parametrize('markdown_function, expected',", "'</tr>' '</table>' ) ], [ notify_plain_text_email_markdown, ( '\\n' '\\n1. one'", "in en_dash_replacement_sequence assert hyphen not in en_dash_replacement_sequence @pytest.mark.parametrize('markup, expected_fixed', [", "font-size: 11pt; line-height: 25px; color: #0B0C0C;\">inset text</p>' ], [ notify_plain_text_email_markdown,", "break-word; color: #005ea5;\" href=\"https://service.example.com/accept_invite/a1b2c3d4\">' 'https://service.example.com/accept_invite/a1b2c3d4' '</a>' ) in str(HTMLEmailTemplate({'content': (", "color: #005ea5;\" href=\"http://example.com\">http://example.com</a>' ' in the middle' ), ), (", "markdown_function( 'before\\n\\n\\n\\n\\n\\nafter' ) == expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown", "'after_each': '</i>'}, '<i>1</i>, <i>2</i> and <i>3</i>'), ]) def test_formatted_list(items, kwargs,", "), ( '2004-2008', '2004-2008', # no replacement ), ( 'bonjour", ") ], [ notify_plain_text_email_markdown, ( '\\n' '\\n' '\\nheading' '\\n-----------------------------------------------------------------' ),", "), ]) def test_smart_quotes(dumb, smart): assert make_quotes_smart(dumb) == smart @pytest.mark.parametrize('nasty,", "), ), ( 'double -- dash', 'double \\u2013 dash', ),", "def test_formatted_list(items, kwargs, expected_output): assert formatted_list(items, **kwargs) == expected_output def", "assert markdown_function('~~Strike~~') == expected def test_footnotes(): # Can’t work out", "'\\n=================================================================' '\\n' '\\nb' ), ], )) def test_hrule(markdown_function, expected): assert", "'' ) @pytest.mark.parametrize('markdown_function, link, expected', ( [ notify_letter_preview_markdown, 'http://example.com', '<p><strong>example.com</strong></p>'", "#005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>')\"\"\", # noqa \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>‘)\"\"\",", "#0B0C0C;\">' '{}' '</p>' ).format(url) def test_handles_placeholders_in_urls(): assert notify_email_markdown( \"http://example.com/?token=<span class='placeholder'>((token))</span>&key=1\"", "( [ notify_letter_preview_markdown, ( '<ol>\\n' '<li>one</li>\\n' '<li>two</li>\\n' '<li>three</li>\\n' '</ol>\\n' )", "expected def test_sms_preview_adds_newlines(): template = SMSPreviewTemplate({'content': \"\"\" the quick brown", "], [ notify_plain_text_email_markdown, ( '\\n' '\\nbefore' '\\n' '\\nafter' ), ],", "\"<a href=\\\"https://example.com\\\">Example</a>\", ] ) def test_doesnt_make_links_out_of_invalid_urls(url): assert notify_email_markdown(url) == (", "two' '\\n' '\\nnew paragraph' ), ], )) def test_paragraphs(markdown_function, expected):", "expected): assert markdown_function( '[Example](http://example.com \"An example URL\")' ) == expected", "), marks=pytest.mark.xfail(raises=AssertionError)), ( # bullet as bullet '• one\\n' '•", "Tiffany's\"?\"\"\", \"\"\"And I said, “what about breakfast at Tiffany’s”?\"\"\", ),", "sms_encode, formatted_list, strip_dvla_markup, strip_pipes, escape_html, remove_whitespace_before_punctuation, make_quotes_smart, replace_hyphens_with_en_dashes, tweak_dvla_list_markup, nl2li,", "def test_image(markdown_function): assert markdown_function( '![alt text](http://example.com/image.png)' ) == ( ''", "'https://example.com\\n' '\\n' 'Next paragraph' ) == expected_output @pytest.mark.parametrize( \"template_content,expected\", [", "line-height: 25px; color: #0B0C0C;\">+ two</p>' '<p style=\"Margin: 0 0 20px", "def test_block_quote(markdown_function, expected): assert markdown_function('^ inset text') == expected @pytest.mark.parametrize('heading',", "notify_plain_text_email_markdown, '\\n\\nStrike' ], )) def test_strikethrough(markdown_function, expected): assert markdown_function('~~Strike~~') ==", "'‘1’, ‘2’ and ‘3’'), ([1, 2, 3], {'prefix': 'foo', 'prefix_plural':", "unspaced em dash. ' ), ), ( 'double -- dash',", "( '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://service.example.com/accept_invite/a1b2c3d4\">' 'https://service.example.com/accept_invite/a1b2c3d4' '</a>' )", "== expected def test_footnotes(): # Can’t work out how to", "em dash. ' ), ), ( 'double -- dash', 'double", "href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>'\"\"\", # noqa \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>’\"\"\", #", "'color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\" title=\"An example", "one' '\\nline two' '\\n' '\\nnew paragraph' ), ], )) def", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">' '<a style=\"word-wrap: break-word;", ") ], [ notify_plain_text_email_markdown, ( '\\n' '\\na' '\\n' '\\n=================================================================' '\\n'", "test this pass def test_sms_encode(): assert sms_encode('aàá…') == 'aàa...' @pytest.mark.parametrize('items,", "25px; color: #0B0C0C;\">before</p>' '<p style=\"Margin: 0 0 20px 0; font-size:", "'http://example.com', ( '<p style=\"Margin: 0 0 20px 0; font-size: 11pt;", "running text when, as ' 'discussed in this section, indicating", "def test_codespan(markdown_function, expected): assert markdown_function( 'variable called `thing`' ) ==", ") ], [ notify_plain_text_email_markdown, ( '\\n' '\\nExample: http://example.com' ), ],", "0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">a</p>' '<hr style=\"border: 0;", "notify_letter_preview_markdown, ( '<p>a</p>' '<div class=\"page-break\">&nbsp;</div>' '<p>b</p>' ) ], [ notify_email_markdown,", "at Tiffany’s”?\"\"\", ), ( \"\"\" <a href=\"http://example.com?q='foo'\">http://example.com?q='foo'</a> \"\"\", \"\"\" <a", "# noqa \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22style=%27text-decoration:blink\">https://example.com\"style='text-decoration:blink</a>’\"\"\", # noqa", "#0B0C0C;\">two</li>' '<li style=\"Margin: 5px 0 5px; padding: 0 0 0", "notify_letter_preview_markdown, ( '<p>' 'line one<br>' 'line two' '</p>' '<p>' 'new", "'something **important**' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown,", "[ notify_plain_text_email_markdown, 'http://example.com', ( '\\n' '\\nhttp://example.com' ), ], )) def", "3], {'before_each': '<i>', 'after_each': '</i>'}, '<i>1</i>, <i>2</i> and <i>3</i>'), ])", "the spaced em dash both have a certain ' 'technical", "called thing', ], )) def test_codespan(markdown_function, expected): assert markdown_function( 'variable", "is a message' ), ( '\\n \\t , word', '\\n,", "( [ notify_letter_preview_markdown, '<h2>heading</h2>\\n' ], [ notify_email_markdown, ( '<h2 style=\"Margin:", "height: 1px; background: #BFC1C3; Margin: 30px 0 30px 0;\">' '<p", "tab '* one\\n' '* two\\n' '* three\\n' ), ( #", "( [ notify_letter_preview_markdown, ( '<p>Example: <strong>example.com</strong></p>' ) ], [ notify_email_markdown,", "== ( '' ) @pytest.mark.parametrize('markdown_function, link, expected', ( [ notify_letter_preview_markdown,", "words & some more <words>' '<cr><h1><h2><p><normal><op><np><bul><tab>' '<CR><H1><H2><P><NORMAL><OP><NP><BUL><TAB>' '<tAb>' ) )", "clean', [ ( 'Hello ((name)) .\\n\\nThis is a message', 'Hello", "'\\nnew paragraph' ), ], )) def test_paragraphs(markdown_function, expected): assert markdown_function(", "( \"&lt;to cancel daily cat facts reply 'cancel'&gt;\" ) @pytest.mark.parametrize('dirty,", "== 'abc' def test_bleach_doesnt_try_to_make_valid_html_before_cleaning(): assert escape_html( \"<to cancel daily cat", "def test_sms_preview_adds_newlines(): template = SMSPreviewTemplate({'content': \"\"\" the quick brown fox", "= None assert '<br>' in str(template) @pytest.mark.parametrize( 'markdown_function, expected', (", "notify_email_markdown, 'http://example.com', ( '<p style=\"Margin: 0 0 20px 0; font-size:", "noqa \"\"\"<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">https://example.com\"onclick=\"alert('hi</a>‘)\"\"\", # noqa ),", "expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>something important</p>' ], [", "@pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>variable called thing</p>' ], [", "== expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>something important</p>' ],", "== expected @pytest.mark.parametrize('markdown_function, expected', ( [ notify_letter_preview_markdown, '<p>Strike</p>' ], [", "'<li>three</li>\\n' '</ol>\\n' ) ], [ notify_email_markdown, ( '<table role=\"presentation\" style=\"padding:", "11pt; line-height: 25px; color: #0B0C0C;\">' '{}' '</p>' ).format(link)) @pytest.mark.parametrize('input, output',", "([1, 2], {}, '‘1’ and ‘2’'), ([1, 2, 3], {},", "important</p>' ], [ notify_email_markdown, '<p style=\"Margin: 0 0 20px 0;", "0 0 5px; font-size: 19px;' 'line-height: 25px; color: #0B0C0C;\">three</li>' '</ul>'", "the unspaced em dash. ' ), ), ( 'double --", "style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com/?token=\">' 'http://example.com/?token=' '</a>' '<span class=\\'placeholder\\'>((token))</span>&amp;key=1' '</p>'", "', \"\"\" \\t bar \"\"\", ' \\u180E\\u200B \\u200C bar \\u200D", "def test_table(markdown_function): assert markdown_function( 'col | col\\n' '----|----\\n' 'val |", "[ (\"gov.uk\", u\"gov.\\u200Buk\"), (\"GOV.UK\", u\"GOV.\\u200BUK\"), (\"Gov.uk\", u\"Gov.\\u200Buk\"), (\"https://gov.uk\", \"https://gov.uk\"), (\"https://www.gov.uk\",", "****** bar' ) == expected @pytest.mark.parametrize('markdown_function', ( notify_letter_preview_markdown, notify_email_markdown, notify_plain_text_email_markdown", "color: #0B0C0C;\">' '<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"https://example.com%22onclick=%22alert%28%27hi\">' 'https://example.com\"onclick=\"alert(\\'hi' '</a>\\')'", "( 'The en dash \\u2013 always with spaces in running", "expected_html_in_template in str(HTMLEmailTemplate({'content': url, 'subject': ''})) def test_HTML_template_has_URLs_replaced_with_links(): assert (", "expected', ( [ notify_letter_preview_markdown, ( '<p>a</p>' '<div class=\"page-break\">&nbsp;</div>' '<p>b</p>' )", "), ( '\\n \\t , word', '\\n, word', ), (", "spaced em dash both have a certain ' 'technical advantage", "'(<a style=\"word-wrap: break-word; color: #005ea5;\" href=\"http://example.com\">http://example.com</a>)' ), ) ]) def", "[ notify_email_markdown, 'http://example.com', ( '<p style=\"Margin: 0 0 20px 0;", "markdown_function( 'something *important*' ) == expected @pytest.mark.parametrize('markdown_function, expected', ( [", "0 20px 0; font-size: 11pt; line-height: 25px; color: #0B0C0C;\">+ two</p>'", "dash', 'double \\u2013 dash', ), ( 'triple --- dash', 'triple", "link, expected', ( [ notify_letter_preview_markdown, 'http://example.com', '<p><strong>example.com</strong></p>' ], [ notify_email_markdown,", "link is in brackets ' '(<a style=\"word-wrap: break-word; color: #005ea5;\"" ]
[ "seems jolly rotten,\") banner_text(\"There's something you've forgotten!\") banner_text(\"And that's to", "== \"*\": print(\"*\" * screen_width) else: centred_text = text.center(screen_width -", "SPECIFIED WIDTH\") if text == \"*\": print(\"*\" * screen_width) else:", "* screen_width) else: centred_text = text.center(screen_width - 4) output_string =", "if len(text) > screen_width - 4: print(\"EEK!!\") print(\"THE TEXT IS", "sing,\") banner_text(\" \") banner_text(\"When you're feeling in the dumps,\") banner_text(\"Don't", "centred_text = text.center(screen_width - 4) output_string = \"**{0}**\".format(centred_text) print(output_string) banner_text(\"*\")", "silly chumps,\") banner_text(\"Just purse your lips and whistle - that's", "feeling in the dumps,\") banner_text(\"Don't be silly chumps,\") banner_text(\"Just purse", "[4, 2, 7, 5, 8, 3, 9, 6, 1] print(numbers.sort())", "look on the bright side of life...\") banner_text(\"If life seems", "> screen_width - 4: print(\"EEK!!\") print(\"THE TEXT IS TOO LONG", "\") banner_text(\"When you're feeling in the dumps,\") banner_text(\"Don't be silly", "screen_width) else: centred_text = text.center(screen_width - 4) output_string = \"**{0}**\".format(centred_text)", "lips and whistle - that's the thing!\") banner_text(\"And... always look", "dance and sing,\") banner_text(\" \") banner_text(\"When you're feeling in the", "you've forgotten!\") banner_text(\"And that's to laugh and smile and dance", "= 80 if len(text) > screen_width - 4: print(\"EEK!!\") print(\"THE", "in the dumps,\") banner_text(\"Don't be silly chumps,\") banner_text(\"Just purse your", "life seems jolly rotten,\") banner_text(\"There's something you've forgotten!\") banner_text(\"And that's", "= \"**{0}**\".format(centred_text) print(output_string) banner_text(\"*\") banner_text(\"Always look on the bright side", "your lips and whistle - that's the thing!\") banner_text(\"And... always", "whistle - that's the thing!\") banner_text(\"And... always look on the", "banner_text(\"*\") result = banner_text(\"Nothing is returned\") print(result) numbers = [4,", "and smile and dance and sing,\") banner_text(\" \") banner_text(\"When you're", "bright side of life...\") banner_text(\"If life seems jolly rotten,\") banner_text(\"There's", "- 4) output_string = \"**{0}**\".format(centred_text) print(output_string) banner_text(\"*\") banner_text(\"Always look on", "= text.center(screen_width - 4) output_string = \"**{0}**\".format(centred_text) print(output_string) banner_text(\"*\") banner_text(\"Always", "print(\"EEK!!\") print(\"THE TEXT IS TOO LONG TO FIT IN THE", "to laugh and smile and dance and sing,\") banner_text(\" \")", "banner_text(\"And... always look on the bright side of life...\") banner_text(\"*\")", "bright side of life...\") banner_text(\"*\") result = banner_text(\"Nothing is returned\")", "returned\") print(result) numbers = [4, 2, 7, 5, 8, 3,", "always look on the bright side of life...\") banner_text(\"*\") result", "side of life...\") banner_text(\"If life seems jolly rotten,\") banner_text(\"There's something", "- 4: print(\"EEK!!\") print(\"THE TEXT IS TOO LONG TO FIT", "that's to laugh and smile and dance and sing,\") banner_text(\"", "banner_text(text): screen_width = 80 if len(text) > screen_width - 4:", "print(result) numbers = [4, 2, 7, 5, 8, 3, 9,", "jolly rotten,\") banner_text(\"There's something you've forgotten!\") banner_text(\"And that's to laugh", "the bright side of life...\") banner_text(\"If life seems jolly rotten,\")", "banner_text(\"When you're feeling in the dumps,\") banner_text(\"Don't be silly chumps,\")", "= [4, 2, 7, 5, 8, 3, 9, 6, 1]", "the bright side of life...\") banner_text(\"*\") result = banner_text(\"Nothing is", "banner_text(\"If life seems jolly rotten,\") banner_text(\"There's something you've forgotten!\") banner_text(\"And", "is returned\") print(result) numbers = [4, 2, 7, 5, 8,", "WIDTH\") if text == \"*\": print(\"*\" * screen_width) else: centred_text", "banner_text(\"*\") banner_text(\"Always look on the bright side of life...\") banner_text(\"If", "len(text) > screen_width - 4: print(\"EEK!!\") print(\"THE TEXT IS TOO", "THE SPECIFIED WIDTH\") if text == \"*\": print(\"*\" * screen_width)", "that's the thing!\") banner_text(\"And... always look on the bright side", "laugh and smile and dance and sing,\") banner_text(\" \") banner_text(\"When", "4) output_string = \"**{0}**\".format(centred_text) print(output_string) banner_text(\"*\") banner_text(\"Always look on the", "<reponame>kumarvgit/python3 def banner_text(text): screen_width = 80 if len(text) > screen_width", "banner_text(\"Don't be silly chumps,\") banner_text(\"Just purse your lips and whistle", "LONG TO FIT IN THE SPECIFIED WIDTH\") if text ==", "if text == \"*\": print(\"*\" * screen_width) else: centred_text =", "- that's the thing!\") banner_text(\"And... always look on the bright", "text.center(screen_width - 4) output_string = \"**{0}**\".format(centred_text) print(output_string) banner_text(\"*\") banner_text(\"Always look", "TOO LONG TO FIT IN THE SPECIFIED WIDTH\") if text", "else: centred_text = text.center(screen_width - 4) output_string = \"**{0}**\".format(centred_text) print(output_string)", "screen_width = 80 if len(text) > screen_width - 4: print(\"EEK!!\")", "you're feeling in the dumps,\") banner_text(\"Don't be silly chumps,\") banner_text(\"Just", "the thing!\") banner_text(\"And... always look on the bright side of", "print(\"THE TEXT IS TOO LONG TO FIT IN THE SPECIFIED", "\"*\": print(\"*\" * screen_width) else: centred_text = text.center(screen_width - 4)", "banner_text(\" \") banner_text(\"When you're feeling in the dumps,\") banner_text(\"Don't be", "IS TOO LONG TO FIT IN THE SPECIFIED WIDTH\") if", "result = banner_text(\"Nothing is returned\") print(result) numbers = [4, 2,", "TEXT IS TOO LONG TO FIT IN THE SPECIFIED WIDTH\")", "banner_text(\"Nothing is returned\") print(result) numbers = [4, 2, 7, 5,", "side of life...\") banner_text(\"*\") result = banner_text(\"Nothing is returned\") print(result)", "thing!\") banner_text(\"And... always look on the bright side of life...\")", "smile and dance and sing,\") banner_text(\" \") banner_text(\"When you're feeling", "print(\"*\" * screen_width) else: centred_text = text.center(screen_width - 4) output_string", "text == \"*\": print(\"*\" * screen_width) else: centred_text = text.center(screen_width", "def banner_text(text): screen_width = 80 if len(text) > screen_width -", "of life...\") banner_text(\"*\") result = banner_text(\"Nothing is returned\") print(result) numbers", "dumps,\") banner_text(\"Don't be silly chumps,\") banner_text(\"Just purse your lips and", "print(output_string) banner_text(\"*\") banner_text(\"Always look on the bright side of life...\")", "life...\") banner_text(\"*\") result = banner_text(\"Nothing is returned\") print(result) numbers =", "and whistle - that's the thing!\") banner_text(\"And... always look on", "on the bright side of life...\") banner_text(\"*\") result = banner_text(\"Nothing", "and dance and sing,\") banner_text(\" \") banner_text(\"When you're feeling in", "= banner_text(\"Nothing is returned\") print(result) numbers = [4, 2, 7,", "numbers = [4, 2, 7, 5, 8, 3, 9, 6,", "the dumps,\") banner_text(\"Don't be silly chumps,\") banner_text(\"Just purse your lips", "and sing,\") banner_text(\" \") banner_text(\"When you're feeling in the dumps,\")", "TO FIT IN THE SPECIFIED WIDTH\") if text == \"*\":", "life...\") banner_text(\"If life seems jolly rotten,\") banner_text(\"There's something you've forgotten!\")", "forgotten!\") banner_text(\"And that's to laugh and smile and dance and", "banner_text(\"And that's to laugh and smile and dance and sing,\")", "something you've forgotten!\") banner_text(\"And that's to laugh and smile and", "chumps,\") banner_text(\"Just purse your lips and whistle - that's the", "IN THE SPECIFIED WIDTH\") if text == \"*\": print(\"*\" *", "output_string = \"**{0}**\".format(centred_text) print(output_string) banner_text(\"*\") banner_text(\"Always look on the bright", "look on the bright side of life...\") banner_text(\"*\") result =", "purse your lips and whistle - that's the thing!\") banner_text(\"And...", "banner_text(\"Just purse your lips and whistle - that's the thing!\")", "screen_width - 4: print(\"EEK!!\") print(\"THE TEXT IS TOO LONG TO", "FIT IN THE SPECIFIED WIDTH\") if text == \"*\": print(\"*\"", "\"**{0}**\".format(centred_text) print(output_string) banner_text(\"*\") banner_text(\"Always look on the bright side of", "rotten,\") banner_text(\"There's something you've forgotten!\") banner_text(\"And that's to laugh and", "4: print(\"EEK!!\") print(\"THE TEXT IS TOO LONG TO FIT IN", "banner_text(\"Always look on the bright side of life...\") banner_text(\"If life", "of life...\") banner_text(\"If life seems jolly rotten,\") banner_text(\"There's something you've", "be silly chumps,\") banner_text(\"Just purse your lips and whistle -", "on the bright side of life...\") banner_text(\"If life seems jolly", "banner_text(\"There's something you've forgotten!\") banner_text(\"And that's to laugh and smile", "80 if len(text) > screen_width - 4: print(\"EEK!!\") print(\"THE TEXT" ]
[ ".provider import Provider from .adapter import Adapter from .device import", ".adapter import Adapter from .device import Device from .gatt import", "Adapter from .device import Device from .gatt import GattService, GattCharacteristic,", "from .device import Device from .gatt import GattService, GattCharacteristic, GattDescriptor", "Provider from .adapter import Adapter from .device import Device from", "import Adapter from .device import Device from .gatt import GattService,", "from .provider import Provider from .adapter import Adapter from .device", "<reponame>acoomans/Adafruit_Python_BluefruitLE from .provider import Provider from .adapter import Adapter from", "import Provider from .adapter import Adapter from .device import Device", "from .adapter import Adapter from .device import Device from .gatt" ]
[ "axju.generic.basic import BasicWorker from axju.generic.execution import ExecutionWorker from axju.generic.template import", "from axju.generic.basic import BasicWorker from axju.generic.execution import ExecutionWorker from axju.generic.template", "import BasicWorker from axju.generic.execution import ExecutionWorker from axju.generic.template import TemplateWorker" ]
[ "print f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report =report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc',", "fchecksum = \"9145af38\" dsname = \"data11_7TeV.00177986.physics_Egamma.merge.AOD.r2276_p516_p523_tid310713_00\" report = {} #print", "\"\"\" # test S3 object store source = \"/bin/hostname\" #dest", "sitemover.get_data(gpfn, lfn, path, fsize, fchecksum, guid, **pdict) if gpfn.startswith(\"s3:\"): sitemover", "fsize, fchecksum, guid, **pdict) if gpfn.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand)", "#print f.findGlobalFilePath(lfn, dsname) #print f.getLocalROOTSetup() #path = \"root://atlas-objectstore.cern.ch//atlas/eventservice/2181626927\" # +", "= \"NTUP_PHOTON.01255150._000001.root.1\" localSize = None localChecksum = None print f.put_data(source,", "= 17848 localChecksum = \"89b93830\" print f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum,", "if surl.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover. put_data(source, surl,", "this scheme(%s)\" % destination, destination, fsize, fchecksum, config_sm.ARCH_DEFAULT if __name__", "lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize = 17848 localChecksum", "**kwrds): self._setup = setup_path self._useTimerCommand = useTimerCommand def get_data(self, gpfn,", "fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc', jobId=2730987843, jobsetID=2728044425,pandaProxySecretKey='') gpfn", "f.findGlobalFilePath(lfn, dsname) #print f.getLocalROOTSetup() #path = \"root://atlas-objectstore.cern.ch//atlas/eventservice/2181626927\" # + your", "2.0 (the \"License\"); # You may not use this file", "be used. \"\"\" copyCommand = \"objectstore\" checksum_command = \"adler32\" def", "gpfn.replace(\"s3+rucio\", \"s3\") if gpfn.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover.get_data(gpfn, lfn,", "source = \"/bin/hostname\" dest = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize", "report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc', jobId=2730987843, jobsetID=2728044425,pandaProxySecretKey='') gpfn = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" gpfn", "import xrootdObjectstoreSiteMover from S3ObjectstoreSiteMover import S3ObjectstoreSiteMover class objectstoreSiteMover(SiteMover.SiteMover): \"\"\" ObjectstoreSiteMover", "\"4261010441\" fchecksum = \"9145af38\" dsname = \"data11_7TeV.00177986.physics_Egamma.merge.AOD.r2276_p516_p523_tid310713_00\" report = {}", "config_sm import SiteMover from xrootdObjectstoreSiteMover import xrootdObjectstoreSiteMover from S3ObjectstoreSiteMover import", "experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc', jobId=2730987843, jobsetID=2728044425,pandaProxySecretKey='') gpfn = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\"", "return sitemover.get_data(gpfn, lfn, path, fsize, fchecksum, guid, **pdict) return -1,", "lfn = \"AOD.310713._000004.pool.root.1\" path = os.getcwd() fsize = \"4261010441\" fchecksum", "+ your .root filename\" \"\"\" source = \"/bin/hostname\" dest =", "self._useTimerCommand = useTimerCommand def get_data(self, gpfn, lfn, path, fsize=0, fchecksum=0,", "at # http://www.apache.org/licenses/LICENSE-2.0 # # Authors: # - <NAME>, <<EMAIL>>,", "use this file except in compliance with the License. #", "\"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" dest = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize = None", "sitemover found for this scheme(%s)\" % destination, destination, fsize, fchecksum,", "**pdict): # Get input parameters from pdict lfn = pdict.get('lfn',", "s1 = SiteInformation() #s1.getObjectstoresField(\"os_access_key\", \"eventservice\", queuename='BNL_EC2W2_MCORE') f = objectstoreSiteMover() gpfn", "\"/bin/hostname\" #dest = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" dest = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\"", "License. # You may obtain a copy of the License", "destination, fsize, fchecksum, **pdict) if surl.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand)", "\"/bin/hostname\" dest = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize = 17848", "localChecksum = \"89b93830\" print f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS',", "import config_sm import SiteMover from xrootdObjectstoreSiteMover import xrootdObjectstoreSiteMover from S3ObjectstoreSiteMover", "parameters from pdict lfn = pdict.get('lfn', '') logPath = pdict.get('logPath',", "print f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report =report, lfn=lfn,", "pdict.get('logPath', '') if logPath != \"\": surl = logPath else:", "= gpfn.replace(\"s3+rucio\", \"s3\") if gpfn.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover.get_data(gpfn,", ".root filename\" \"\"\" source = \"/bin/hostname\" dest = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/\" lfn", "= xrootdObjectstoreSiteMover(self.getSetup()) return sitemover. put_data(source, destination, fsize, fchecksum, **pdict) if", "% destination, destination, fsize, fchecksum, config_sm.ARCH_DEFAULT if __name__ == '__main__':", "self._setup = setup_path self._useTimerCommand = useTimerCommand def get_data(self, gpfn, lfn,", "= None print f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report", "fsize, fchecksum, **pdict) if surl.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return", "European Organization for Nuclear Research (CERN) # # Licensed under", "lfn = pdict.get('lfn', '') logPath = pdict.get('logPath', '') if logPath", "in compliance with the License. # You may obtain a", "{} #print f.getGlobalFilePaths(dsname) #print f.findGlobalFilePath(lfn, dsname) #print f.getLocalROOTSetup() #path =", "fchecksum, config_sm.ARCH_DEFAULT if __name__ == '__main__': os.environ['PilotHomeDir'] = os.getcwd() from", "gpfn = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" gpfn = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir", "gpfn = gpfn.replace(\"s3+rucio\", \"s3\") if gpfn.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return", "jobId=2730987843, jobsetID=2728044425,pandaProxySecretKey='') gpfn = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" gpfn = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/NTUP_PHOTON.01255150._000001.root.1\" lfn =", "a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # #", "path, fsize, fchecksum, guid, **pdict) return -1, \"No objectstore sitemover", "decide which ObjectstoreSiteMover implementation to be used. \"\"\" copyCommand =", "if gpfn.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover.get_data(gpfn, lfn, path, fsize,", "= \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize = None localChecksum =", "\"\"\" copyCommand = \"objectstore\" checksum_command = \"adler32\" def __init__(self, setup_path='',", "report =report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') \"\"\" # test S3 object store source", "None localChecksum = None print f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest',", "from configSiteMover import config_sm import SiteMover from xrootdObjectstoreSiteMover import xrootdObjectstoreSiteMover", "dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc', jobId=2730987843,", "sitemover.get_data(gpfn, lfn, path, fsize, fchecksum, guid, **pdict) return -1, \"No", "\"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize = None localChecksum = None", "surl = surl.replace(\"s3+rucio\", \"s3\") if surl.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return", "= pdict.get('logPath', '') if logPath != \"\": surl = logPath", "config_sm.ARCH_DEFAULT if __name__ == '__main__': os.environ['PilotHomeDir'] = os.getcwd() from SiteInformation", "fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc', jobId=2730987843, jobsetID=2728044425,pandaProxySecretKey='')", "ObjectstoreSiteMover It uses the url to decide which ObjectstoreSiteMover implementation", "f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report =report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc', jobId=2730987843,", "the License. # You may obtain a copy of the", "= {} #print f.getGlobalFilePaths(dsname) #print f.findGlobalFilePath(lfn, dsname) #print f.getLocalROOTSetup() #path", "\"s3\") if gpfn.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover.get_data(gpfn, lfn, path,", "else: surl = os.path.join(destination, lfn) surl = surl.replace(\"s3+rucio\", \"s3\") if", "\"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize = 17848 localChecksum = \"89b93830\"", "for this scheme(%s)\" % gpfn def put_data(self, source, destination, fsize=0,", "objectstoreSiteMover.py import os from configSiteMover import config_sm import SiteMover from", "S3ObjectstoreSiteMover class objectstoreSiteMover(SiteMover.SiteMover): \"\"\" ObjectstoreSiteMover It uses the url to", "= \"/bin/hostname\" #dest = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" dest = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/\" lfn =", "Version 2.0 (the \"License\"); # You may not use this", "\"objectstore\" checksum_command = \"adler32\" def __init__(self, setup_path='', useTimerCommand=True, *args, **kwrds):", "with the License. # You may obtain a copy of", "surl = os.path.join(destination, lfn) surl = surl.replace(\"s3+rucio\", \"s3\") if surl.startswith(\"root:\"):", "path, fsize, fchecksum, guid, **pdict) if gpfn.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(),", "dest = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize = 17848 localChecksum", "prodSourceLabel='ptest', experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc', jobId=2730987843, jobsetID=2728044425,pandaProxySecretKey='') gpfn =", "gpfn def put_data(self, source, destination, fsize=0, fchecksum=0, **pdict): # Get", "\"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize = None localChecksum = None", "used. \"\"\" copyCommand = \"objectstore\" checksum_command = \"adler32\" def __init__(self,", "compliance with the License. # You may obtain a copy", "\"nonsens_gpfn\" lfn = \"AOD.310713._000004.pool.root.1\" path = os.getcwd() fsize = \"4261010441\"", "= logPath else: surl = os.path.join(destination, lfn) surl = surl.replace(\"s3+rucio\",", "__name__ == '__main__': os.environ['PilotHomeDir'] = os.getcwd() from SiteInformation import SiteInformation", "= \"AOD.310713._000004.pool.root.1\" path = os.getcwd() fsize = \"4261010441\" fchecksum =", "lfn, path, fsize, fchecksum, guid, **pdict) if gpfn.startswith(\"s3:\"): sitemover =", "(CERN) # # Licensed under the Apache License, Version 2.0", "f.getGlobalFilePaths(dsname) #print f.findGlobalFilePath(lfn, dsname) #print f.getLocalROOTSetup() #path = \"root://atlas-objectstore.cern.ch//atlas/eventservice/2181626927\" #", "License at # http://www.apache.org/licenses/LICENSE-2.0 # # Authors: # - <NAME>,", "#dest = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" dest = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize", "= \"/bin/hostname\" dest = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize =", "copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Authors:", "except in compliance with the License. # You may obtain", "fchecksum=0, **pdict): # Get input parameters from pdict lfn =", "Authors: # - <NAME>, <<EMAIL>>, 2014 # objectstoreSiteMover.py import os", "gpfn.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover.get_data(gpfn, lfn, path, fsize, fchecksum,", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "= \"data11_7TeV.00177986.physics_Egamma.merge.AOD.r2276_p516_p523_tid310713_00\" report = {} #print f.getGlobalFilePaths(dsname) #print f.findGlobalFilePath(lfn, dsname)", "None print f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report =report,", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "useTimerCommand def get_data(self, gpfn, lfn, path, fsize=0, fchecksum=0, guid=0, **pdict):", "\"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize = None", "Research (CERN) # # Licensed under the Apache License, Version", "your .root filename\" \"\"\" source = \"/bin/hostname\" dest = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/\"", "from pdict lfn = pdict.get('lfn', '') logPath = pdict.get('logPath', '')", "f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc')", "found for this scheme(%s)\" % destination, destination, fsize, fchecksum, config_sm.ARCH_DEFAULT", "gpfn = \"nonsens_gpfn\" lfn = \"AOD.310713._000004.pool.root.1\" path = os.getcwd() fsize", "None localChecksum = None print f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum,", "os.environ['PilotHomeDir'] = os.getcwd() from SiteInformation import SiteInformation s1 = SiteInformation()", "fchecksum, **pdict) return -1, \"No objectstore sitemover found for this", "sitemover. put_data(source, destination, fsize, fchecksum, **pdict) if surl.startswith(\"s3:\"): sitemover =", "fchecksum=0, guid=0, **pdict): gpfn = gpfn.replace(\"s3+rucio\", \"s3\") if gpfn.startswith(\"root:\"): sitemover", "lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc', jobId=2730987843, jobsetID=2728044425,pandaProxySecretKey='') gpfn = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" gpfn = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/NTUP_PHOTON.01255150._000001.root.1\"", "= \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" gpfn = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir =", "Apache License, Version 2.0 (the \"License\"); # You may not", "localChecksum = None print f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS',", "\"/tmp/\" localSize = 17848 localChecksum = \"89b93830\" print f.get_data(gpfn, lfn,", "'__main__': os.environ['PilotHomeDir'] = os.getcwd() from SiteInformation import SiteInformation s1 =", "fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') gpfn =", "prodSourceLabel='ptest', experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') gpfn = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/NTUP_PHOTON.01255150._000001.root.1\" lfn", "# objectstoreSiteMover.py import os from configSiteMover import config_sm import SiteMover", "fsize, fchecksum, guid, **pdict) return -1, \"No objectstore sitemover found", "put_data(self, source, destination, fsize=0, fchecksum=0, **pdict): # Get input parameters", "\"89b93830\" print f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report =report,", "= \"9145af38\" dsname = \"data11_7TeV.00177986.physics_Egamma.merge.AOD.r2276_p516_p523_tid310713_00\" report = {} #print f.getGlobalFilePaths(dsname)", "lfn, path, fsize, fchecksum, guid, **pdict) return -1, \"No objectstore", "fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') gpfn = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/NTUP_PHOTON.01255150._000001.root.1\"", "= 17848 localChecksum = \"89b93830\" print f.get_data(gpfn, lfn, tmpDir, fsize=localSize,", "2014 # objectstoreSiteMover.py import os from configSiteMover import config_sm import", "lfn) surl = surl.replace(\"s3+rucio\", \"s3\") if surl.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup())", "logPath = pdict.get('logPath', '') if logPath != \"\": surl =", "S3ObjectstoreSiteMover import S3ObjectstoreSiteMover class objectstoreSiteMover(SiteMover.SiteMover): \"\"\" ObjectstoreSiteMover It uses the", "import SiteInformation s1 = SiteInformation() #s1.getObjectstoresField(\"os_access_key\", \"eventservice\", queuename='BNL_EC2W2_MCORE') f =", "\"/tmp/\" localSize = None localChecksum = None print f.get_data(gpfn, lfn,", "gpfn, lfn, path, fsize=0, fchecksum=0, guid=0, **pdict): gpfn = gpfn.replace(\"s3+rucio\",", "= \"4261010441\" fchecksum = \"9145af38\" dsname = \"data11_7TeV.00177986.physics_Egamma.merge.AOD.r2276_p516_p523_tid310713_00\" report =", "SiteInformation import SiteInformation s1 = SiteInformation() #s1.getObjectstoresField(\"os_access_key\", \"eventservice\", queuename='BNL_EC2W2_MCORE') f", "pdict lfn = pdict.get('lfn', '') logPath = pdict.get('logPath', '') if", "jobsetID=2728044425,pandaProxySecretKey='') gpfn = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" gpfn = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\"", "return sitemover. put_data(source, destination, fsize, fchecksum, **pdict) if surl.startswith(\"s3:\"): sitemover", "-1, \"No objectstore sitemover found for this scheme(%s)\" % gpfn", "put_data(source, surl, fsize, fchecksum, **pdict) return -1, \"No objectstore sitemover", "lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') gpfn = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir =", "uses the url to decide which ObjectstoreSiteMover implementation to be", "guid=0, **pdict): gpfn = gpfn.replace(\"s3+rucio\", \"s3\") if gpfn.startswith(\"root:\"): sitemover =", "guid, **pdict) return -1, \"No objectstore sitemover found for this", "'') if logPath != \"\": surl = logPath else: surl", "License, Version 2.0 (the \"License\"); # You may not use", "fchecksum=localChecksum, experiment='ATLAS', report =report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') \"\"\" # test S3 object", "self._useTimerCommand) return sitemover.get_data(gpfn, lfn, path, fsize, fchecksum, guid, **pdict) return", "# - <NAME>, <<EMAIL>>, 2014 # objectstoreSiteMover.py import os from", "*args, **kwrds): self._setup = setup_path self._useTimerCommand = useTimerCommand def get_data(self,", "# Copyright European Organization for Nuclear Research (CERN) # #", "# You may not use this file except in compliance", "S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover. put_data(source, surl, fsize, fchecksum, **pdict) return", "this scheme(%s)\" % gpfn def put_data(self, source, destination, fsize=0, fchecksum=0,", "It uses the url to decide which ObjectstoreSiteMover implementation to", "to decide which ObjectstoreSiteMover implementation to be used. \"\"\" copyCommand", "guid, **pdict) if gpfn.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover.get_data(gpfn,", "may not use this file except in compliance with the", "localSize = 17848 localChecksum = \"89b93830\" print f.put_data(source, dest, fsize=localSize,", "xrootdObjectstoreSiteMover(self.getSetup()) return sitemover. put_data(source, destination, fsize, fchecksum, **pdict) if surl.startswith(\"s3:\"):", "f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc',", "= \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize =", "\"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" gpfn = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\"", "this file except in compliance with the License. # You", "fsize = \"4261010441\" fchecksum = \"9145af38\" dsname = \"data11_7TeV.00177986.physics_Egamma.merge.AOD.r2276_p516_p523_tid310713_00\" report", "queuename='BNL_EC2W2_MCORE') f = objectstoreSiteMover() gpfn = \"nonsens_gpfn\" lfn = \"AOD.310713._000004.pool.root.1\"", "tmpDir = \"/tmp/\" localSize = 17848 localChecksum = \"89b93830\" print", "print f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report =report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc')", "# + your .root filename\" \"\"\" source = \"/bin/hostname\" dest", "S3 object store source = \"/bin/hostname\" #dest = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" dest", "<NAME>, <<EMAIL>>, 2014 # objectstoreSiteMover.py import os from configSiteMover import", "copyCommand = \"objectstore\" checksum_command = \"adler32\" def __init__(self, setup_path='', useTimerCommand=True,", "useTimerCommand=True, *args, **kwrds): self._setup = setup_path self._useTimerCommand = useTimerCommand def", "**pdict) return -1, \"No objectstore sitemover found for this scheme(%s)\"", "# # Licensed under the Apache License, Version 2.0 (the", "surl.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover. put_data(source, surl, fsize,", "file except in compliance with the License. # You may", "**pdict): gpfn = gpfn.replace(\"s3+rucio\", \"s3\") if gpfn.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup())", "(the \"License\"); # You may not use this file except", "fchecksum, guid, **pdict) if gpfn.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return", "\"89b93830\" print f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report =report,", "import S3ObjectstoreSiteMover class objectstoreSiteMover(SiteMover.SiteMover): \"\"\" ObjectstoreSiteMover It uses the url", "import SiteMover from xrootdObjectstoreSiteMover import xrootdObjectstoreSiteMover from S3ObjectstoreSiteMover import S3ObjectstoreSiteMover", "import os from configSiteMover import config_sm import SiteMover from xrootdObjectstoreSiteMover", "destination, fsize, fchecksum, config_sm.ARCH_DEFAULT if __name__ == '__main__': os.environ['PilotHomeDir'] =", "# test S3 object store source = \"/bin/hostname\" #dest =", "os.getcwd() fsize = \"4261010441\" fchecksum = \"9145af38\" dsname = \"data11_7TeV.00177986.physics_Egamma.merge.AOD.r2276_p516_p523_tid310713_00\"", "the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Authors: # -", "#print f.getLocalROOTSetup() #path = \"root://atlas-objectstore.cern.ch//atlas/eventservice/2181626927\" # + your .root filename\"", "gpfn = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize", "return sitemover. put_data(source, surl, fsize, fchecksum, **pdict) return -1, \"No", "= S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover. put_data(source, surl, fsize, fchecksum, **pdict)", "sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover. put_data(source, surl, fsize, fchecksum,", "class objectstoreSiteMover(SiteMover.SiteMover): \"\"\" ObjectstoreSiteMover It uses the url to decide", "= \"/tmp/\" localSize = 17848 localChecksum = \"89b93830\" print f.get_data(gpfn,", "= os.getcwd() fsize = \"4261010441\" fchecksum = \"9145af38\" dsname =", "surl.replace(\"s3+rucio\", \"s3\") if surl.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover. put_data(source,", "__init__(self, setup_path='', useTimerCommand=True, *args, **kwrds): self._setup = setup_path self._useTimerCommand =", "source, destination, fsize=0, fchecksum=0, **pdict): # Get input parameters from", "from xrootdObjectstoreSiteMover import xrootdObjectstoreSiteMover from S3ObjectstoreSiteMover import S3ObjectstoreSiteMover class objectstoreSiteMover(SiteMover.SiteMover):", "sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover. put_data(source, destination, fsize, fchecksum, **pdict)", "object store source = \"/bin/hostname\" #dest = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" dest =", "lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize = 17848 localChecksum = \"89b93830\" print", "== '__main__': os.environ['PilotHomeDir'] = os.getcwd() from SiteInformation import SiteInformation s1", "scheme(%s)\" % destination, destination, fsize, fchecksum, config_sm.ARCH_DEFAULT if __name__ ==", "= S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover.get_data(gpfn, lfn, path, fsize, fchecksum, guid,", "= \"NTUP_PHOTON.01255150._000001.root.1\" localSize = 17848 localChecksum = \"89b93830\" print f.put_data(source,", "\"\": surl = logPath else: surl = os.path.join(destination, lfn) surl", "= xrootdObjectstoreSiteMover(self.getSetup()) return sitemover.get_data(gpfn, lfn, path, fsize, fchecksum, guid, **pdict)", "configSiteMover import config_sm import SiteMover from xrootdObjectstoreSiteMover import xrootdObjectstoreSiteMover from", "= \"adler32\" def __init__(self, setup_path='', useTimerCommand=True, *args, **kwrds): self._setup =", "filename\" \"\"\" source = \"/bin/hostname\" dest = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/\" lfn =", "localSize = None localChecksum = None print f.get_data(gpfn, lfn, tmpDir,", "objectstore sitemover found for this scheme(%s)\" % gpfn def put_data(self,", "You may not use this file except in compliance with", "!= \"\": surl = logPath else: surl = os.path.join(destination, lfn)", "of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Authors: #", "SiteInformation() #s1.getObjectstoresField(\"os_access_key\", \"eventservice\", queuename='BNL_EC2W2_MCORE') f = objectstoreSiteMover() gpfn = \"nonsens_gpfn\"", "\"No objectstore sitemover found for this scheme(%s)\" % destination, destination,", "% gpfn def put_data(self, source, destination, fsize=0, fchecksum=0, **pdict): #", "\"AOD.310713._000004.pool.root.1\" path = os.getcwd() fsize = \"4261010441\" fchecksum = \"9145af38\"", "#path = \"root://atlas-objectstore.cern.ch//atlas/eventservice/2181626927\" # + your .root filename\" \"\"\" source", "dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') gpfn", "for this scheme(%s)\" % destination, destination, fsize, fchecksum, config_sm.ARCH_DEFAULT if", "python # Copyright European Organization for Nuclear Research (CERN) #", "lfn, path, fsize=0, fchecksum=0, guid=0, **pdict): gpfn = gpfn.replace(\"s3+rucio\", \"s3\")", "#print f.getGlobalFilePaths(dsname) #print f.findGlobalFilePath(lfn, dsname) #print f.getLocalROOTSetup() #path = \"root://atlas-objectstore.cern.ch//atlas/eventservice/2181626927\"", "\"NTUP_PHOTON.01255150._000001.root.1\" localSize = None localChecksum = None print f.put_data(source, dest,", "sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover.get_data(gpfn, lfn, path, fsize, fchecksum,", "= os.path.join(destination, lfn) surl = surl.replace(\"s3+rucio\", \"s3\") if surl.startswith(\"root:\"): sitemover", "None print f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report =report,", "# http://www.apache.org/licenses/LICENSE-2.0 # # Authors: # - <NAME>, <<EMAIL>>, 2014", "surl, fsize, fchecksum, **pdict) return -1, \"No objectstore sitemover found", "may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0", "17848 localChecksum = \"89b93830\" print f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum,", "= \"/tmp/\" localSize = None localChecksum = None print f.get_data(gpfn,", "\"\"\" ObjectstoreSiteMover It uses the url to decide which ObjectstoreSiteMover", "self._useTimerCommand) return sitemover. put_data(source, surl, fsize, fchecksum, **pdict) return -1,", "if logPath != \"\": surl = logPath else: surl =", "dsname) #print f.getLocalROOTSetup() #path = \"root://atlas-objectstore.cern.ch//atlas/eventservice/2181626927\" # + your .root", "input parameters from pdict lfn = pdict.get('lfn', '') logPath =", "guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') gpfn = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\"", "fsize=0, fchecksum=0, guid=0, **pdict): gpfn = gpfn.replace(\"s3+rucio\", \"s3\") if gpfn.startswith(\"root:\"):", "Nuclear Research (CERN) # # Licensed under the Apache License,", "if gpfn.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover.get_data(gpfn, lfn, path,", "localChecksum = None print f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS',", "<filename>objectstoreSiteMover.py<gh_stars>10-100 #!/usr/bin/env python # Copyright European Organization for Nuclear Research", "sitemover found for this scheme(%s)\" % gpfn def put_data(self, source,", "destination, destination, fsize, fchecksum, config_sm.ARCH_DEFAULT if __name__ == '__main__': os.environ['PilotHomeDir']", "= \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize =", "= os.getcwd() from SiteInformation import SiteInformation s1 = SiteInformation() #s1.getObjectstoresField(\"os_access_key\",", "\"9145af38\" dsname = \"data11_7TeV.00177986.physics_Egamma.merge.AOD.r2276_p516_p523_tid310713_00\" report = {} #print f.getGlobalFilePaths(dsname) #print", "surl = logPath else: surl = os.path.join(destination, lfn) surl =", "def put_data(self, source, destination, fsize=0, fchecksum=0, **pdict): # Get input", "return sitemover.get_data(gpfn, lfn, path, fsize, fchecksum, guid, **pdict) if gpfn.startswith(\"s3:\"):", "report = {} #print f.getGlobalFilePaths(dsname) #print f.findGlobalFilePath(lfn, dsname) #print f.getLocalROOTSetup()", "= None localChecksum = None print f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum,", "SiteMover from xrootdObjectstoreSiteMover import xrootdObjectstoreSiteMover from S3ObjectstoreSiteMover import S3ObjectstoreSiteMover class", "sitemover. put_data(source, surl, fsize, fchecksum, **pdict) return -1, \"No objectstore", "=report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') \"\"\" # test S3 object store source =", "dsname = \"data11_7TeV.00177986.physics_Egamma.merge.AOD.r2276_p516_p523_tid310713_00\" report = {} #print f.getGlobalFilePaths(dsname) #print f.findGlobalFilePath(lfn,", "fsize, fchecksum, **pdict) return -1, \"No objectstore sitemover found for", "#s1.getObjectstoresField(\"os_access_key\", \"eventservice\", queuename='BNL_EC2W2_MCORE') f = objectstoreSiteMover() gpfn = \"nonsens_gpfn\" lfn", "fsize=0, fchecksum=0, **pdict): # Get input parameters from pdict lfn", "for Nuclear Research (CERN) # # Licensed under the Apache", "- <NAME>, <<EMAIL>>, 2014 # objectstoreSiteMover.py import os from configSiteMover", "to be used. \"\"\" copyCommand = \"objectstore\" checksum_command = \"adler32\"", "logPath != \"\": surl = logPath else: surl = os.path.join(destination,", "-1, \"No objectstore sitemover found for this scheme(%s)\" % destination,", "http://www.apache.org/licenses/LICENSE-2.0 # # Authors: # - <NAME>, <<EMAIL>>, 2014 #", "fchecksum, guid, **pdict) return -1, \"No objectstore sitemover found for", "which ObjectstoreSiteMover implementation to be used. \"\"\" copyCommand = \"objectstore\"", "\"adler32\" def __init__(self, setup_path='', useTimerCommand=True, *args, **kwrds): self._setup = setup_path", "surl.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover. put_data(source, destination, fsize, fchecksum,", "scheme(%s)\" % gpfn def put_data(self, source, destination, fsize=0, fchecksum=0, **pdict):", "= \"root://atlas-objectstore.cern.ch//atlas/eventservice/2181626927\" # + your .root filename\" \"\"\" source =", "# Authors: # - <NAME>, <<EMAIL>>, 2014 # objectstoreSiteMover.py import", "found for this scheme(%s)\" % gpfn def put_data(self, source, destination,", "def __init__(self, setup_path='', useTimerCommand=True, *args, **kwrds): self._setup = setup_path self._useTimerCommand", "xrootdObjectstoreSiteMover import xrootdObjectstoreSiteMover from S3ObjectstoreSiteMover import S3ObjectstoreSiteMover class objectstoreSiteMover(SiteMover.SiteMover): \"\"\"", "put_data(source, destination, fsize, fchecksum, **pdict) if surl.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(),", "**pdict) if surl.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover. put_data(source,", "=report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc', jobId=2730987843, jobsetID=2728044425,pandaProxySecretKey='') gpfn = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" gpfn =", "= \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize = 17848 localChecksum =", "lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize = None localChecksum", "objectstoreSiteMover(SiteMover.SiteMover): \"\"\" ObjectstoreSiteMover It uses the url to decide which", "localSize = 17848 localChecksum = \"89b93830\" print f.get_data(gpfn, lfn, tmpDir,", "Organization for Nuclear Research (CERN) # # Licensed under the", "fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report =report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') \"\"\" # test S3", "sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover.get_data(gpfn, lfn, path, fsize, fchecksum, guid,", "xrootdObjectstoreSiteMover(self.getSetup()) return sitemover.get_data(gpfn, lfn, path, fsize, fchecksum, guid, **pdict) if", "source = \"/bin/hostname\" #dest = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" dest = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/\" lfn", "implementation to be used. \"\"\" copyCommand = \"objectstore\" checksum_command =", "lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report =report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') \"\"\" #", "guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc', jobId=2730987843, jobsetID=2728044425,pandaProxySecretKey='') gpfn = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" gpfn = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/NTUP_PHOTON.01255150._000001.root.1\" lfn", "f = objectstoreSiteMover() gpfn = \"nonsens_gpfn\" lfn = \"AOD.310713._000004.pool.root.1\" path", "experiment='ATLAS', report =report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') \"\"\" # test S3 object store", "\"root://atlas-objectstore.cern.ch//atlas/eventservice/2181626927\" # + your .root filename\" \"\"\" source = \"/bin/hostname\"", "url to decide which ObjectstoreSiteMover implementation to be used. \"\"\"", "\"eventservice\", queuename='BNL_EC2W2_MCORE') f = objectstoreSiteMover() gpfn = \"nonsens_gpfn\" lfn =", "# You may obtain a copy of the License at", "os.getcwd() from SiteInformation import SiteInformation s1 = SiteInformation() #s1.getObjectstoresField(\"os_access_key\", \"eventservice\",", "gpfn.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover.get_data(gpfn, lfn, path, fsize,", "'') logPath = pdict.get('logPath', '') if logPath != \"\": surl", "f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report =report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') \"\"\"", "path, fsize=0, fchecksum=0, guid=0, **pdict): gpfn = gpfn.replace(\"s3+rucio\", \"s3\") if", "from SiteInformation import SiteInformation s1 = SiteInformation() #s1.getObjectstoresField(\"os_access_key\", \"eventservice\", queuename='BNL_EC2W2_MCORE')", "<<EMAIL>>, 2014 # objectstoreSiteMover.py import os from configSiteMover import config_sm", "xrootdObjectstoreSiteMover from S3ObjectstoreSiteMover import S3ObjectstoreSiteMover class objectstoreSiteMover(SiteMover.SiteMover): \"\"\" ObjectstoreSiteMover It", "= pdict.get('lfn', '') logPath = pdict.get('logPath', '') if logPath !=", "= \"nonsens_gpfn\" lfn = \"AOD.310713._000004.pool.root.1\" path = os.getcwd() fsize =", "= \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize = None localChecksum =", "def get_data(self, gpfn, lfn, path, fsize=0, fchecksum=0, guid=0, **pdict): gpfn", "get_data(self, gpfn, lfn, path, fsize=0, fchecksum=0, guid=0, **pdict): gpfn =", "fsize, fchecksum, config_sm.ARCH_DEFAULT if __name__ == '__main__': os.environ['PilotHomeDir'] = os.getcwd()", "logPath else: surl = os.path.join(destination, lfn) surl = surl.replace(\"s3+rucio\", \"s3\")", "S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover.get_data(gpfn, lfn, path, fsize, fchecksum, guid, **pdict)", "os.path.join(destination, lfn) surl = surl.replace(\"s3+rucio\", \"s3\") if surl.startswith(\"root:\"): sitemover =", "= None print f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report", "tmpDir = \"/tmp/\" localSize = None localChecksum = None print", "if __name__ == '__main__': os.environ['PilotHomeDir'] = os.getcwd() from SiteInformation import", "lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report =report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc', jobId=2730987843, jobsetID=2728044425,pandaProxySecretKey='<KEY>')", "\"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize = 17848 localChecksum = \"89b93830\"", "setup_path='', useTimerCommand=True, *args, **kwrds): self._setup = setup_path self._useTimerCommand = useTimerCommand", "obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 #", "\"NTUP_PHOTON.01255150._000001.root.1\" localSize = 17848 localChecksum = \"89b93830\" print f.put_data(source, dest,", "objectstore sitemover found for this scheme(%s)\" % destination, destination, fsize,", "checksum_command = \"adler32\" def __init__(self, setup_path='', useTimerCommand=True, *args, **kwrds): self._setup", "**pdict) if gpfn.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover.get_data(gpfn, lfn,", "pdict.get('lfn', '') logPath = pdict.get('logPath', '') if logPath != \"\":", "setup_path self._useTimerCommand = useTimerCommand def get_data(self, gpfn, lfn, path, fsize=0,", "\"No objectstore sitemover found for this scheme(%s)\" % gpfn def", "path = os.getcwd() fsize = \"4261010441\" fchecksum = \"9145af38\" dsname", "= objectstoreSiteMover() gpfn = \"nonsens_gpfn\" lfn = \"AOD.310713._000004.pool.root.1\" path =", "from S3ObjectstoreSiteMover import S3ObjectstoreSiteMover class objectstoreSiteMover(SiteMover.SiteMover): \"\"\" ObjectstoreSiteMover It uses", "fchecksum, **pdict) if surl.startswith(\"s3:\"): sitemover = S3ObjectstoreSiteMover(self.getSetup(), self._useTimerCommand) return sitemover.", "lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize = None localChecksum = None print", "if surl.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover. put_data(source, destination, fsize,", "Copyright European Organization for Nuclear Research (CERN) # # Licensed", "store source = \"/bin/hostname\" #dest = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" dest = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/\"", "ObjectstoreSiteMover implementation to be used. \"\"\" copyCommand = \"objectstore\" checksum_command", "destination, fsize=0, fchecksum=0, **pdict): # Get input parameters from pdict", "report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') gpfn = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\"", "test S3 object store source = \"/bin/hostname\" #dest = \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\"", "\"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize = 17848", "= \"89b93830\" print f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS', report", "return -1, \"No objectstore sitemover found for this scheme(%s)\" %", "os from configSiteMover import config_sm import SiteMover from xrootdObjectstoreSiteMover import", "under the Apache License, Version 2.0 (the \"License\"); # You", "\"s3\") if surl.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover. put_data(source, destination,", "= \"89b93830\" print f.get_data(gpfn, lfn, tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report", "# Get input parameters from pdict lfn = pdict.get('lfn', '')", "= \"s3://ceph003.usatlas.bnl.gov:8443//wguan_bucket/dir1/dir2/NTUP_PHOTON.01255150._000001.root.1\" dest = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize =", "\"data11_7TeV.00177986.physics_Egamma.merge.AOD.r2276_p516_p523_tid310713_00\" report = {} #print f.getGlobalFilePaths(dsname) #print f.findGlobalFilePath(lfn, dsname) #print", "f.getLocalROOTSetup() #path = \"root://atlas-objectstore.cern.ch//atlas/eventservice/2181626927\" # + your .root filename\" \"\"\"", "tmpDir, fsize=localSize, fchecksum=localChecksum, experiment='ATLAS', report =report, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') \"\"\" # test", "dest = \"s3://s3-us-west-2.amazonaws.com:80//s3-atlasdatadisk-west2-racf/dir1/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" localSize = None localChecksum", "experiment='ATLAS', report =report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') gpfn = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/NTUP_PHOTON.01255150._000001.root.1\" lfn =", "= setup_path self._useTimerCommand = useTimerCommand def get_data(self, gpfn, lfn, path,", "= surl.replace(\"s3+rucio\", \"s3\") if surl.startswith(\"root:\"): sitemover = xrootdObjectstoreSiteMover(self.getSetup()) return sitemover.", "gpfn = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize", "guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') \"\"\" # test S3 object store source = \"/bin/hostname\"", "= useTimerCommand def get_data(self, gpfn, lfn, path, fsize=0, fchecksum=0, guid=0,", "localChecksum = \"89b93830\" print f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest', experiment='ATLAS',", "\"\"\" source = \"/bin/hostname\" dest = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\"", "17848 localChecksum = \"89b93830\" print f.put_data(source, dest, fsize=localSize, fchecksum=localChecksum, prodSourceLabel='ptest',", "\"License\"); # You may not use this file except in", "You may obtain a copy of the License at #", "the url to decide which ObjectstoreSiteMover implementation to be used.", "localSize = None localChecksum = None print f.put_data(source, dest, fsize=localSize,", "SiteInformation s1 = SiteInformation() #s1.getObjectstoresField(\"os_access_key\", \"eventservice\", queuename='BNL_EC2W2_MCORE') f = objectstoreSiteMover()", "the Apache License, Version 2.0 (the \"License\"); # You may", "=report, lfn=lfn, guid='aa8ee1ae-54a5-468b-a0a0-41cf17477ffc') gpfn = \"root://eosatlas.cern.ch//eos/atlas/unpledged/group-wisc/users/wguan/NTUP_PHOTON.01255150._000001.root.1\" lfn = \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir", "= SiteInformation() #s1.getObjectstoresField(\"os_access_key\", \"eventservice\", queuename='BNL_EC2W2_MCORE') f = objectstoreSiteMover() gpfn =", "= \"NTUP_PHOTON.01255150._000001.root.1\" tmpDir = \"/tmp/\" localSize = 17848 localChecksum =", "Get input parameters from pdict lfn = pdict.get('lfn', '') logPath", "objectstoreSiteMover() gpfn = \"nonsens_gpfn\" lfn = \"AOD.310713._000004.pool.root.1\" path = os.getcwd()", "# # Authors: # - <NAME>, <<EMAIL>>, 2014 # objectstoreSiteMover.py", "= None localChecksum = None print f.get_data(gpfn, lfn, tmpDir, fsize=localSize,", "#!/usr/bin/env python # Copyright European Organization for Nuclear Research (CERN)", "= \"objectstore\" checksum_command = \"adler32\" def __init__(self, setup_path='', useTimerCommand=True, *args," ]
[ "gerar um gráfico com a biblioteca plotly.graph_objects def gera_grafico(tipo): #", "adicionando um estilo externo através do link abaixo # esse", "= go.Figure() # https://plotly.com/python/creating-and-updating-figures/ # adicionando um traço a figura", "representadas dessa forma, necessitando de módulos da biblioteca plotly para", "# o parâmetro style define estilos css para o componente", "dcc.Tab(label='Gráfico de Linha e Pontos',value='tab-3') ] ), # onde será", "da biblioteca plotly import plotly.graph_objects as go # adicionando um", "children=[ dcc.Tab(label='Gráfico de linha',value='tab-1'), dcc.Tab(label='Gráfico de Barra',value='tab-2'), dcc.Tab(label='Gráfico de Linha", "arquivo apresentado no vídeo do YouTube # Não deixe de", "onde será apresentado o conteúdo das abas logo após a", "# criando um layout para a variável app # adicionando", "de Linha e Pontos',value='tab-3') ] ), # onde será apresentado", "as bibliotecas necessárias import dash import dash_core_components as dcc import", "dash HTML components como título/cabeçalho do layout html.H2( ['Painel de", "# variável retornada pela função gera_grafico(tipo) return fig # criando", "# quando a aba com valor igual a 'tab-1' for", "Output # importando o módulo graph_objects da biblioteca plotly import", "criando a aplicação por meio da função Dash do pacote", "é o recomendado pela documentação da biblioteca Dash e ao", "'tabs-content' # receberá o gráfico de barras construído e retornado", "de linha',value='tab-1'), dcc.Tab(label='Gráfico de Barra',value='tab-2'), dcc.Tab(label='Gráfico de Linha e Pontos',value='tab-3')", "erro else: return html.Div(['Erro!']) # servindo a aplicação em dash", "para trabalhar com as informações fig = go.Figure() # https://plotly.com/python/creating-and-updating-figures/", "a figura fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], mode=tipo, name='Reta', ) )", "# criando uma figura # caso você faça print(fig), um", "modificações em relação ao arquivo apresentado no vídeo do YouTube", "do componente 'tabs-content' # receberá o gráfico de linha retornado", "abaixo elif tab == 'tab-2': fig_bar = go.Figure() fig_bar.add_trace( go.Bar(", "em relação ao arquivo apresentado no vídeo do YouTube #", "a aplicação em dash como versão para teste if __name__", "aplicação em dash como versão para teste if __name__ ==", "componente id='tabs', # criando as abas filhas dentro do parâmetro", "mensagem de erro else: return html.Div(['Erro!']) # servindo a aplicação", "gera_grafico('lines')) ]) # quando a aba com valor igual a", "plotly import plotly.graph_objects as go # adicionando um estilo externo", "estudar pela documentação ofical Dash # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # importando as", "que dão forma app.layout = html.Div([ # inserindo um componente", "dicionário será apresentado uma vez que as figuras podem ser", "forma app.layout = html.Div([ # inserindo um componente da biblioteca", "tab == 'tab-1': return html.Div([ dcc.Graph(figure = gera_grafico('lines')) ]) #", "fig_bar) ]) # quando a aba com valor igual a", "dash.dependencies import Input, Output # importando o módulo graph_objects da", "valor igual a 'tab-1' for selecionada, a propriedade children do", "faça print(fig), um dicionário será apresentado uma vez que as", "e saídas (output) @app.callback( # Output(component_id,component_property) Output('tabs-content','children'), [ # Input(component_id,component_property)", "apresentado no vídeo do YouTube # Não deixe de assistir", "dash from dash.dependencies import Input, Output # importando o módulo", "= dash.Dash( __name__, external_stylesheets=external_stylesheets ) # criando uma função para", "html # importando as funções que auxiliam no funcionamento das", "# Input(component_id,component_property) Input('tabs','value') ] ) # função que será chamada", "go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], ) ) fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], )", "layout html.H2( ['Painel de Visualização de Gráficos'], # o parâmetro", "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # importando as bibliotecas necessárias import dash import dash_core_components", "dash.Dash( __name__, external_stylesheets=external_stylesheets ) # criando uma função para gerar", "podem ser representadas dessa forma, necessitando de módulos da biblioteca", "retornado abaixo pela função gera_gráfico(tipo='lines') if tab == 'tab-1': return", "ele possui a estrutura de um arquivo CSS external_stylesheets =", "= fig_bar) ]) # quando a aba com valor igual", "YouTube # Não deixe de assistir o vídeo e estudar", "# quando a aba com valor igual a 'tab-3' for", "html.Div([ dcc.Graph(figure = fig_bar) ]) # quando a aba com", "linha retornado abaixo pela função gera_gráfico(tipo='lines+markers') elif tab == 'tab-3':", "componente 'tabs-content' # receberá o gráfico de barras construído e", "Dash do pacote dash e atribuindo a variável app app", "assim, retornamos a mensagem de erro else: return html.Div(['Erro!']) #", "um título ao gráfico fig.update_layout(title='Gráfico Exemplo') # variável retornada pela", "<filename>codigos_videos/Exemplo_2.py # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Esse arquivo possui algumas modificações em", "== 'tab-1': return html.Div([ dcc.Graph(figure = gera_grafico('lines')) ]) # quando", "linha',value='tab-1'), dcc.Tab(label='Gráfico de Barra',value='tab-2'), dcc.Tab(label='Gráfico de Linha e Pontos',value='tab-3') ]", "título ao gráfico fig.update_layout(title='Gráfico Exemplo') # variável retornada pela função", "que irá conter os demais componentes que dão forma app.layout", "gráfico fig.update_layout(title='Gráfico Exemplo') # variável retornada pela função gera_grafico(tipo) return", "dcc.Tab(label='Gráfico de linha',value='tab-1'), dcc.Tab(label='Gráfico de Barra',value='tab-2'), dcc.Tab(label='Gráfico de Linha e", "# receberá o gráfico de barras construído e retornado abaixo", "componente style={ 'textAlign':'center', # texto alinhado 'font-weight':'bold' # texto em", "(output) @app.callback( # Output(component_id,component_property) Output('tabs-content','children'), [ # Input(component_id,component_property) Input('tabs','value') ]", "a propriedade children do componente 'tabs-content' # receberá o gráfico", "'tab-3': return html.Div([ dcc.Graph(figure = gera_grafico('lines+markers')) ]) # caso nenhuma", "necessárias import dash import dash_core_components as dcc import dash_html_components as", "algumas modificações em relação ao arquivo apresentado no vídeo do", "dash_core_components as dcc import dash_html_components as html # importando as", "gera_grafico(tipo): # criando uma figura # caso você faça print(fig),", "o gráfico de linha retornado abaixo pela função gera_gráfico(tipo='lines+markers') elif", "das callbacks do subpacote dependencies do pacote dash from dash.dependencies", "os demais componentes que dão forma app.layout = html.Div([ #", "else: return html.Div(['Erro!']) # servindo a aplicação em dash como", "em negrito } ), # adicionando uma linha horizontal no", "possui algumas modificações em relação ao arquivo apresentado no vídeo", "return html.Div([ dcc.Graph(figure = gera_grafico('lines')) ]) # quando a aba", "negrito } ), # adicionando uma linha horizontal no layout", "retornado abaixo pela função gera_gráfico(tipo='lines+markers') elif tab == 'tab-3': return", "abas filhas dentro do parâmetro children da função Tabs() children=[", "aceitas, significa que existe um erro, e assim, retornamos a", "]) # Callback # estruturando a callback com as entradas", "print(fig), um dicionário será apresentado uma vez que as figuras", "estilos css para o componente style={ 'textAlign':'center', # texto alinhado", ") fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], mode=tipo, name='Parábola', ) ) #", "# esse link é o recomendado pela documentação da biblioteca", "(input) e saídas (output) @app.callback( # Output(component_id,component_property) Output('tabs-content','children'), [ #", "# importando o módulo graph_objects da biblioteca plotly import plotly.graph_objects", "@app.callback( # Output(component_id,component_property) Output('tabs-content','children'), [ # Input(component_id,component_property) Input('tabs','value') ] )", "uma linha horizontal no layout html.Hr(), # criando abas pai", "de Gráficos'], # o parâmetro style define estilos css para", "da função Tabs() children=[ dcc.Tab(label='Gráfico de linha',value='tab-1'), dcc.Tab(label='Gráfico de Barra',value='tab-2'),", "criando as abas filhas dentro do parâmetro children da função", "apresentado uma vez que as figuras podem ser representadas dessa", "a 'tab-3' for selecionada, a propriedade children do componente 'tabs-content'", "adicionando um título ao gráfico fig.update_layout(title='Gráfico Exemplo') # variável retornada", "necessitando de módulos da biblioteca plotly para trabalhar com as", "return fig # criando um layout para a variável app", "# importando as bibliotecas necessárias import dash import dash_core_components as", "import dash_html_components as html # importando as funções que auxiliam", "biblioteca plotly.graph_objects def gera_grafico(tipo): # criando uma figura # caso", "gráfico de barras construído e retornado abaixo elif tab ==", "), # adicionando uma linha horizontal no layout html.Hr(), #", "style={ 'textAlign':'center', # texto alinhado 'font-weight':'bold' # texto em negrito", "# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # importando as bibliotecas necessárias import dash import", ") ) fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], ) ) fig_bar.update_layout(title='Gráfico em", "# Não deixe de assistir o vídeo e estudar pela", "dessa forma, necessitando de módulos da biblioteca plotly para trabalhar", "meio da função Dash do pacote dash e atribuindo a", "for selecionada, a propriedade children do componente 'tabs-content' # receberá", "dcc.Graph(figure = gera_grafico('lines')) ]) # quando a aba com valor", "em Barras Exemplo') return html.Div([ dcc.Graph(figure = fig_bar) ]) #", "layout para a variável app # adicionando ao layout um", "do layout dcc.Tabs( # identidade/nome do componente id='tabs', # criando", "abas pai dentro do layout dcc.Tabs( # identidade/nome do componente", "você faça print(fig), um dicionário será apresentado uma vez que", "texto alinhado 'font-weight':'bold' # texto em negrito } ), #", "ao arquivo apresentado no vídeo do YouTube # Não deixe", "filhas dentro do parâmetro children da função Tabs() children=[ dcc.Tab(label='Gráfico", "de assistir o vídeo e estudar pela documentação ofical Dash", "update_tab(tab): # quando a aba com valor igual a 'tab-1'", "com valor igual a 'tab-1' for selecionada, a propriedade children", "bibliotecas necessárias import dash import dash_core_components as dcc import dash_html_components", "a callback ser ativada html.Div(id='tabs-content'), html.Hr(), ]) # Callback #", "conteúdo das abas logo após a callback ser ativada html.Div(id='tabs-content'),", "do YouTube # Não deixe de assistir o vídeo e", "a aplicação por meio da função Dash do pacote dash", "Dash # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # importando as bibliotecas necessárias import dash", ") ) fig_bar.update_layout(title='Gráfico em Barras Exemplo') return html.Div([ dcc.Graph(figure =", ") ) # adicionando um título ao gráfico fig.update_layout(title='Gráfico Exemplo')", "fig_bar.update_layout(title='Gráfico em Barras Exemplo') return html.Div([ dcc.Graph(figure = fig_bar) ])", "ao acessar esse link no seu navegador, # você perceberá", "from dash.dependencies import Input, Output # importando o módulo graph_objects", "como título/cabeçalho do layout html.H2( ['Painel de Visualização de Gráficos'],", "quando a aba com valor igual a 'tab-1' for selecionada,", "layout dcc.Tabs( # identidade/nome do componente id='tabs', # criando as", "# quando a aba com valor igual a 'tab-2' for", "perceberá que ele possui a estrutura de um arquivo CSS", "dash como versão para teste if __name__ == \"__main__\": app.run_server(debug=True)", "função gera_grafico(tipo) return fig # criando um layout para a", "ser ativada html.Div(id='tabs-content'), html.Hr(), ]) # Callback # estruturando a", "esse link é o recomendado pela documentação da biblioteca Dash", "criando um layout para a variável app # adicionando ao", "= html.Div([ # inserindo um componente da biblioteca dash HTML", "as html # importando as funções que auxiliam no funcionamento", "# servindo a aplicação em dash como versão para teste", "construído e retornado abaixo elif tab == 'tab-2': fig_bar =", "Esse arquivo possui algumas modificações em relação ao arquivo apresentado", "callback ser ativada html.Div(id='tabs-content'), html.Hr(), ]) # Callback # estruturando", "a variável app # adicionando ao layout um componente html.Div", "def gera_grafico(tipo): # criando uma figura # caso você faça", "components como título/cabeçalho do layout html.H2( ['Painel de Visualização de", "a callback com as entradas (input) e saídas (output) @app.callback(", "'tab-1' for selecionada, a propriedade children do componente 'tabs-content' #", "x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], ) ) fig_bar.update_layout(title='Gráfico em Barras Exemplo') return html.Div([", "y=[0,1,2,3,4,5,6], mode=tipo, name='Reta', ) ) fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], mode=tipo,", "mode=tipo, name='Reta', ) ) fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], mode=tipo, name='Parábola',", "abas logo após a callback ser ativada html.Div(id='tabs-content'), html.Hr(), ])", "a aba com valor igual a 'tab-2' for selecionada, a", "variável app # adicionando ao layout um componente html.Div que", "Input(component_id,component_property) Input('tabs','value') ] ) # função que será chamada pela", "figuras podem ser representadas dessa forma, necessitando de módulos da", "dcc.Tab(label='Gráfico de Barra',value='tab-2'), dcc.Tab(label='Gráfico de Linha e Pontos',value='tab-3') ] ),", "go.Figure() # https://plotly.com/python/creating-and-updating-figures/ # adicionando um traço a figura fig.add_trace(", "'tab-1': return html.Div([ dcc.Graph(figure = gera_grafico('lines')) ]) # quando a", "igual a 'tab-2' for selecionada, a propriedade children do componente", "css para o componente style={ 'textAlign':'center', # texto alinhado 'font-weight':'bold'", "Input('tabs','value') ] ) # função que será chamada pela callback", "por meio da função Dash do pacote dash e atribuindo", "forma, necessitando de módulos da biblioteca plotly para trabalhar com", "dash e atribuindo a variável app app = dash.Dash( __name__,", "logo após a callback ser ativada html.Div(id='tabs-content'), html.Hr(), ]) #", "receberá o gráfico de linha retornado abaixo pela função gera_gráfico(tipo='lines')", "função gera_gráfico(tipo='lines') if tab == 'tab-1': return html.Div([ dcc.Graph(figure =", "erro, e assim, retornamos a mensagem de erro else: return", ") ) fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], mode=tipo, name='Parábola', ) )", "define estilos css para o componente style={ 'textAlign':'center', # texto", "e retornado abaixo elif tab == 'tab-2': fig_bar = go.Figure()", "callbacks do subpacote dependencies do pacote dash from dash.dependencies import", "abaixo pela função gera_gráfico(tipo='lines') if tab == 'tab-1': return html.Div([", "]) # quando a aba com valor igual a 'tab-2'", "external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # criando a aplicação por meio da", "html.H2( ['Painel de Visualização de Gráficos'], # o parâmetro style", "componente da biblioteca dash HTML components como título/cabeçalho do layout", "será apresentado uma vez que as figuras podem ser representadas", "html.Div(id='tabs-content'), html.Hr(), ]) # Callback # estruturando a callback com", "# função que será chamada pela callback def update_tab(tab): #", "o vídeo e estudar pela documentação ofical Dash # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", "dcc.Graph(figure = gera_grafico('lines+markers')) ]) # caso nenhuma das condições acima", "entradas (input) e saídas (output) @app.callback( # Output(component_id,component_property) Output('tabs-content','children'), [", "relação ao arquivo apresentado no vídeo do YouTube # Não", "importando o módulo graph_objects da biblioteca plotly import plotly.graph_objects as", "estrutura de um arquivo CSS external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # criando", "pela função gera_grafico(tipo) return fig # criando um layout para", "import dash import dash_core_components as dcc import dash_html_components as html", "import dash_core_components as dcc import dash_html_components as html # importando", "e atribuindo a variável app app = dash.Dash( __name__, external_stylesheets=external_stylesheets", "trabalhar com as informações fig = go.Figure() # https://plotly.com/python/creating-and-updating-figures/ #", ") # adicionando um título ao gráfico fig.update_layout(title='Gráfico Exemplo') #", "style define estilos css para o componente style={ 'textAlign':'center', #", "ser representadas dessa forma, necessitando de módulos da biblioteca plotly", "pacote dash from dash.dependencies import Input, Output # importando o", "importando as funções que auxiliam no funcionamento das callbacks do", "condições acima sejam aceitas, significa que existe um erro, e", "um dicionário será apresentado uma vez que as figuras podem", "'textAlign':'center', # texto alinhado 'font-weight':'bold' # texto em negrito }", "funções que auxiliam no funcionamento das callbacks do subpacote dependencies", "Output('tabs-content','children'), [ # Input(component_id,component_property) Input('tabs','value') ] ) # função que", "go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], mode=tipo, name='Reta', ) ) fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6],", "em dash como versão para teste if __name__ == \"__main__\":", "de linha retornado abaixo pela função gera_gráfico(tipo='lines') if tab ==", "externo através do link abaixo # esse link é o", "# receberá o gráfico de linha retornado abaixo pela função", "sejam aceitas, significa que existe um erro, e assim, retornamos", "com a biblioteca plotly.graph_objects def gera_grafico(tipo): # criando uma figura", "html.Hr(), # criando abas pai dentro do layout dcc.Tabs( #", "Tabs() children=[ dcc.Tab(label='Gráfico de linha',value='tab-1'), dcc.Tab(label='Gráfico de Barra',value='tab-2'), dcc.Tab(label='Gráfico de", "aba com valor igual a 'tab-3' for selecionada, a propriedade", "do componente 'tabs-content' # receberá o gráfico de barras construído", "HTML components como título/cabeçalho do layout html.H2( ['Painel de Visualização", "Visualização de Gráficos'], # o parâmetro style define estilos css", "o recomendado pela documentação da biblioteca Dash e ao acessar", "componentes que dão forma app.layout = html.Div([ # inserindo um", "um componente da biblioteca dash HTML components como título/cabeçalho do", "que auxiliam no funcionamento das callbacks do subpacote dependencies do", "barras construído e retornado abaixo elif tab == 'tab-2': fig_bar", "pela callback def update_tab(tab): # quando a aba com valor", "caso nenhuma das condições acima sejam aceitas, significa que existe", "return html.Div([ dcc.Graph(figure = gera_grafico('lines+markers')) ]) # caso nenhuma das", "elif tab == 'tab-2': fig_bar = go.Figure() fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6],", "no funcionamento das callbacks do subpacote dependencies do pacote dash", ") fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], ) ) fig_bar.update_layout(title='Gráfico em Barras", "para o componente style={ 'textAlign':'center', # texto alinhado 'font-weight':'bold' #", "Barras Exemplo') return html.Div([ dcc.Graph(figure = fig_bar) ]) # quando", "callback def update_tab(tab): # quando a aba com valor igual", "# texto alinhado 'font-weight':'bold' # texto em negrito } ),", "importando as bibliotecas necessárias import dash import dash_core_components as dcc", "html.Div que irá conter os demais componentes que dão forma", "de Visualização de Gráficos'], # o parâmetro style define estilos", "para gerar um gráfico com a biblioteca plotly.graph_objects def gera_grafico(tipo):", "'tab-2' for selecionada, a propriedade children do componente 'tabs-content' #", "as dcc import dash_html_components as html # importando as funções", "possui a estrutura de um arquivo CSS external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']", "app # adicionando ao layout um componente html.Div que irá", "html.Div([ dcc.Graph(figure = gera_grafico('lines')) ]) # quando a aba com", "biblioteca plotly import plotly.graph_objects as go # adicionando um estilo", "uma vez que as figuras podem ser representadas dessa forma,", "a biblioteca plotly.graph_objects def gera_grafico(tipo): # criando uma figura #", "criando uma função para gerar um gráfico com a biblioteca", "navegador, # você perceberá que ele possui a estrutura de", "as funções que auxiliam no funcionamento das callbacks do subpacote", "a 'tab-2' for selecionada, a propriedade children do componente 'tabs-content'", "# caso nenhuma das condições acima sejam aceitas, significa que", "plotly.graph_objects def gera_grafico(tipo): # criando uma figura # caso você", "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Esse arquivo possui algumas modificações em relação ao", "# identidade/nome do componente id='tabs', # criando as abas filhas", "figura fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], mode=tipo, name='Reta', ) ) fig.add_trace(", ") fig_bar.update_layout(title='Gráfico em Barras Exemplo') return html.Div([ dcc.Graph(figure = fig_bar)", "do pacote dash e atribuindo a variável app app =", "Linha e Pontos',value='tab-3') ] ), # onde será apresentado o", "arquivo possui algumas modificações em relação ao arquivo apresentado no", "o gráfico de linha retornado abaixo pela função gera_gráfico(tipo='lines') if", "um traço a figura fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], mode=tipo, name='Reta',", "['https://codepen.io/chriddyp/pen/bWLwgP.css'] # criando a aplicação por meio da função Dash", "assistir o vídeo e estudar pela documentação ofical Dash #", "no seu navegador, # você perceberá que ele possui a", "pacote dash e atribuindo a variável app app = dash.Dash(", "da função Dash do pacote dash e atribuindo a variável", "módulos da biblioteca plotly para trabalhar com as informações fig", "parâmetro children da função Tabs() children=[ dcc.Tab(label='Gráfico de linha',value='tab-1'), dcc.Tab(label='Gráfico", "propriedade children do componente 'tabs-content' # receberá o gráfico de", "== 'tab-3': return html.Div([ dcc.Graph(figure = gera_grafico('lines+markers')) ]) # caso", "Gráficos'], # o parâmetro style define estilos css para o", "pela função gera_gráfico(tipo='lines') if tab == 'tab-1': return html.Div([ dcc.Graph(figure", "# adicionando um título ao gráfico fig.update_layout(title='Gráfico Exemplo') # variável", "nenhuma das condições acima sejam aceitas, significa que existe um", "html.Div([ dcc.Graph(figure = gera_grafico('lines+markers')) ]) # caso nenhuma das condições", "criando uma figura # caso você faça print(fig), um dicionário", "estilo externo através do link abaixo # esse link é", "= go.Figure() fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], ) ) fig_bar.add_trace( go.Bar(", "igual a 'tab-3' for selecionada, a propriedade children do componente", "children do componente 'tabs-content' # receberá o gráfico de barras", "# inserindo um componente da biblioteca dash HTML components como", "Exemplo') # variável retornada pela função gera_grafico(tipo) return fig #", "título/cabeçalho do layout html.H2( ['Painel de Visualização de Gráficos'], #", "receberá o gráfico de linha retornado abaixo pela função gera_gráfico(tipo='lines+markers')", "com as informações fig = go.Figure() # https://plotly.com/python/creating-and-updating-figures/ # adicionando", "import plotly.graph_objects as go # adicionando um estilo externo através", "Callback # estruturando a callback com as entradas (input) e", "dão forma app.layout = html.Div([ # inserindo um componente da", "módulo graph_objects da biblioteca plotly import plotly.graph_objects as go #", "existe um erro, e assim, retornamos a mensagem de erro", "# caso você faça print(fig), um dicionário será apresentado uma", "# https://plotly.com/python/creating-and-updating-figures/ # adicionando um traço a figura fig.add_trace( go.Scatter(", "a estrutura de um arquivo CSS external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] #", "de módulos da biblioteca plotly para trabalhar com as informações", "ofical Dash # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # importando as bibliotecas necessárias import", "retornamos a mensagem de erro else: return html.Div(['Erro!']) # servindo", "dentro do layout dcc.Tabs( # identidade/nome do componente id='tabs', #", "você perceberá que ele possui a estrutura de um arquivo", "parâmetro style define estilos css para o componente style={ 'textAlign':'center',", "das condições acima sejam aceitas, significa que existe um erro,", "'font-weight':'bold' # texto em negrito } ), # adicionando uma", "biblioteca plotly para trabalhar com as informações fig = go.Figure()", "ao layout um componente html.Div que irá conter os demais", "tab == 'tab-3': return html.Div([ dcc.Graph(figure = gera_grafico('lines+markers')) ]) #", "CSS external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # criando a aplicação por meio", "do pacote dash from dash.dependencies import Input, Output # importando", "caso você faça print(fig), um dicionário será apresentado uma vez", "# você perceberá que ele possui a estrutura de um", "linha horizontal no layout html.Hr(), # criando abas pai dentro", "atribuindo a variável app app = dash.Dash( __name__, external_stylesheets=external_stylesheets )", "componente html.Div que irá conter os demais componentes que dão", "de um arquivo CSS external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # criando a", "Exemplo') return html.Div([ dcc.Graph(figure = fig_bar) ]) # quando a", "do componente id='tabs', # criando as abas filhas dentro do", "vídeo e estudar pela documentação ofical Dash # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #", "# criando a aplicação por meio da função Dash do", "horizontal no layout html.Hr(), # criando abas pai dentro do", "será apresentado o conteúdo das abas logo após a callback", "da biblioteca dash HTML components como título/cabeçalho do layout html.H2(", "biblioteca dash HTML components como título/cabeçalho do layout html.H2( ['Painel", "linha retornado abaixo pela função gera_gráfico(tipo='lines') if tab == 'tab-1':", "função gera_gráfico(tipo='lines+markers') elif tab == 'tab-3': return html.Div([ dcc.Graph(figure =", "pela documentação ofical Dash # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # importando as bibliotecas", "chamada pela callback def update_tab(tab): # quando a aba com", "saídas (output) @app.callback( # Output(component_id,component_property) Output('tabs-content','children'), [ # Input(component_id,component_property) Input('tabs','value')", "return html.Div([ dcc.Graph(figure = fig_bar) ]) # quando a aba", "id='tabs', # criando as abas filhas dentro do parâmetro children", "__name__, external_stylesheets=external_stylesheets ) # criando uma função para gerar um", "# Esse arquivo possui algumas modificações em relação ao arquivo", "do parâmetro children da função Tabs() children=[ dcc.Tab(label='Gráfico de linha',value='tab-1'),", "= gera_grafico('lines')) ]) # quando a aba com valor igual", "# texto em negrito } ), # adicionando uma linha", "y=[0,1,4,9,16,25,36], ) ) fig_bar.update_layout(title='Gráfico em Barras Exemplo') return html.Div([ dcc.Graph(figure", "dash_html_components as html # importando as funções que auxiliam no", "com as entradas (input) e saídas (output) @app.callback( # Output(component_id,component_property)", "igual a 'tab-1' for selecionada, a propriedade children do componente", "# criando as abas filhas dentro do parâmetro children da", "esse link no seu navegador, # você perceberá que ele", "as figuras podem ser representadas dessa forma, necessitando de módulos", "da biblioteca plotly para trabalhar com as informações fig =", "['Painel de Visualização de Gráficos'], # o parâmetro style define", "tab == 'tab-2': fig_bar = go.Figure() fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6],", "texto em negrito } ), # adicionando uma linha horizontal", "a variável app app = dash.Dash( __name__, external_stylesheets=external_stylesheets ) #", "adicionando uma linha horizontal no layout html.Hr(), # criando abas", "x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], mode=tipo, name='Parábola', ) ) # adicionando um título", "y=[0,1,4,9,16,25,36], mode=tipo, name='Parábola', ) ) # adicionando um título ao", "função Dash do pacote dash e atribuindo a variável app", "# onde será apresentado o conteúdo das abas logo após", "fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], ) ) fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36],", "ao gráfico fig.update_layout(title='Gráfico Exemplo') # variável retornada pela função gera_grafico(tipo)", "abaixo pela função gera_gráfico(tipo='lines+markers') elif tab == 'tab-3': return html.Div([", "com valor igual a 'tab-3' for selecionada, a propriedade children", "auxiliam no funcionamento das callbacks do subpacote dependencies do pacote", "as entradas (input) e saídas (output) @app.callback( # Output(component_id,component_property) Output('tabs-content','children'),", "retornado abaixo elif tab == 'tab-2': fig_bar = go.Figure() fig_bar.add_trace(", "da biblioteca Dash e ao acessar esse link no seu", "dcc.Graph(figure = fig_bar) ]) # quando a aba com valor", "conter os demais componentes que dão forma app.layout = html.Div([", "external_stylesheets=external_stylesheets ) # criando uma função para gerar um gráfico", "um gráfico com a biblioteca plotly.graph_objects def gera_grafico(tipo): # criando", "será chamada pela callback def update_tab(tab): # quando a aba", "== 'tab-2': fig_bar = go.Figure() fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], )", "vídeo do YouTube # Não deixe de assistir o vídeo", "mode=tipo, name='Parábola', ) ) # adicionando um título ao gráfico", "layout html.Hr(), # criando abas pai dentro do layout dcc.Tabs(", "através do link abaixo # esse link é o recomendado", "# estruturando a callback com as entradas (input) e saídas", "app = dash.Dash( __name__, external_stylesheets=external_stylesheets ) # criando uma função", "e assim, retornamos a mensagem de erro else: return html.Div(['Erro!'])", "Dash e ao acessar esse link no seu navegador, #", "que será chamada pela callback def update_tab(tab): # quando a", "# adicionando ao layout um componente html.Div que irá conter", "figura # caso você faça print(fig), um dicionário será apresentado", "variável app app = dash.Dash( __name__, external_stylesheets=external_stylesheets ) # criando", "retornada pela função gera_grafico(tipo) return fig # criando um layout", "go.Figure() fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], ) ) fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6],", "# adicionando um estilo externo através do link abaixo #", "funcionamento das callbacks do subpacote dependencies do pacote dash from", "identidade/nome do componente id='tabs', # criando as abas filhas dentro", "função para gerar um gráfico com a biblioteca plotly.graph_objects def", "estruturando a callback com as entradas (input) e saídas (output)", "'tab-3' for selecionada, a propriedade children do componente 'tabs-content' #", "arquivo CSS external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # criando a aplicação por", "e Pontos',value='tab-3') ] ), # onde será apresentado o conteúdo", "fig_bar = go.Figure() fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], ) ) fig_bar.add_trace(", "selecionada, a propriedade children do componente 'tabs-content' # receberá o", "pai dentro do layout dcc.Tabs( # identidade/nome do componente id='tabs',", "um componente html.Div que irá conter os demais componentes que", "'tabs-content' # receberá o gráfico de linha retornado abaixo pela", "a aba com valor igual a 'tab-1' for selecionada, a", "dentro do parâmetro children da função Tabs() children=[ dcc.Tab(label='Gráfico de", "# importando as funções que auxiliam no funcionamento das callbacks", "o parâmetro style define estilos css para o componente style={", "a aba com valor igual a 'tab-3' for selecionada, a", "]) # caso nenhuma das condições acima sejam aceitas, significa", "e ao acessar esse link no seu navegador, # você", "função que será chamada pela callback def update_tab(tab): # quando", "documentação ofical Dash # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # importando as bibliotecas necessárias", "dependencies do pacote dash from dash.dependencies import Input, Output #", "abaixo # esse link é o recomendado pela documentação da", "no vídeo do YouTube # Não deixe de assistir o", "# adicionando um traço a figura fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6],", "ativada html.Div(id='tabs-content'), html.Hr(), ]) # Callback # estruturando a callback", "demais componentes que dão forma app.layout = html.Div([ # inserindo", "# criando abas pai dentro do layout dcc.Tabs( # identidade/nome", "go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], mode=tipo, name='Parábola', ) ) # adicionando um", "pela função gera_gráfico(tipo='lines+markers') elif tab == 'tab-3': return html.Div([ dcc.Graph(figure", "de erro else: return html.Div(['Erro!']) # servindo a aplicação em", "# Output(component_id,component_property) Output('tabs-content','children'), [ # Input(component_id,component_property) Input('tabs','value') ] ) #", "dash import dash_core_components as dcc import dash_html_components as html #", "deixe de assistir o vídeo e estudar pela documentação ofical", "após a callback ser ativada html.Div(id='tabs-content'), html.Hr(), ]) # Callback", "Output(component_id,component_property) Output('tabs-content','children'), [ # Input(component_id,component_property) Input('tabs','value') ] ) # função", "plotly.graph_objects as go # adicionando um estilo externo através do", "que ele possui a estrutura de um arquivo CSS external_stylesheets", "o conteúdo das abas logo após a callback ser ativada", "a 'tab-1' for selecionada, a propriedade children do componente 'tabs-content'", "Não deixe de assistir o vídeo e estudar pela documentação", "informações fig = go.Figure() # https://plotly.com/python/creating-and-updating-figures/ # adicionando um traço", "inserindo um componente da biblioteca dash HTML components como título/cabeçalho", "app app = dash.Dash( __name__, external_stylesheets=external_stylesheets ) # criando uma", "vez que as figuras podem ser representadas dessa forma, necessitando", "]) # quando a aba com valor igual a 'tab-3'", "o componente style={ 'textAlign':'center', # texto alinhado 'font-weight':'bold' # texto", "de linha retornado abaixo pela função gera_gráfico(tipo='lines+markers') elif tab ==", "acessar esse link no seu navegador, # você perceberá que", "] ) # função que será chamada pela callback def", ") # função que será chamada pela callback def update_tab(tab):", "aba com valor igual a 'tab-1' for selecionada, a propriedade", "gráfico com a biblioteca plotly.graph_objects def gera_grafico(tipo): # criando uma", "name='Parábola', ) ) # adicionando um título ao gráfico fig.update_layout(title='Gráfico", "go # adicionando um estilo externo através do link abaixo", "subpacote dependencies do pacote dash from dash.dependencies import Input, Output", "fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], ) ) fig_bar.update_layout(title='Gráfico em Barras Exemplo')", "plotly para trabalhar com as informações fig = go.Figure() #", "gera_grafico(tipo) return fig # criando um layout para a variável", "do layout html.H2( ['Painel de Visualização de Gráficos'], # o", "return html.Div(['Erro!']) # servindo a aplicação em dash como versão", "aplicação por meio da função Dash do pacote dash e", "uma função para gerar um gráfico com a biblioteca plotly.graph_objects", "no layout html.Hr(), # criando abas pai dentro do layout", "x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], mode=tipo, name='Reta', ) ) fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36],", ") # criando uma função para gerar um gráfico com", "y=[0,1,2,3,4,5,6], ) ) fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], ) ) fig_bar.update_layout(title='Gráfico", "Barra',value='tab-2'), dcc.Tab(label='Gráfico de Linha e Pontos',value='tab-3') ] ), # onde", "link abaixo # esse link é o recomendado pela documentação", "fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], mode=tipo, name='Parábola', ) ) # adicionando", "link no seu navegador, # você perceberá que ele possui", "adicionando ao layout um componente html.Div que irá conter os", "# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Esse arquivo possui algumas modificações em relação", "app.layout = html.Div([ # inserindo um componente da biblioteca dash", "do subpacote dependencies do pacote dash from dash.dependencies import Input,", "children do componente 'tabs-content' # receberá o gráfico de linha", "pela documentação da biblioteca Dash e ao acessar esse link", "# adicionando uma linha horizontal no layout html.Hr(), # criando", "de Barra',value='tab-2'), dcc.Tab(label='Gráfico de Linha e Pontos',value='tab-3') ] ), #", "as abas filhas dentro do parâmetro children da função Tabs()", "a mensagem de erro else: return html.Div(['Erro!']) # servindo a", "gráfico de linha retornado abaixo pela função gera_gráfico(tipo='lines+markers') elif tab", "'tab-2': fig_bar = go.Figure() fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], ) )", "do link abaixo # esse link é o recomendado pela", "[ # Input(component_id,component_property) Input('tabs','value') ] ) # função que será", "x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], ) ) fig_bar.add_trace( go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], ) )", "valor igual a 'tab-3' for selecionada, a propriedade children do", "documentação da biblioteca Dash e ao acessar esse link no", "das abas logo após a callback ser ativada html.Div(id='tabs-content'), html.Hr(),", "valor igual a 'tab-2' for selecionada, a propriedade children do", "fig # criando um layout para a variável app #", "name='Reta', ) ) fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], mode=tipo, name='Parábola', )", "variável retornada pela função gera_grafico(tipo) return fig # criando um", "html.Div([ # inserindo um componente da biblioteca dash HTML components", "biblioteca Dash e ao acessar esse link no seu navegador,", "traço a figura fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], mode=tipo, name='Reta', )", "# Callback # estruturando a callback com as entradas (input)", "que as figuras podem ser representadas dessa forma, necessitando de", "apresentado o conteúdo das abas logo após a callback ser", "uma figura # caso você faça print(fig), um dicionário será", "} ), # adicionando uma linha horizontal no layout html.Hr(),", "e estudar pela documentação ofical Dash # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # importando", "com valor igual a 'tab-2' for selecionada, a propriedade children", "if tab == 'tab-1': return html.Div([ dcc.Graph(figure = gera_grafico('lines')) ])", "receberá o gráfico de barras construído e retornado abaixo elif", "elif tab == 'tab-3': return html.Div([ dcc.Graph(figure = gera_grafico('lines+markers')) ])", "= gera_grafico('lines+markers')) ]) # caso nenhuma das condições acima sejam", "), # onde será apresentado o conteúdo das abas logo", "layout um componente html.Div que irá conter os demais componentes", "o módulo graph_objects da biblioteca plotly import plotly.graph_objects as go", "para a variável app # adicionando ao layout um componente", "children da função Tabs() children=[ dcc.Tab(label='Gráfico de linha',value='tab-1'), dcc.Tab(label='Gráfico de", "aba com valor igual a 'tab-2' for selecionada, a propriedade", "= ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # criando a aplicação por meio da função", "# criando uma função para gerar um gráfico com a", "fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], mode=tipo, name='Reta', ) ) fig.add_trace( go.Scatter(", "alinhado 'font-weight':'bold' # texto em negrito } ), # adicionando", "um arquivo CSS external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # criando a aplicação", "gráfico de linha retornado abaixo pela função gera_gráfico(tipo='lines') if tab", "um estilo externo através do link abaixo # esse link", "criando abas pai dentro do layout dcc.Tabs( # identidade/nome do", "irá conter os demais componentes que dão forma app.layout =", "seu navegador, # você perceberá que ele possui a estrutura", "servindo a aplicação em dash como versão para teste if", "quando a aba com valor igual a 'tab-3' for selecionada,", "o gráfico de barras construído e retornado abaixo elif tab", "go.Bar( x=[0,1,2,3,4,5,6], y=[0,1,4,9,16,25,36], ) ) fig_bar.update_layout(title='Gráfico em Barras Exemplo') return", "dcc.Tabs( # identidade/nome do componente id='tabs', # criando as abas", "gera_gráfico(tipo='lines+markers') elif tab == 'tab-3': return html.Div([ dcc.Graph(figure = gera_grafico('lines+markers'))", "acima sejam aceitas, significa que existe um erro, e assim,", "dcc import dash_html_components as html # importando as funções que", "link é o recomendado pela documentação da biblioteca Dash e", "Input, Output # importando o módulo graph_objects da biblioteca plotly", "significa que existe um erro, e assim, retornamos a mensagem", "gera_grafico('lines+markers')) ]) # caso nenhuma das condições acima sejam aceitas,", "adicionando um traço a figura fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], mode=tipo,", "callback com as entradas (input) e saídas (output) @app.callback( #", "import Input, Output # importando o módulo graph_objects da biblioteca", "recomendado pela documentação da biblioteca Dash e ao acessar esse", "def update_tab(tab): # quando a aba com valor igual a", "um layout para a variável app # adicionando ao layout", "que existe um erro, e assim, retornamos a mensagem de", "] ), # onde será apresentado o conteúdo das abas", "fig.update_layout(title='Gráfico Exemplo') # variável retornada pela função gera_grafico(tipo) return fig", "as informações fig = go.Figure() # https://plotly.com/python/creating-and-updating-figures/ # adicionando um", "um erro, e assim, retornamos a mensagem de erro else:", "html.Hr(), ]) # Callback # estruturando a callback com as", "graph_objects da biblioteca plotly import plotly.graph_objects as go # adicionando", "fig = go.Figure() # https://plotly.com/python/creating-and-updating-figures/ # adicionando um traço a", "quando a aba com valor igual a 'tab-2' for selecionada,", "de barras construído e retornado abaixo elif tab == 'tab-2':", "função Tabs() children=[ dcc.Tab(label='Gráfico de linha',value='tab-1'), dcc.Tab(label='Gráfico de Barra',value='tab-2'), dcc.Tab(label='Gráfico", "componente 'tabs-content' # receberá o gráfico de linha retornado abaixo", "gera_gráfico(tipo='lines') if tab == 'tab-1': return html.Div([ dcc.Graph(figure = gera_grafico('lines'))", "as go # adicionando um estilo externo através do link", "Pontos',value='tab-3') ] ), # onde será apresentado o conteúdo das", "html.Div(['Erro!']) # servindo a aplicação em dash como versão para", "https://plotly.com/python/creating-and-updating-figures/ # adicionando um traço a figura fig.add_trace( go.Scatter( x=[0,1,2,3,4,5,6]," ]
[ "!= ')': if self.__tokens[pos + 1].get_value() in (')', ','): i", "1 if self.__tokens[i].get_value() == ';': return i + 1 brace_count", "naming[i:] j = len(naming) - 1 while naming[j] == '_':", "+= 1 return pos def __fix_field_comment(self, pos): comment_token = self.__find_doc_comment_before(pos)", "0 if len(params) < len(params_list): append_string += \"\\n\" + \"\\n\".join(", "i += 1 return tokens def __find_to_fix(self): i = 0", "pos += 1 return True def __fix(self): for token in", "== '@': start = comment_string.find(' ', i) macro = comment_string[i:start]", "> 0: value = comment_string[start + 1:end] new_value = self.__fix_link(value)", "return self.__tokens[i].get_type() == TokenType.COMMENT def __find_class_name(self, i=0): while self.__tokens[i].get_value() not", "= '' comment_string = comment_token.get_value() while i < len(comment_string): if", "self.__tokens[i].get_value() in ('class', 'interface'): i = self.__fix_class_comments(i) i += 1", "'(': pos += 1 pos -= 1 while self.__tokens[pos].get_type() ==", "' * count def __skip_ws_tokens(self, pos): while self.__tokens[pos].get_type() == TokenType.WHITESPACE:", "';': if self.__tokens[i + 1].get_value() in (';', '=', ','): pos", "if len(params) > 0: all_params.append(\"\\n\".join([f\"{indent} * @param {param}\" for param", "'throws': is_throws = True elif is_throws and self.__tokens[pos].get_type() == TokenType.IDENTIFIER:", "1 pos += 1 count = 1 pos += 1", "TokenType.WHITESPACE: naming_pos -= 1 if self.__tokens[naming_pos].get_type() == TokenType.IDENTIFIER: type_pos =", "== ';': return pos + 1 pos += 1 count", "1 # Fix start comment def __add_start_comment(self): if not self.__is_start_comment_exists():", "Formatter.to_snake_upper_case(parameter) else: for parameter in parameters: if not Formatter.is_camel_lower_case(parameter): self.__to_fix[parameter]", "= self.__get_return_type(pos) if len(return_type) > 0: all_params.append(f\"{indent} * @return {self.__get_return_type(pos)}\")", "elif self.__tokens[i].get_value() == '}': brace_count -= 1 elif self.__tokens[i].get_value() in", "pos < len(self.__tokens) and self.__tokens[pos].get_value() != value: pos += 1", "'<': if self.__tokens[pos].get_value() == '(': return parameters pos += 1", "pos = self.__find_token_before(pos, '\\n') while self.__tokens[pos].get_value() not in ('=', ';',", "1] == '_'): link = link.replace(name, self.__to_fix[name]) return link def", "elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD): if self.__is_parameter(pos): parameters, i =", "1 if comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) def __fix_link(self,", "1 continue end = comment_string.find('\\n', i) link = comment_string[start:end] elif", "component.isupper() else component[0].upper() + component[1:] for component in naming.split('_')] return", "while self.__tokens[pos].get_value() != '>': if self.__tokens[pos - 1].get_value() in ('<',", "params])) throws = self.__get_throws(pos) if len(throws) > 0: all_params.append(\"\\n\".join([f\"{indent} *", "0 while naming[i] == '_': i += 1 naming =", "self.__tokens[pos].get_value() == '}': count -= 1 pos += 1 return", "pos += 1 return 'package-private' def __fix_method_comment(self, pos): comment_token =", "== '=': return True elif self.__tokens[pos].get_value() in ('class', 'interface', '(',", "TokenType.WHITESPACE: pos -= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -=", "token.get_value() in ('class', 'interface') and self.__tokens[i - 1].get_value() != '.':", "+ component[1:].lower() if component.isupper() else component[0].upper() + component[1:] for component", "= comment_string.rfind('@throws') if i != -1: i = comment_string.find('\\n', i)", "')'): return False pos += 1 return True def __fix(self):", "None comment_string = comment_token.get_value() while i < len(comment_string): if comment_string[i]", "+ 1].get_value() in (';', ','): while pos > 0 and", "__is_parameter(self, pos): while self.__tokens[pos].get_value() != ';' and pos < len(self.__tokens):", "*/' update_token_value(self.__file, comment_token, comment_string) insert_pos = self.__find_token_before(pos, '\\n') self.__tokens.insert(insert_pos, Token('\\n',", "= re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', naming) return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', naming).lower() @staticmethod def", "datetime from javaccflab.lexer import parse from javaccflab.java_token import TokenType, Token,", "comment_string.find(' ', i) macro = comment_string[i:start] end = min(comment_string.find(' ',", "in (')', ','): i = pos while self.__tokens[i].get_type() == TokenType.WHITESPACE:", "while self.__tokens[pos].get_type() == TokenType.WHITESPACE: return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value()) return_type.reverse()", "False while self.__tokens[pos].get_value() not in ('{', ';'): if self.__tokens[pos].get_value() ==", "+= 1 return pos def __fix_class_body(self, pos, class_name): while self.__tokens[pos].get_value()", "self.__tokens[i], params[self.__tokens[i].get_value()]) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[ i].get_value() in", "self.__tokens[i].get_value() not in ('class', 'interface') and self.__tokens[i - 1].get_value() !=", "i = comment_string.rfind('@return') while comment_string[i] != '\\n': i -= 1", "0: all_params.append(f\"{indent} * @return {self.__get_return_type(pos)}\") comment_token = Token(None, TokenType.COMMENT) comment_string", "if self.__tokens[i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1", "self.__tokens[i - 1].get_value() != '.': i = self.__skip_ws_tokens(i + 1)", "+= 1 end = i return params, end def __is_final(self,", "('class', 'interface'): if self.__is_parameter(pos): pos = self.__fix_field_comment(pos) else: pos =", "> 0 and self.__tokens[pos].get_value() != value: pos -= 1 return", "if comment_string.find('\\n', i) != -1 else comment_string.find('*', i) - 1", "+= 1 while self.__tokens[pos].get_value() != ')': if self.__tokens[pos + 1].get_value()", "i += 1 end = i return params, end def", "self.__tokens[i] if token.get_value() == 'package': i = self.__fix_package(i) elif token.get_value()", "if self.__tokens[pos].get_value() == ' ': count += 1 pos +=", "self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if not Formatter.is_camel_lower_case(self.__tokens[pos].get_value()): fixed_value", "1 elif self.__tokens[pos].get_value() == '}': count -= 1 elif self.__tokens[pos].get_value()", "i = 0 params = [] throws = [] return_type", "if end >= 0 else max(comment_string.find(' ', start + 1),", "+= 1 return pos def __find_doc_comment_before(self, pos): while self.__tokens[pos].get_value() !=", "self.__tokens[i].get_value() != ';': if self.__tokens[i + 1].get_value() in (';', '=',", "+ component[1:] for component in naming.split('_')] return components[0][0].lower() + components[0][1:]", "comment_string[i] == '@': start = comment_string.find(' ', i) if comment_string[i:start]", "is_lower_case(naming): return naming.find('_') == -1 and naming.islower() @staticmethod def to_lower_case(naming):", "self.__tokens[type_pos].get_value() not in ('class', 'identifier')) or self.__tokens[ type_pos].get_value() == ',':", "'identifier')) or self.__tokens[ type_pos].get_value() == ',': if not Formatter.is_camel_lower_case(self.__tokens[naming_pos].get_value()): fixed_value", "= Token(None, TokenType.COMMENT) comment_string = f'{indent}/**\\n' + \\ '\\n'.join(all_params) +", "method_parameters[self.__tokens[i].get_value()]) i += 1 if self.__tokens[i].get_value() == ';': return i", "+= 1 while brace_count != 0: if self.__tokens[i].get_value() == '{':", "pos - 1].isdigit() or link[pos - 1] == '_'): link", "if token.get_value() in self.__to_fix and not token.is_fixed(): update_token_value(self.__file, token, self.__to_fix[token.get_value()])", "is None: comment_token = Token(None, TokenType.COMMENT) comment_string = f'/**\\n' \\", "+ f\"\\n{indent} * @return {return_type_value}\" else: i = comment_string.rfind('@return') while", "'>': while self.__tokens[pos].get_value() != '<': return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value())", "and not (link[pos - 1].isalpha() or link[ pos - 1].isdigit()", "def __is_parameter(self, pos): while self.__tokens[pos].get_value() != ';' and pos <", "len(return_type) > 0: all_params.append(f\"{indent} * @return {self.__get_return_type(pos)}\") comment_token = Token(None,", "methods and fields def __fix_class_body_comments(self, pos): while self.__tokens[pos].get_value() != '{':", "self.__get_parameter_list(pos) params_list.extend(self.__get_type_parameter_list(pos)) throws_list = self.__get_throws(pos) return_type_value = self.__get_return_type(pos) params, throws,", "in self.__files: tokens.append(parse(open(file, 'r').read())) i = 0 while i <", "+= \"\\n\" + \"\\n\".join( [f\"{indent} * @throws {param}\" for param", "self.__tokens[pos].get_value() != '(': pos += 1 while self.__tokens[pos].get_value() != ')':", "= None self.__tokens = [] self.__to_fix = dict() def process(self):", "i += 1 return parameters def __fix_method_body(self, i, method_parameters): params", "comment_string = comment_string.replace(value, new_value) update_token_value(self.__file, comment_token, comment_string) value = new_value", "pos += 1 pos -= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE:", "__get_field_names(self, i): params = [] while self.__tokens[i].get_value() != ';': if", "token in self.__tokens: if token.get_value() in self.__to_fix and not token.is_fixed():", "TokenType.WHITESPACE: i -= 1 if self.__tokens[i].get_type() != TokenType.KEYWORD or self.__tokens[i].get_value()", "return parameters pos += 1 i = pos - 1", "return pos def __fix_comment_links(self, comment_token): i = 0 link =", "i def __get_field_names(self, i): params = [] while self.__tokens[i].get_value() !=", "j = len(naming) - 1 while naming[j] == '_': i", "= comment_string.rfind('@return') while comment_string[i] != '\\n': i -= 1 comment_string", "pos): throws = [] is_throws = False while self.__tokens[pos].get_value() not", "value): while pos > 0 and self.__tokens[pos].get_value() != value: pos", "def to_lower_case(naming): return ''.join([component.lower() for component in naming.split('_')]) @staticmethod def", "- 1] == '_'): link = link.replace(name, self.__to_fix[name]) return link", "+ lower[1:] @staticmethod def is_snake_lower_case(naming): return naming.islower() @staticmethod def to_snake_lower_case(naming):", "+= 1 continue elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and self.__tokens[", "< len(self.__tokens): token = self.__tokens[i] if token.get_value() == 'package': i", "if not self.__is_start_comment_exists(): comment_token = Token(None, TokenType.COMMENT) comment_string = f'/*\\n'", "__init__(self, files): self.__files = files self.__file = None self.__tokens =", "= self.__files[i] self.__find_to_fix() tokens[i] = self.__tokens i += 1 i", "'interface'): i = self.__fix_class_comments(i) i += 1 i += 1", "if value != new_value: comment_string = comment_string.replace(value, new_value) update_token_value(self.__file, comment_token,", "= self.__tokens i += 1 return tokens def __find_to_fix(self): i", "True pos -= 1 if not is_value: params.append(field_name) i +=", "TokenType.IDENTIFIER and self.__tokens[ i].get_value() in params.keys(): update_token_value(self.__file, self.__tokens[i], params[self.__tokens[i].get_value()]) elif", "'{': brace_count += 1 elif self.__tokens[i].get_value() == '}': brace_count -=", "def __fix_method_comment(self, pos): comment_token = self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) all_params", "in ('class', 'interface'): i = self.__fix_class_comments(i) i += 1 i", "comment_token = self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) all_params = [] if", "return naming.isupper() @staticmethod def to_snake_upper_case(naming): return Formatter.to_snake_lower_case(naming).upper() @staticmethod def remove_underscores_around(naming):", "-= 1 while self.__tokens[pos].get_type() != TokenType.WHITESPACE: pos -= 1 while", "append_string = '' i = comment_string.find('\\n', i) if len(return_type) ==", "!= '(': pos += 1 while self.__tokens[pos].get_value() != ')': if", "self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 if self.__tokens[i].get_value() != class_name", "[] for value in after: if value not in before:", "return self.__tokens[i].get_value() # Fix class comment def __fix_class_comments(self, pos): comment_token", "if self.__is_final(pos) else \"variable\"}{\"s\" if len(field_names) > 0 else \"\"}\\n'", "pos -= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1", "def to_snake_lower_case(naming): naming = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', naming) return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2',", "i) if len(return_type) == '': append_string += \"\\n\" + f\"\\n{indent}", "\\ f' *\\n' \\ f' * {datetime.date.today().strftime(\"%B %d, %Y\")}\\n' \\", "self.__get_parameter_list(pos) params.extend(self.__get_type_parameter_list(pos)) if len(params) > 0: all_params.append(\"\\n\".join([f\"{indent} * @param {param}\"", "'public', 'protected'): return self.__tokens[pos].get_value() pos += 1 return 'package-private' def", "visibility = self.__find_visibility(pos) comment_token = Token(None, TokenType.COMMENT) comment_string = comment_string", "while i < len(self.__tokens): token = self.__tokens[i] if token.get_value() ==", "return_type = [] while self.__tokens[pos].get_value() != '(': pos += 1", "'<': return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value()) pos -= 1 while", "1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value())", "+= 1 pos -= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos", "missing_params.append(value) return missing_params def __get_parameter_list(self, pos): parameters = [] while", "throws.append(value) elif macro == '@return': return_type = value i +=", "> 0 and self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if", "self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD): if self.__is_parameter(pos): parameters, i = self.__get_field_names(pos)", "params = [] throws = [] return_type = '' comment_string", "def __init__(self, files): self.__files = files self.__file = None self.__tokens", "\\ f' * Implementation of {self.__find_class_name(pos)}\\n' \\ f' */' update_token_value(self.__file,", "self.__file = self.__files[i] self.__find_to_fix() tokens[i] = self.__tokens i += 1", "count def __skip_ws_tokens(self, pos): while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos +=", "+ 1, comment_token) else: self.__fix_comment_links(comment_token) return self.__fix_class_body_comments(pos) # Fix comments", "-= 1 while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 if", "+ 1:end] new_value = self.__fix_link(value) if value != new_value: comment_string", "comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) def __fix_link(self, link): for", "__is_start_comment_exists(self): i = self.__skip_ws_tokens(0) return self.__tokens[i].get_type() == TokenType.COMMENT def __find_class_name(self,", "';'): if self.__tokens[pos].get_value() == 'throws': is_throws = True elif is_throws", "link = None i += 1 if comment_string != comment_token.get_value():", "= [] return_type = '' comment_string = comment_token.get_value() while i", "and \\ self.__tokens[type_pos].get_value() not in ('class', 'identifier')) or self.__tokens[ type_pos].get_value()", "dict() while self.__tokens[i].get_value() != '(': i += 1 while self.__tokens[i].get_value()", "pos -= 1 if not is_value: params.append(field_name) i += 1", "link = link.replace(name, self.__to_fix[name]) return link def __get_indent(self, pos): pos", "def is_lower_case(naming): return naming.find('_') == -1 and naming.islower() @staticmethod def", "in after: if value not in before: missing_params.append(value) return missing_params", "in ('{', ';'): if self.__tokens[pos].get_value() == 'throws': is_throws = True", "if not Formatter.is_snake_upper_case(parameter): self.__to_fix[parameter] = Formatter.to_snake_upper_case(parameter) else: for parameter in", "0 link = None comment_string = comment_token.get_value() while i <", "= pos - 1 while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -=", "def __find_to_fix(self): i = 0 while i < len(self.__tokens): token", "1 while self.__tokens[type_pos].get_type() == TokenType.WHITESPACE: type_pos -= 1 if (self.__tokens[type_pos].get_type()", "Formatter: def __init__(self, files): self.__files = files self.__file = None", "{self.__find_class_name()}\\n' \\ f' *\\n' \\ f' * {datetime.date.today().strftime(\"%B %d, %Y\")}\\n'", "== ' ': count += 1 pos += 1 return", "link = comment_string[start:end] elif comment_string[i] == '{': start = comment_string.find('", "== '{': count += 1 elif self.__tokens[pos].get_value() == '}': count", "Fix class comment def __fix_class_comments(self, pos): comment_token = self.__find_doc_comment_before(pos) if", "@param {param}\" for param in Formatter.get_missing(params, params_list)]) i = comment_string.rfind('@param')", "macro == '@throws': throws.append(value) elif macro == '@return': return_type =", "self.__tokens[pos].get_type() == TokenType.IDENTIFIER and not Formatter.is_lower_case( self.__tokens[pos].get_value()): self.__to_fix[self.__tokens[pos].get_value()] = Formatter.to_lower_case(", "throws_list = self.__get_throws(pos) return_type_value = self.__get_return_type(pos) params, throws, return_type =", "== TokenType.COMMENT and self.__tokens[pos].get_value().startswith('/**'): return self.__tokens[pos] return None def __find_token_before(self,", "return ''.join(return_type) def __fix_comment_params(self, comment_token): i = 0 params =", "Formatter.is_camel_lower_case(parameter): self.__to_fix[parameter] = Formatter.to_camel_lower_case(parameter) pos = i else: self.__fix_method_name(pos, class_name)", "1 continue elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD): if self.__is_parameter(pos): parameters,", "1) if self.__tokens[i].get_value() == '{': pos = i + 1", "pos = link.find(name) if pos != -1 and not (link[pos", "1 return pos def __find_doc_comment_before(self, pos): while self.__tokens[pos].get_value() != '\\n':", "pos @staticmethod def is_lower_case(naming): return naming.find('_') == -1 and naming.islower()", "+= 1 return params, throws, return_type def __skip_method(self, pos): while", "= [] while self.__tokens[pos].get_value() != '(': pos += 1 while", "1 return params, throws, return_type def __skip_method(self, pos): while self.__tokens[pos].get_value()", "= tokens[i] self.__file = self.__files[i] self.__find_to_fix() tokens[i] = self.__tokens i", "self.__tokens[i].get_value() != '(': i += 1 while self.__tokens[i].get_value() != ')':", "= self.__find_doc_comment_before(pos) if comment_token is None: comment_token = Token(None, TokenType.COMMENT)", "len(params) < len(params_list): append_string += \"\\n\" + \"\\n\".join( [f\"{indent} *", "Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) def __is_start_comment_exists(self): i = self.__skip_ws_tokens(0)", "update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1 if self.__tokens[i].get_value() == ';':", "comment_string[i] == '{': start = comment_string.find(' ', i) end =", "1 if not is_value: params.append(field_name) i += 1 end =", "-= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: return_type.append(self.__tokens[pos].get_value()) pos -= 1", "pos): comment_token = self.__find_doc_comment_before(pos) if comment_token is None: comment_token =", "else: self.__fix_comment_links(comment_token) return self.__fix_class_body_comments(pos) # Fix comments for methods and", "len(tokens): self.__tokens = tokens[i] self.__file = self.__files[i] self.__find_to_fix() tokens[i] =", "def __get_return_type(self, pos): return_type = [] while self.__tokens[pos].get_value() != '(':", "== '(': return parameters pos += 1 i = pos", "pos + 1].get_value() != '.' and self.__tokens[pos].get_value() not in ('class',", "pos = self.__skip_ws_tokens(pos) while self.__tokens[pos].get_value() != ';': if self.__tokens[pos].get_type() ==", "1 field_name = self.__tokens[pos].get_value() is_value = False if self.__tokens[i +", "start + 1)) if end > 0: value = comment_string[start", "@staticmethod def to_lower_case(naming): return ''.join([component.lower() for component in naming.split('_')]) @staticmethod", "name in self.__to_fix.keys(): pos = link.find(name) if pos != -1", "params.append(field_name) i += 1 end = i return params, end", "pos > 0 and self.__tokens[pos].get_value() != value: pos -= 1", "pos): while self.__tokens[pos].get_value() != '{': pos += 1 count =", "- 1].get_value() != '.': i += 1 i = self.__skip_ws_tokens(i", "f'/**\\n' \\ f' * Implementation of {self.__find_class_name(pos)}\\n' \\ f' */'", "f'{indent}/**\\n' \\ f'{indent} * The {visibility} {field_names} {\"constant\" if self.__is_final(pos)", "TokenType.KEYWORD): if self.__is_parameter(pos): parameters, i = self.__get_field_names(pos) if self.__is_final(pos): for", "for component in naming.split('_')] return components[0][0].lower() + components[0][1:] + ''.join(components[1:])", "self.__tokens[pos].get_type() == TokenType.IDENTIFIER: throws.append(self.__tokens[pos].get_value()) pos += 1 return throws def", "in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1 if self.__tokens[i].get_value()", "1), comment_string.find('\\n', start + 1)) end = end if end", "+ 1) if not Formatter.is_camel_upper_case(self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_camel_upper_case( self.__tokens[i].get_value()) i", "__add_start_comment(self): if not self.__is_start_comment_exists(): comment_token = Token(None, TokenType.COMMENT) comment_string =", "naming.islower() @staticmethod def to_lower_case(naming): return ''.join([component.lower() for component in naming.split('_')])", "comment_string = f'/**\\n' \\ f' * Implementation of {self.__find_class_name(pos)}\\n' \\", "!= -1 and not (link[pos - 1].isalpha() or link[ pos", "__get_parameter_list(self, pos): parameters = [] while self.__tokens[pos].get_value() != '(': pos", "if self.__tokens[pos].get_value() == '(': return parameters pos += 1 i", "+= 1 elif self.__tokens[i].get_value() == '}': brace_count -= 1 elif", "f' */' update_token_value(self.__file, comment_token, comment_string) insert_pos = self.__find_token_before(pos, '\\n') self.__tokens.insert(insert_pos,", "method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1 return i def", "= self.__get_parameter_list(pos) params_list.extend(self.__get_type_parameter_list(pos)) throws_list = self.__get_throws(pos) return_type_value = self.__get_return_type(pos) params,", "i else: self.__fix_method_name(pos, class_name) parameters = self.__get_method_parameters(pos) pos = self.__fix_method_body(pos,", "after): missing_params = [] for value in after: if value", "'.join(self.__get_field_names(pos)[0]) visibility = self.__find_visibility(pos) comment_token = Token(None, TokenType.COMMENT) comment_string =", "== '@param': params.append(value) elif macro == '@throws': throws.append(value) elif macro", "1 while self.__tokens[naming_pos].get_type() == TokenType.WHITESPACE: naming_pos -= 1 if self.__tokens[naming_pos].get_type()", "self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) def __is_start_comment_exists(self): i =", "end = comment_string.find('}', i) link = comment_string[start:end] if link is", "@staticmethod def is_snake_lower_case(naming): return naming.islower() @staticmethod def to_snake_lower_case(naming): naming =", "('class', 'interface') and self.__tokens[i - 1].get_value() != '.': i =", "= fixed_value update_token_value(self.__file, self.__tokens[naming_pos], fixed_value) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and", "if link is not None: new_link = self.__fix_link(link) comment_string =", "self.__fix_field_comment(pos) else: pos = self.__fix_method_comment(pos) pos += 1 return pos", "pos def __find_doc_comment_before(self, pos): while self.__tokens[pos].get_value() != '\\n': pos -=", "# Fix start comment def __add_start_comment(self): if not self.__is_start_comment_exists(): comment_token", "self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and self.__tokens[ pos + 1].get_value() !=", "'@': start = comment_string.find(' ', i) if comment_string[i:start] != '@see':", "def remove_underscores_around(naming): i = 0 while naming[i] == '_': i", "if self.__tokens[pos].get_value() in ('private', 'public', 'protected'): return self.__tokens[pos].get_value() pos +=", "new_value = self.__fix_link(value) if value != new_value: comment_string = comment_string.replace(value,", "@staticmethod def is_snake_upper_case(naming): return naming.isupper() @staticmethod def to_snake_upper_case(naming): return Formatter.to_snake_lower_case(naming).upper()", "1 return throws def __get_return_type(self, pos): return_type = [] while", "1 if self.__tokens[pos].get_value() == '>': while self.__tokens[pos].get_value() != '<': return_type.append(self.__tokens[pos].get_value())", "i = self.__fix_class_body(i, self.__tokens[i].get_value()) i += 1 def __fix_package(self, pos):", "not in ('class', 'interface') and self.__tokens[i - 1].get_value() != '.':", "> 0 else \"\"}\\n' \\ f'{indent} */' update_token_value(self.__file, comment_token, comment_string)", "comment_string = comment_string.replace(link, new_link) link = None i += 1", "= dict() while self.__tokens[i].get_value() != '(': i += 1 while", "pos > 0 and self.__tokens[pos].get_value() not in (';', '}'): if", "1 if self.__tokens[i].get_value() != class_name and not Formatter.is_snake_lower_case( self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()]", "= tokens[i] self.__file = self.__files[i] self.__fix() self.__fix_comments() tokens[i] = self.__tokens", "if comment_string[i] == '@': start = comment_string.find(' ', i) macro", "False def __is_parameter(self, pos): while self.__tokens[pos].get_value() != ';' and pos", "and naming[0].isupper() @staticmethod def to_camel_upper_case(naming): lower = Formatter.to_camel_lower_case(naming) return lower[0].upper()", "self.__tokens[pos].get_value() != ')': if self.__tokens[pos + 1].get_value() in (')', ','):", "return params, throws, return_type def __skip_method(self, pos): while self.__tokens[pos].get_value() !=", "''.join([component.lower() for component in naming.split('_')]) @staticmethod def is_camel_lower_case(naming): return naming.find('_')", "comment_token, comment_string) def __fix_link(self, link): for name in self.__to_fix.keys(): pos", "1, comment_token) else: self.__fix_comment_links(comment_token) return self.__find_token_after(pos, ';') def __find_visibility(self, pos):", "'package-private' def __fix_method_comment(self, pos): comment_token = self.__find_doc_comment_before(pos) indent = self.__get_indent(pos)", "components[0][0].lower() + components[0][1:] + ''.join(components[1:]) @staticmethod def is_camel_upper_case(naming): return naming.find('_')", "self.__add_start_comment() i = 0 while i < len(self.__tokens): if self.__tokens[i].get_value()", "if self.__tokens[i].get_value() != class_name and not Formatter.is_snake_lower_case( self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] =", "< len(params_list): append_string += \"\\n\" + \"\\n\".join( [f\"{indent} * @param", "if self.__tokens[naming_pos].get_type() == TokenType.IDENTIFIER: type_pos = naming_pos - 1 while", "in naming.split('_')] return components[0][0].lower() + components[0][1:] + ''.join(components[1:]) @staticmethod def", "len(throws) < len(throws_list): append_string += \"\\n\" + \"\\n\".join( [f\"{indent} *", "naming_pos -= 1 if self.__tokens[naming_pos].get_type() == TokenType.IDENTIFIER: type_pos = naming_pos", "def __get_method_parameters(self, i): parameters = dict() while self.__tokens[i].get_value() != '(':", "indent = self.__get_indent(pos) all_params = [] if comment_token is None:", "self.__fix_class_body_comments(pos) # Fix comments for methods and fields def __fix_class_body_comments(self,", "= Formatter.to_snake_upper_case(parameter) else: for parameter in parameters: if not Formatter.is_camel_lower_case(parameter):", "TokenType.WHITESPACE: type_pos -= 1 if (self.__tokens[type_pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and", "{visibility} {field_names} {\"constant\" if self.__is_final(pos) else \"variable\"}{\"s\" if len(field_names) >", "def to_camel_upper_case(naming): lower = Formatter.to_camel_lower_case(naming) return lower[0].upper() + lower[1:] @staticmethod", "for param in throws])) return_type = self.__get_return_type(pos) if len(return_type) >", "pos -= 1 field_name = self.__tokens[pos].get_value() is_value = False if", "self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if self.__tokens[pos].get_value() == '>':", "@staticmethod def is_camel_lower_case(naming): return naming.find('_') == -1 and not naming.isupper()", "== ',': if not Formatter.is_camel_lower_case(self.__tokens[naming_pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[naming_pos].get_value()) params[self.__tokens[naming_pos].get_value()] =", "fixed_value) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[ i].get_value() in params.keys():", "i += 1 while self.__tokens[i].get_value() != ')': if self.__tokens[i +", "+ append_string + comment_string[i:] if comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token,", "self.__tokens[i + 1].get_value() in (';', '=', ','): pos = i", "self.__tokens[pos].get_value() in ('private', 'public', 'protected'): return self.__tokens[pos].get_value() pos += 1", "i): parameters = dict() while self.__tokens[i].get_value() != '(': i +=", "self.__tokens[i].get_value() == '{': brace_count += 1 elif self.__tokens[i].get_value() == '}':", "1 while count != 0: if self.__tokens[pos].get_value() == '{': count", "None: field_names = ', '.join(self.__get_field_names(pos)[0]) visibility = self.__find_visibility(pos) comment_token =", "f' * Implementation of {self.__find_class_name(pos)}\\n' \\ f' */' update_token_value(self.__file, comment_token,", "TokenType.KEYWORD) and self.__tokens[ pos + 1].get_value() != '.' and self.__tokens[pos].get_value()", "self.__get_throws(pos) if len(throws) > 0: all_params.append(\"\\n\".join([f\"{indent} * @throws {param}\" for", "self.__to_fix[name]) return link def __get_indent(self, pos): pos = self.__find_token_before(pos, '\\n')", "is_snake_lower_case(naming): return naming.islower() @staticmethod def to_snake_lower_case(naming): naming = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2',", "== TokenType.WHITESPACE: pos -= 1 while self.__tokens[pos].get_type() != TokenType.WHITESPACE: pos", "= Token(None, TokenType.COMMENT) comment_string = f'/*\\n' \\ f' * {self.__find_class_name()}\\n'", "+ 1].get_value() in (';', '=', ','): pos = i while", "Token(None, TokenType.COMMENT) comment_string = f'{indent}/**\\n' + \\ '\\n'.join(all_params) + \\", "= [] if comment_token is None: params = self.__get_parameter_list(pos) params.extend(self.__get_type_parameter_list(pos))", "while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 parameters.append(self.__tokens[i].get_value()) pos +=", "* The {visibility} {field_names} {\"constant\" if self.__is_final(pos) else \"variable\"}{\"s\" if", "in ('=', ';', '('): if self.__tokens[pos].get_value() in ('private', 'public', 'protected'):", "f'{indent} * The {visibility} {field_names} {\"constant\" if self.__is_final(pos) else \"variable\"}{\"s\"", "-= 1 elif self.__tokens[i].get_value() in ('=', ';'): naming_pos = i", "= comment_string[:i] + append_string + comment_string[i:] append_string = '' i", "f\"\\n{indent} * @return {return_type_value}\" else: i = comment_string.rfind('@return') while comment_string[i]", "else: for parameter in parameters: if not Formatter.is_camel_lower_case(parameter): self.__to_fix[parameter] =", "[] return_type = '' comment_string = comment_token.get_value() while i <", "= comment_string.find(' ', i) if comment_string[i:start] != '@see': i +=", "* {datetime.date.today().strftime(\"%B %d, %Y\")}\\n' \\ f' */' update_token_value(self.__file, comment_token, comment_string)", "files self.__file = None self.__tokens = [] self.__to_fix = dict()", "while self.__tokens[pos].get_value() != '{': if self.__tokens[pos].get_value() == ';': return pos", "while i < len(tokens): self.__tokens = tokens[i] self.__file = self.__files[i]", "in params.keys(): update_token_value(self.__file, self.__tokens[i], params[self.__tokens[i].get_value()]) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and", "self.__tokens[pos].get_value() pos += 1 return 'package-private' def __fix_method_comment(self, pos): comment_token", "self.__tokens[naming_pos].get_type() == TokenType.WHITESPACE: naming_pos -= 1 if self.__tokens[naming_pos].get_type() == TokenType.IDENTIFIER:", "naming[i] == '_': i += 1 naming = naming[i:] j", "and self.__tokens[pos].get_type() == TokenType.IDENTIFIER: throws.append(self.__tokens[pos].get_value()) pos += 1 return throws", "of {self.__find_class_name(pos)}\\n' \\ f' */' update_token_value(self.__file, comment_token, comment_string) insert_pos =", "+ \"\\n\".join( [f\"{indent} * @param {param}\" for param in Formatter.get_missing(params,", "for token in self.__tokens: if token.get_value() in self.__to_fix and not", "parse from javaccflab.java_token import TokenType, Token, update_token_value class Formatter: def", "-= 1 if not Formatter.is_camel_lower_case(self.__tokens[pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[pos].get_value()) parameters[self.__tokens[pos].get_value()] =", "TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token) return self.__fix_class_body_comments(pos) #", "if len(params) < len(params_list): append_string += \"\\n\" + \"\\n\".join( [f\"{indent}", "f'/*\\n' \\ f' * {self.__find_class_name()}\\n' \\ f' *\\n' \\ f'", "','): i = pos while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -=", "Fix start comment def __add_start_comment(self): if not self.__is_start_comment_exists(): comment_token =", "\"\\n\" + \"\\n\".join( [f\"{indent} * @throws {param}\" for param in", "def __fix_class_body_comments(self, pos): while self.__tokens[pos].get_value() != '{': pos += 1", "i < len(tokens): self.__tokens = tokens[i] self.__file = self.__files[i] self.__fix()", "is not None: new_link = self.__fix_link(link) comment_string = comment_string.replace(link, new_link)", "in ('<', ','): i = pos while self.__tokens[i].get_type() == TokenType.WHITESPACE:", "f'\\n{indent} */' update_token_value(self.__file, comment_token, comment_string) insert_pos = self.__find_token_before(pos, '\\n') self.__tokens.insert(insert_pos,", "= i - 1 while self.__tokens[naming_pos].get_type() == TokenType.WHITESPACE: naming_pos -=", "not Formatter.is_camel_upper_case(self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_camel_upper_case( self.__tokens[i].get_value()) i = self.__fix_class_body(i, self.__tokens[i].get_value())", "';'): return parameters while self.__tokens[pos].get_value() != '>': if self.__tokens[pos -", "naming.find('_') == -1 and not naming.isupper() and not naming[0].isupper() @staticmethod", "parameters def __fix_method_body(self, i, method_parameters): params = dict() while self.__tokens[i].get_value()", "1 naming = naming[i:] j = len(naming) - 1 while", "javaccflab.java_token import TokenType, Token, update_token_value class Formatter: def __init__(self, files):", "len(params) > 0: all_params.append(\"\\n\".join([f\"{indent} * @param {param}\" for param in", "comment_token, comment_string) value = new_value if macro == '@param': params.append(value)", "def __fix_class_body(self, pos, class_name): while self.__tokens[pos].get_value() != '{': pos +=", "if not Formatter.is_camel_upper_case(self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_camel_upper_case( self.__tokens[i].get_value()) i = self.__fix_class_body(i,", "i += 1 i += 1 # Fix start comment", "if not Formatter.is_camel_lower_case(self.__tokens[pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[pos].get_value()) parameters[self.__tokens[pos].get_value()] = fixed_value update_token_value(self.__file,", "comment_string) insert_pos = self.__find_token_before(pos, '\\n') self.__tokens.insert(insert_pos, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(insert_pos +", "Formatter.get_missing(throws, throws_list)]) i = comment_string.rfind('@throws') if i != -1: i", "i) if comment_string.find('\\n', i) != -1 else comment_string.find('*', i) -", "if comment_string[i] == '@': start = comment_string.find(' ', i) if", "!= class_name and not Formatter.is_snake_lower_case( self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_snake_lower_case(self.__tokens[i].get_value()) def", "parameter in parameters: if not Formatter.is_snake_upper_case(parameter): self.__to_fix[parameter] = Formatter.to_snake_upper_case(parameter) else:", "comment_string.find('\\n', start + 1)) end = end if end >=", "+= 1 naming = naming[i:] j = len(naming) - 1", "== TokenType.WHITESPACE: pos -= 1 field_name = self.__tokens[pos].get_value() is_value =", "return pos def __fix_class_body(self, pos, class_name): while self.__tokens[pos].get_value() != '{':", "@staticmethod def is_camel_upper_case(naming): return naming.find('_') == -1 and not naming.isupper()", "== '=': is_value = True pos -= 1 if not", "'' i = comment_string.find('\\n', i) if len(return_type) == '': append_string", "self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 while self.__tokens[pos].get_type() != TokenType.WHITESPACE:", "(';', ','): while pos > 0 and self.__tokens[pos].get_value() not in", "i = self.__fix_package(i) elif token.get_value() in ('class', 'interface') and self.__tokens[i", "not Formatter.is_camel_lower_case(parameter): self.__to_fix[parameter] = Formatter.to_camel_lower_case(parameter) pos = i else: self.__fix_method_name(pos,", "'' if len(throws) < len(throws_list): append_string += \"\\n\" + \"\\n\".join(", "link[ pos - 1].isdigit() or link[pos - 1] == '_'):", "self.__tokens[i].get_value() not in ('}', ';'): return parameters while self.__tokens[pos].get_value() !=", "if self.__is_parameter(pos): pos = self.__fix_field_comment(pos) else: pos = self.__fix_method_comment(pos) pos", "Formatter.to_camel_lower_case(self.__tokens[naming_pos].get_value()) params[self.__tokens[naming_pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[naming_pos], fixed_value) elif self.__tokens[i].get_type() ==", "i) macro = comment_string[i:start] end = min(comment_string.find(' ', start +", "Formatter.is_camel_lower_case(self.__tokens[naming_pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[naming_pos].get_value()) params[self.__tokens[naming_pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[naming_pos], fixed_value)", "f' */' update_token_value(self.__file, comment_token, comment_string) self.__tokens.insert(0, comment_token) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE))", "self.__tokens[i + 1].get_value() in (')', ','): pos = i while", "comment_token = self.__find_doc_comment_before(pos) if comment_token is None: comment_token = Token(None,", "if len(throws) < len(throws_list): append_string += \"\\n\" + \"\\n\".join( [f\"{indent}", "__find_token_after(self, pos, value): while pos < len(self.__tokens) and self.__tokens[pos].get_value() !=", "def __skip_ws_tokens(self, pos): while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos += 1", "self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1 return i def __get_field_names(self, i):", "= self.__tokens[pos].get_value() is_value = False if self.__tokens[i + 1].get_value() in", "== '>': while self.__tokens[pos].get_value() != '<': return_type.append(self.__tokens[pos].get_value()) pos -= 1", "TokenType.WHITESPACE: i -= 1 if self.__tokens[i].get_value() != class_name and not", "-= 1 if self.__tokens[pos].get_value() == '>': while self.__tokens[pos].get_value() != '<':", "method_parameters[self.__tokens[i].get_value()]) i += 1 return i def __get_field_names(self, i): params", "= 0 link = None comment_string = comment_token.get_value() while i", "== TokenType.WHITESPACE: if self.__tokens[pos].get_value() == ' ': count += 1", "comment_token) else: self.__fix_comment_links(comment_token) return self.__fix_class_body_comments(pos) # Fix comments for methods", "pos -= 1 if self.__tokens[pos].get_value() == '>': while self.__tokens[pos].get_value() !=", "-= 1 if not is_value: params.append(field_name) i += 1 end", "count = 1 pos += 1 while count != 0:", "naming[0].isupper() @staticmethod def to_camel_upper_case(naming): lower = Formatter.to_camel_lower_case(naming) return lower[0].upper() +", "self.__tokens[pos].get_value() != '(': pos += 1 pos -= 1 while", "!= comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) return self.__skip_method(pos) @staticmethod def get_missing(before,", "self.__tokens[i].get_value() in ('=', ';'): naming_pos = i - 1 while", "TokenType.KEYWORD or self.__tokens[i].get_value() not in ('}', ';'): return parameters while", "not (link[pos - 1].isalpha() or link[ pos - 1].isdigit() or", "pos = self.__fix_field_comment(pos) else: pos = self.__fix_method_comment(pos) pos += 1", "pos = self.__fix_method_comment(pos) pos += 1 return pos def __fix_field_comment(self,", "pos -= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: return_type.append(self.__tokens[pos].get_value()) pos -=", "Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token) params_list =", "== '}': count -= 1 pos += 1 return pos", "if self.__tokens[pos - 1].get_value() in ('<', ','): i = pos", "naming.isupper() and not naming[0].isupper() @staticmethod def to_camel_lower_case(naming): naming = Formatter.remove_underscores_around(naming)", "i += 1 return False def __is_parameter(self, pos): while self.__tokens[pos].get_value()", "*/' update_token_value(self.__file, comment_token, comment_string) self.__tokens.insert(0, comment_token) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(1,", "== '_'): link = link.replace(name, self.__to_fix[name]) return link def __get_indent(self,", "return ''.join([component.lower() for component in naming.split('_')]) @staticmethod def is_camel_lower_case(naming): return", "+= 1 while self.__tokens[i].get_value() != ')': if self.__tokens[i + 1].get_value()", "__find_to_fix(self): i = 0 while i < len(self.__tokens): token =", "self.__find_token_before(pos, '\\n') self.__tokens.insert(insert_pos, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1, comment_token) else:", "method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1 if self.__tokens[i].get_value() ==", "-1 and not naming.isupper() and not naming[0].isupper() @staticmethod def to_camel_lower_case(naming):", "@staticmethod def to_camel_upper_case(naming): lower = Formatter.to_camel_lower_case(naming) return lower[0].upper() + lower[1:]", "= '' i = comment_string.find('\\n', i) if len(return_type) == '':", "'(': return parameters pos += 1 i = pos -", "pos, value): while pos < len(self.__tokens) and self.__tokens[pos].get_value() != value:", "__find_token_before(self, pos, value): while pos > 0 and self.__tokens[pos].get_value() !=", "comment_string[i:start] != '@see': i += 1 continue end = comment_string.find('\\n',", "('(', ';'): i += 1 i -= 1 while self.__tokens[i].get_type()", "= self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) all_params = [] if comment_token", "TokenType.COMMENT) comment_string = comment_string = f'{indent}/**\\n' \\ f'{indent} * The", "== -1 and not naming.isupper() and not naming[0].isupper() @staticmethod def", "while i < len(self.__tokens): if self.__tokens[i].get_value() in ('class', 'interface'): i", "and not Formatter.is_snake_lower_case( self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_snake_lower_case(self.__tokens[i].get_value()) def __get_method_parameters(self, i):", "append_string = '' i = 0 if len(params) < len(params_list):", "tokens[i] = self.__tokens i += 1 return tokens def __find_to_fix(self):", "== '{': pos = i + 1 count += 1", "'interface') and self.__tokens[i - 1].get_value() != '.': i += 1", "comment_string[:i] + append_string + comment_string[i:] append_string = '' i =", "= pos while self.__tokens[i].get_type() == TokenType.WHITESPACE: i += 1 parameters.append(self.__tokens[i].get_value())", "comment_token is None: field_names = ', '.join(self.__get_field_names(pos)[0]) visibility = self.__find_visibility(pos)", "and fields def __fix_class_body_comments(self, pos): while self.__tokens[pos].get_value() != '{': pos", "'=', ','): pos = i while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos", "comment_string = f'{indent}/**\\n' \\ f'{indent} * The {visibility} {field_names} {\"constant\"", "len(return_type) == '': append_string += \"\\n\" + f\"\\n{indent} * @return", "None i += 1 if comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token,", "self.__files = files self.__file = None self.__tokens = [] self.__to_fix", "= self.__find_visibility(pos) comment_token = Token(None, TokenType.COMMENT) comment_string = comment_string =", "pos = i while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1", "self.__tokens[i].get_value() # Fix class comment def __fix_class_comments(self, pos): comment_token =", "start = comment_string.find(' ', i) end = comment_string.find('}', i) link", "return self.__tokens[pos].get_value() pos += 1 return 'package-private' def __fix_method_comment(self, pos):", "start + 1), comment_string.find('\\n', start + 1)) end = end", "'' i = 0 if len(params) < len(params_list): append_string +=", "\"\\n\".join( [f\"{indent} * @throws {param}\" for param in Formatter.get_missing(throws, throws_list)])", "1 elif self.__tokens[i].get_value() in ('=', ';'): naming_pos = i -", "if comment_token is None: params = self.__get_parameter_list(pos) params.extend(self.__get_type_parameter_list(pos)) if len(params)", "= comment_string.find('\\n', i) if comment_string.find('\\n', i) != -1 else comment_string.find('*',", "javaccflab.lexer import parse from javaccflab.java_token import TokenType, Token, update_token_value class", "= comment_string.replace(link, new_link) link = None i += 1 if", "== TokenType.WHITESPACE: i -= 1 parameters.append(self.__tokens[i].get_value()) pos += 1 return", "comments for methods and fields def __fix_class_body_comments(self, pos): while self.__tokens[pos].get_value()", "(';', '=', '('): if self.__tokens[i].get_value() == 'final': return True i", "parameters = [] while self.__tokens[pos].get_value() != '<': if self.__tokens[pos].get_value() ==", "count = 0 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: if self.__tokens[pos].get_value() ==", "Token(None, TokenType.COMMENT) comment_string = f'/**\\n' \\ f' * Implementation of", "all_params.append(f\"{indent} * @return {self.__get_return_type(pos)}\") comment_token = Token(None, TokenType.COMMENT) comment_string =", "'final': return True i += 1 return False def __is_parameter(self,", "[f\"{indent} * @param {param}\" for param in Formatter.get_missing(params, params_list)]) i", "value i += 1 return params, throws, return_type def __skip_method(self,", "def __fix_field_comment(self, pos): comment_token = self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) if", "append_string += \"\\n\" + \"\\n\".join( [f\"{indent} * @param {param}\" for", "* @throws {param}\" for param in throws])) return_type = self.__get_return_type(pos)", "while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 field_name = self.__tokens[pos].get_value()", "tokens[i] self.__file = self.__files[i] self.__find_to_fix() tokens[i] = self.__tokens i +=", "= self.__get_return_type(pos) params, throws, return_type = self.__fix_comment_params(comment_token) comment_string = comment_token.get_value()", "return naming.find('_') == -1 and not naming.isupper() and not naming[0].isupper()", "throws = self.__get_throws(pos) if len(throws) > 0: all_params.append(\"\\n\".join([f\"{indent} * @throws", "or self.__tokens[ type_pos].get_value() == ',': if not Formatter.is_camel_lower_case(self.__tokens[naming_pos].get_value()): fixed_value =", "(';', '=', ','): pos = i while self.__tokens[pos].get_type() == TokenType.WHITESPACE:", "\\ f' */' update_token_value(self.__file, comment_token, comment_string) self.__tokens.insert(0, comment_token) self.__tokens.insert(1, Token('\\n',", "self.__files[i] self.__find_to_fix() tokens[i] = self.__tokens i += 1 i =", "0 while i < len(tokens): self.__tokens = tokens[i] self.__file =", "comment_string[i] != '\\n': i -= 1 comment_string = comment_string[:i] +", "len(self.__tokens): if self.__tokens[i].get_value() in ('class', 'interface'): i = self.__fix_class_comments(i) i", "i while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if not", "comment_token) else: self.__fix_comment_links(comment_token) return self.__find_token_after(pos, ';') def __find_visibility(self, pos): pos", "';' and pos < len(self.__tokens): if self.__tokens[pos].get_value() == '=': return", "1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 while self.__tokens[pos].get_type()", "comment_string[i] == '@': start = comment_string.find(' ', i) macro =", "+= 1 continue end = comment_string.find('\\n', i) link = comment_string[start:end]", "and not token.is_fixed(): update_token_value(self.__file, token, self.__to_fix[token.get_value()]) def __fix_comments(self): self.__add_start_comment() i", "i += 1 i = self.__skip_ws_tokens(i + 1) return self.__tokens[i].get_value()", "return False def __is_parameter(self, pos): while self.__tokens[pos].get_value() != ';' and", "TokenType.WHITESPACE: if self.__tokens[pos].get_value() == ' ': count += 1 pos", "+= 1 elif self.__tokens[pos].get_value() == '}': count -= 1 pos", "__find_visibility(self, pos): pos = self.__find_token_before(pos, '\\n') while self.__tokens[pos].get_value() not in", "i = self.__fix_class_comments(i) i += 1 i += 1 #", "count != 0: if self.__tokens[pos].get_value() == '{': count += 1", "if len(field_names) > 0 else \"\"}\\n' \\ f'{indent} */' update_token_value(self.__file,", "self.__tokens i += 1 return tokens def __find_to_fix(self): i =", "elif self.__tokens[pos].get_value() in ('class', 'interface', '(', ')'): return False pos", "-1: i = comment_string.find('\\n', i) if comment_string.find('\\n', i) != -1", "\\ f' * {self.__find_class_name()}\\n' \\ f' *\\n' \\ f' *", "comment def __add_start_comment(self): if not self.__is_start_comment_exists(): comment_token = Token(None, TokenType.COMMENT)", "update_token_value(self.__file, comment_token, comment_string) def __fix_link(self, link): for name in self.__to_fix.keys():", "= self.__get_indent(pos) if comment_token is None: field_names = ', '.join(self.__get_field_names(pos)[0])", "self.__to_fix[parameter] = Formatter.to_snake_upper_case(parameter) else: for parameter in parameters: if not", "== -1 and not naming.isupper() and naming[0].isupper() @staticmethod def to_camel_upper_case(naming):", "self.__tokens[i].get_value() == 'final': return True i += 1 return False", "self.__find_doc_comment_before(pos) if comment_token is None: comment_token = Token(None, TokenType.COMMENT) comment_string", "if self.__tokens[i + 1].get_value() in (';', ','): while pos >", "= comment_token.get_value() while i < len(comment_string): if comment_string[i] == '@':", "!= '{': pos += 1 count = 1 pos +=", "def __is_final(self, i): while self.__tokens[i].get_value() not in (';', '=', '('):", "for methods and fields def __fix_class_body_comments(self, pos): while self.__tokens[pos].get_value() !=", "self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 parameters.append(self.__tokens[i].get_value()) pos += 1", "{field_names} {\"constant\" if self.__is_final(pos) else \"variable\"}{\"s\" if len(field_names) > 0", "-= 1 if self.__tokens[i].get_type() != TokenType.KEYWORD or self.__tokens[i].get_value() not in", "[] is_throws = False while self.__tokens[pos].get_value() not in ('{', ';'):", "('{', ';'): if self.__tokens[pos].get_value() == 'throws': is_throws = True elif", "{return_type_value}\" else: i = comment_string.rfind('@return') while comment_string[i] != '\\n': i", "+= 1 return pos def __fix_comment_links(self, comment_token): i = 0", "': count += 1 pos += 1 return ' '", "!= new_value: comment_string = comment_string.replace(value, new_value) update_token_value(self.__file, comment_token, comment_string) value", "Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token) return self.__fix_class_body_comments(pos)", "indent = self.__get_indent(pos) if comment_token is None: field_names = ',", "' ') + \\ f'\\n{indent} */' update_token_value(self.__file, comment_token, comment_string) insert_pos", "start = comment_string.find(' ', i) if comment_string[i:start] != '@see': i", "* count def __skip_ws_tokens(self, pos): while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos", "+= 1 return pos def __fix_method_name(self, i, class_name): while self.__tokens[i].get_value()", "= self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) if comment_token is None: field_names", "1), comment_string.find('\\n', start + 1)) if end > 0: value", "return pos def __fix_field_comment(self, pos): comment_token = self.__find_doc_comment_before(pos) indent =", "def __find_doc_comment_before(self, pos): while self.__tokens[pos].get_value() != '\\n': pos -= 1", "pos -= 1 if self.__tokens[pos].get_type() == TokenType.COMMENT and self.__tokens[pos].get_value().startswith('/**'): return", "TokenType.COMMENT and self.__tokens[pos].get_value().startswith('/**'): return self.__tokens[pos] return None def __find_token_before(self, pos,", "i, method_parameters): params = dict() while self.__tokens[i].get_value() not in ('{',", "link = comment_string[start:end] if link is not None: new_link =", "for file in self.__files: tokens.append(parse(open(file, 'r').read())) i = 0 while", "component in naming.split('_')] return components[0][0].lower() + components[0][1:] + ''.join(components[1:]) @staticmethod", "+= 1 elif self.__tokens[pos].get_value() == '}': count -= 1 elif", "start + 1), comment_string.find('\\n', start + 1)) if end >", "__fix_method_body(self, i, method_parameters): params = dict() while self.__tokens[i].get_value() not in", "0 else max(comment_string.find(' ', start + 1), comment_string.find('\\n', start +", "comment_string.replace(link, new_link) link = None i += 1 if comment_string", "throws_list)]) i = comment_string.rfind('@throws') if i != -1: i =", "self.__is_final(pos): for parameter in parameters: if not Formatter.is_snake_upper_case(parameter): self.__to_fix[parameter] =", "comment_token is None: comment_token = Token(None, TokenType.COMMENT) comment_string = f'/**\\n'", "1) if not Formatter.is_camel_upper_case(self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_camel_upper_case( self.__tokens[i].get_value()) i =", "else: self.__fix_comment_links(comment_token) params_list = self.__get_parameter_list(pos) params_list.extend(self.__get_type_parameter_list(pos)) throws_list = self.__get_throws(pos) return_type_value", "self.__tokens[pos].get_value() == ' ': count += 1 pos += 1", "(';', '}'): if self.__tokens[pos].get_value() == '=': is_value = True pos", "1 comment_string = comment_string[:i] + append_string + comment_string[i:] if comment_string", "'{': if self.__tokens[pos].get_value() == ';': return pos + 1 pos", "-= 1 if self.__tokens[pos].get_type() == TokenType.COMMENT and self.__tokens[pos].get_value().startswith('/**'): return self.__tokens[pos]", "True def __fix(self): for token in self.__tokens: if token.get_value() in", "self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) if comment_token is None: field_names =", "' ': count += 1 pos += 1 return '", "comment_string.rfind('@return') while comment_string[i] != '\\n': i -= 1 comment_string =", "parameters pos += 1 i = pos - 1 while", "1, comment_token) else: self.__fix_comment_links(comment_token) params_list = self.__get_parameter_list(pos) params_list.extend(self.__get_type_parameter_list(pos)) throws_list =", "return components[0][0].lower() + components[0][1:] + ''.join(components[1:]) @staticmethod def is_camel_upper_case(naming): return", "%Y\")}\\n' \\ f' */' update_token_value(self.__file, comment_token, comment_string) self.__tokens.insert(0, comment_token) self.__tokens.insert(1,", "link): for name in self.__to_fix.keys(): pos = link.find(name) if pos", "1)) end = end if end >= 0 else max(comment_string.find('", "return tokens def __find_to_fix(self): i = 0 while i <", "while self.__tokens[pos].get_value() not in ('=', ';', '('): if self.__tokens[pos].get_value() in", "type_pos = naming_pos - 1 while self.__tokens[type_pos].get_type() == TokenType.WHITESPACE: type_pos", "in (';', '=', ','): pos = i while self.__tokens[pos].get_type() ==", "1 comment_string = comment_string[:i] + append_string + comment_string[i:] append_string =", "else max(comment_string.find(' ', start + 1), comment_string.find('\\n', start + 1))", "f'{indent}/**\\n' + \\ '\\n'.join(all_params) + \\ ('' if len(params) <=", "-= 1 return pos def __find_token_after(self, pos, value): while pos", "Token(None, TokenType.COMMENT) comment_string = f'/*\\n' \\ f' * {self.__find_class_name()}\\n' \\", "tokens.append(parse(open(file, 'r').read())) i = 0 while i < len(tokens): self.__tokens", "if end > 0: value = comment_string[start + 1:end] new_value", "i = 0 link = None comment_string = comment_token.get_value() while", "self.__tokens[pos].get_value()): self.__to_fix[self.__tokens[pos].get_value()] = Formatter.to_lower_case( (self.__tokens[pos].get_value())) pos += 1 return pos", "> 0: all_params.append(\"\\n\".join([f\"{indent} * @param {param}\" for param in params]))", "Formatter.to_snake_lower_case(naming).upper() @staticmethod def remove_underscores_around(naming): i = 0 while naming[i] ==", "= comment_string[start:end] elif comment_string[i] == '{': start = comment_string.find(' ',", "fixed_value) i += 1 return parameters def __fix_method_body(self, i, method_parameters):", "- 1 while self.__tokens[naming_pos].get_type() == TokenType.WHITESPACE: naming_pos -= 1 if", "params.keys(): update_token_value(self.__file, self.__tokens[i], params[self.__tokens[i].get_value()]) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[", "= 0 while i < len(self.__tokens): if self.__tokens[i].get_value() in ('class',", "self.__tokens i += 1 i = 0 while i <", "i = 0 while i < len(self.__tokens): if self.__tokens[i].get_value() in", "-= 1 while pos > 0 and self.__tokens[pos].get_type() == TokenType.WHITESPACE:", "while self.__tokens[pos].get_value() != '<': return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value()) pos", "pos += 1 return ' ' * count def __skip_ws_tokens(self,", "= 1 pos += 1 while count != 0: if", "' ' * count def __skip_ws_tokens(self, pos): while self.__tokens[pos].get_type() ==", "1:end] new_value = self.__fix_link(value) if value != new_value: comment_string =", "self.__fix_comment_links(comment_token) params_list = self.__get_parameter_list(pos) params_list.extend(self.__get_type_parameter_list(pos)) throws_list = self.__get_throws(pos) return_type_value =", "1 return parameters def __get_throws(self, pos): throws = [] is_throws", "while i < len(comment_string): if comment_string[i] == '@': start =", "self.__tokens.insert(insert_pos, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token) params_list", "brace_count != 0: if self.__tokens[i].get_value() == '{': brace_count += 1", "pos += 1 return pos def __fix_method_name(self, i, class_name): while", "else component[0].upper() + component[1:] for component in naming.split('_')] return components[0][0].lower()", "+ 1), comment_string.find('\\n', start + 1)) end = end if", "comment_string = comment_string[:i] + append_string + comment_string[i:] append_string = ''", "append_string + comment_string[i:] if comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string)", "Implementation of {self.__find_class_name(pos)}\\n' \\ f' */' update_token_value(self.__file, comment_token, comment_string) insert_pos", "i = self.__get_field_names(pos) if self.__is_final(pos): for parameter in parameters: if", "self.__get_method_parameters(pos) pos = self.__fix_method_body(pos, parameters) pos += 1 return pos", "update_token_value(self.__file, comment_token, comment_string) self.__tokens.insert(0, comment_token) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(1, Token('\\n',", "+= 1 return throws def __get_return_type(self, pos): return_type = []", "None def __find_token_before(self, pos, value): while pos > 0 and", "if token.get_value() == 'package': i = self.__fix_package(i) elif token.get_value() in", "1].get_value() != '.' and self.__tokens[pos].get_value() not in ('class', 'interface'): if", "[] self.__to_fix = dict() def process(self): tokens = [] for", "while pos > 0 and self.__tokens[pos].get_value() not in (';', '}'):", "end = comment_string.find('\\n', i) link = comment_string[start:end] elif comment_string[i] ==", "pos = i else: self.__fix_method_name(pos, class_name) parameters = self.__get_method_parameters(pos) pos", "+= 1 return tokens def __find_to_fix(self): i = 0 while", "def __fix_comment_params(self, comment_token): i = 0 params = [] throws", "self.__tokens = tokens[i] self.__file = self.__files[i] self.__fix() self.__fix_comments() tokens[i] =", "pos): while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos += 1 return pos", "def is_snake_lower_case(naming): return naming.islower() @staticmethod def to_snake_lower_case(naming): naming = re.sub('(.)([A-Z][a-z]+)',", "- 1 while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 if", "self.__tokens[pos].get_value() == '(': return parameters pos += 1 i =", "\\ f'{indent} */' update_token_value(self.__file, comment_token, comment_string) insert_pos = self.__find_token_before(pos, '\\n')", "Formatter.to_snake_lower_case(self.__tokens[i].get_value()) def __get_method_parameters(self, i): parameters = dict() while self.__tokens[i].get_value() !=", "self.__tokens[i].get_value()) i += 1 def __fix_package(self, pos): pos = self.__skip_ws_tokens(pos)", "self.__tokens[pos].get_value() == 'throws': is_throws = True elif is_throws and self.__tokens[pos].get_type()", "+= 1 i -= 1 while self.__tokens[i].get_type() == TokenType.WHITESPACE: i", "= Formatter.remove_underscores_around(naming) components = [ component[0] + component[1:].lower() if component.isupper()", "{self.__find_class_name(pos)}\\n' \\ f' */' update_token_value(self.__file, comment_token, comment_string) insert_pos = self.__find_token_before(pos,", "return parameters def __get_throws(self, pos): throws = [] is_throws =", "macro = comment_string[i:start] end = min(comment_string.find(' ', start + 1),", "self.__tokens[pos].get_value() not in ('=', ';', '('): if self.__tokens[pos].get_value() in ('private',", "naming[j] == '_': i -= 1 naming = naming[:j +", "= self.__get_throws(pos) if len(throws) > 0: all_params.append(\"\\n\".join([f\"{indent} * @throws {param}\"", "comment_string.find('*', i) - 1 comment_string = comment_string[:i] + append_string +", "f' *\\n' \\ f' * {datetime.date.today().strftime(\"%B %d, %Y\")}\\n' \\ f'", "i = 0 if len(params) < len(params_list): append_string += \"\\n\"", "len(tokens): self.__tokens = tokens[i] self.__file = self.__files[i] self.__fix() self.__fix_comments() tokens[i]", "update_token_value(self.__file, self.__tokens[pos], fixed_value) i += 1 return parameters def __fix_method_body(self,", "while pos > 0 and self.__tokens[pos].get_value() != value: pos -=", "and pos < len(self.__tokens): if self.__tokens[pos].get_value() == '=': return True", "< len(self.__tokens): if self.__tokens[i].get_value() in ('class', 'interface'): i = self.__fix_class_comments(i)", "naming = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', naming) return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', naming).lower() @staticmethod", "+= 1 return parameters def __fix_method_body(self, i, method_parameters): params =", "new_value) update_token_value(self.__file, comment_token, comment_string) value = new_value if macro ==", "brace_count = 1 i += 1 while brace_count != 0:", "start + 1)) end = end if end >= 0", "pos -= 1 while self.__tokens[pos].get_type() != TokenType.WHITESPACE: pos -= 1", "= comment_string[i:start] end = min(comment_string.find(' ', start + 1), comment_string.find('\\n',", "1].get_value() != '.': i = self.__skip_ws_tokens(i + 1) if not", "field_names = ', '.join(self.__get_field_names(pos)[0]) visibility = self.__find_visibility(pos) comment_token = Token(None,", "fixed_value = Formatter.to_camel_lower_case(self.__tokens[naming_pos].get_value()) params[self.__tokens[naming_pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[naming_pos], fixed_value) elif", "{param}\" for param in throws])) return_type = self.__get_return_type(pos) if len(return_type)", "comment_string.find('}', i) link = comment_string[start:end] if link is not None:", "comment_token = Token(None, TokenType.COMMENT) comment_string = f'/*\\n' \\ f' *", "('class', 'interface', '(', ')'): return False pos += 1 return", "self.__tokens[pos].get_type() == TokenType.WHITESPACE: return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value()) return_type.reverse() return", "if comment_string[i:start] != '@see': i += 1 continue end =", "TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token) return self.__find_token_after(pos, ';')", "== TokenType.WHITESPACE: i -= 1 if self.__tokens[i].get_type() != TokenType.KEYWORD or", "\\ f' * {datetime.date.today().strftime(\"%B %d, %Y\")}\\n' \\ f' */' update_token_value(self.__file,", "pos): return_type = [] while self.__tokens[pos].get_value() != '(': pos +=", "= [] is_throws = False while self.__tokens[pos].get_value() not in ('{',", "is_throws = True elif is_throws and self.__tokens[pos].get_type() == TokenType.IDENTIFIER: throws.append(self.__tokens[pos].get_value())", "i < len(self.__tokens): if self.__tokens[i].get_value() in ('class', 'interface'): i =", "i -= 1 if self.__tokens[i].get_value() != class_name and not Formatter.is_snake_lower_case(", "[] while self.__tokens[pos].get_value() != '(': pos += 1 pos -=", "= i return params, end def __is_final(self, i): while self.__tokens[i].get_value()", "if self.__tokens[i].get_type() != TokenType.KEYWORD or self.__tokens[i].get_value() not in ('}', ';'):", "1 return pos def __fix_class_body(self, pos, class_name): while self.__tokens[pos].get_value() !=", "self.__tokens[i].get_value() != class_name and not Formatter.is_snake_lower_case( self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_snake_lower_case(self.__tokens[i].get_value())", "__fix_class_body_comments(self, pos): while self.__tokens[pos].get_value() != '{': pos += 1 count", "','): i = pos while self.__tokens[i].get_type() == TokenType.WHITESPACE: i +=", "to_camel_upper_case(naming): lower = Formatter.to_camel_lower_case(naming) return lower[0].upper() + lower[1:] @staticmethod def", "i += 1 return i def __get_field_names(self, i): params =", "if self.__tokens[i].get_value() == 'final': return True i += 1 return", "Formatter.is_snake_lower_case( self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_snake_lower_case(self.__tokens[i].get_value()) def __get_method_parameters(self, i): parameters =", "+ ''.join(components[1:]) @staticmethod def is_camel_upper_case(naming): return naming.find('_') == -1 and", "<= 0 else ' ') + \\ f'\\n{indent} */' update_token_value(self.__file,", "1 elif self.__tokens[i].get_value() == '}': brace_count -= 1 elif self.__tokens[i].get_value()", "self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) all_params = [] if comment_token is", "params_list.extend(self.__get_type_parameter_list(pos)) throws_list = self.__get_throws(pos) return_type_value = self.__get_return_type(pos) params, throws, return_type", "1].get_value() in (';', '=', ','): pos = i while self.__tokens[pos].get_type()", "i = 0 while i < len(self.__tokens): token = self.__tokens[i]", "value: pos -= 1 return pos def __find_token_after(self, pos, value):", "'@': start = comment_string.find(' ', i) macro = comment_string[i:start] end", "while naming[i] == '_': i += 1 naming = naming[i:]", "== '{': start = comment_string.find(' ', i) end = comment_string.find('}',", "return True i += 1 return False def __is_parameter(self, pos):", "!= '>': if self.__tokens[pos - 1].get_value() in ('<', ','): i", "comment_string[start + 1:end] new_value = self.__fix_link(value) if value != new_value:", "comment_string = comment_token.get_value() while i < len(comment_string): if comment_string[i] ==", "\"\"}\\n' \\ f'{indent} */' update_token_value(self.__file, comment_token, comment_string) insert_pos = self.__find_token_before(pos,", "+= \"\\n\" + \"\\n\".join( [f\"{indent} * @param {param}\" for param", "not in ('(', ';'): i += 1 i -= 1", "len(throws) > 0: all_params.append(\"\\n\".join([f\"{indent} * @throws {param}\" for param in", "__get_indent(self, pos): pos = self.__find_token_before(pos, '\\n') count = 0 while", "comment_string) self.__tokens.insert(0, comment_token) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) def", "self.__get_return_type(pos) params, throws, return_type = self.__fix_comment_params(comment_token) comment_string = comment_token.get_value() append_string", "< len(throws_list): append_string += \"\\n\" + \"\\n\".join( [f\"{indent} * @throws", "param in throws])) return_type = self.__get_return_type(pos) if len(return_type) > 0:", "i += 1 # Fix start comment def __add_start_comment(self): if", "end > 0: value = comment_string[start + 1:end] new_value =", "'(': i += 1 while self.__tokens[i].get_value() != ')': if self.__tokens[i", "self.__skip_ws_tokens(i + 1) return self.__tokens[i].get_value() # Fix class comment def", "= comment_token.get_value() append_string = '' i = 0 if len(params)", "params[self.__tokens[i].get_value()]) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[ i].get_value() in method_parameters.keys():", "comment_string.find('\\n', i) != -1 else comment_string.find('*', i) - 1 comment_string", "@staticmethod def to_snake_lower_case(naming): naming = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', naming) return re.sub('([a-z0-9])([A-Z])',", "while count != 0: if self.__tokens[pos].get_value() == '{': count +=", "parameters = dict() while self.__tokens[i].get_value() != '(': i += 1", "return True elif self.__tokens[pos].get_value() in ('class', 'interface', '(', ')'): return", "self.__tokens: if token.get_value() in self.__to_fix and not token.is_fixed(): update_token_value(self.__file, token,", "= 0 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: if self.__tokens[pos].get_value() == '", "i < len(tokens): self.__tokens = tokens[i] self.__file = self.__files[i] self.__find_to_fix()", "naming.isupper() and naming[0].isupper() @staticmethod def to_camel_upper_case(naming): lower = Formatter.to_camel_lower_case(naming) return", "self.__tokens[pos].get_value() == '=': return True elif self.__tokens[pos].get_value() in ('class', 'interface',", "__fix_package(self, pos): pos = self.__skip_ws_tokens(pos) while self.__tokens[pos].get_value() != ';': if", "return pos def __find_doc_comment_before(self, pos): while self.__tokens[pos].get_value() != '\\n': pos", "params.extend(self.__get_type_parameter_list(pos)) if len(params) > 0: all_params.append(\"\\n\".join([f\"{indent} * @param {param}\" for", "+= 1 if comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) def", "pos += 1 i = pos - 1 while self.__tokens[i].get_type()", "1].isdigit() or link[pos - 1] == '_'): link = link.replace(name,", "pos): while self.__tokens[pos].get_value() != '\\n': pos -= 1 while pos", "pos): comment_token = self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) all_params = []", "if self.__tokens[pos].get_value() == 'throws': is_throws = True elif is_throws and", "+ 1].get_value() != '.' and self.__tokens[pos].get_value() not in ('class', 'interface'):", "= [] throws = [] return_type = '' comment_string =", "self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token) return self.__find_token_after(pos, ';') def", "is None: field_names = ', '.join(self.__get_field_names(pos)[0]) visibility = self.__find_visibility(pos) comment_token", "= pos while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 parameters.append(self.__tokens[i].get_value())", "comment_string = f'{indent}/**\\n' + \\ '\\n'.join(all_params) + \\ ('' if", "self.__tokens.insert(insert_pos, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token) return", "self.__tokens[pos].get_value() != ';': if self.__tokens[pos].get_type() == TokenType.IDENTIFIER and not Formatter.is_lower_case(", "-1 and naming.islower() @staticmethod def to_lower_case(naming): return ''.join([component.lower() for component", "!= '<': return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value()) pos -= 1", "+ 1)) if end > 0: value = comment_string[start +", "return True def __fix(self): for token in self.__tokens: if token.get_value()", "[] while self.__tokens[i].get_value() != ';': if self.__tokens[i + 1].get_value() in", "1].isalpha() or link[ pos - 1].isdigit() or link[pos - 1]", "if self.__tokens[pos].get_type() == TokenType.IDENTIFIER and not Formatter.is_lower_case( self.__tokens[pos].get_value()): self.__to_fix[self.__tokens[pos].get_value()] =", "* @throws {param}\" for param in Formatter.get_missing(throws, throws_list)]) i =", "naming = Formatter.remove_underscores_around(naming) components = [ component[0] + component[1:].lower() if", "return link def __get_indent(self, pos): pos = self.__find_token_before(pos, '\\n') count", "and self.__tokens[ i].get_value() in params.keys(): update_token_value(self.__file, self.__tokens[i], params[self.__tokens[i].get_value()]) elif self.__tokens[i].get_type()", "\"\\n\" + \"\\n\".join( [f\"{indent} * @param {param}\" for param in", "+ 1), comment_string.find('\\n', start + 1)) if end > 0:", "= self.__skip_ws_tokens(pos) while self.__tokens[pos].get_value() != ';': if self.__tokens[pos].get_type() == TokenType.IDENTIFIER", "token, self.__to_fix[token.get_value()]) def __fix_comments(self): self.__add_start_comment() i = 0 while i", "self.__skip_method(pos) @staticmethod def get_missing(before, after): missing_params = [] for value", "== '': append_string += \"\\n\" + f\"\\n{indent} * @return {return_type_value}\"", "if self.__tokens[i].get_value() == '{': brace_count += 1 elif self.__tokens[i].get_value() ==", "self.__tokens[pos].get_value() == '=': is_value = True pos -= 1 if", "naming_pos - 1 while self.__tokens[type_pos].get_type() == TokenType.WHITESPACE: type_pos -= 1", "1 def __fix_package(self, pos): pos = self.__skip_ws_tokens(pos) while self.__tokens[pos].get_value() !=", "update_token_value class Formatter: def __init__(self, files): self.__files = files self.__file", "comment_string.find(' ', i) end = comment_string.find('}', i) link = comment_string[start:end]", "TokenType.WHITESPACE: pos -= 1 field_name = self.__tokens[pos].get_value() is_value = False", "return None def __find_token_before(self, pos, value): while pos > 0", "params_list = self.__get_parameter_list(pos) params_list.extend(self.__get_type_parameter_list(pos)) throws_list = self.__get_throws(pos) return_type_value = self.__get_return_type(pos)", "comment_string) value = new_value if macro == '@param': params.append(value) elif", "self.__tokens[ type_pos].get_value() == ',': if not Formatter.is_camel_lower_case(self.__tokens[naming_pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[naming_pos].get_value())", "1 pos += 1 return pos def __find_doc_comment_before(self, pos): while", "self.__tokens = tokens[i] self.__file = self.__files[i] self.__find_to_fix() tokens[i] = self.__tokens", "1 count += 1 continue elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD)", "= end if end >= 0 else max(comment_string.find(' ', start", "self.__is_final(pos) else \"variable\"}{\"s\" if len(field_names) > 0 else \"\"}\\n' \\", "in Formatter.get_missing(params, params_list)]) i = comment_string.rfind('@param') if i != -1:", "r'\\1_\\2', naming) return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', naming).lower() @staticmethod def is_snake_upper_case(naming): return", "def __fix_package(self, pos): pos = self.__skip_ws_tokens(pos) while self.__tokens[pos].get_value() != ';':", "self.__files[i] self.__fix() self.__fix_comments() tokens[i] = self.__tokens i += 1 return", "self.__find_visibility(pos) comment_token = Token(None, TokenType.COMMENT) comment_string = comment_string = f'{indent}/**\\n'", "macro == '@return': return_type = value i += 1 return", "== TokenType.WHITESPACE: pos -= 1 if not Formatter.is_camel_lower_case(self.__tokens[pos].get_value()): fixed_value =", "if comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) def __fix_link(self, link):", "(TokenType.IDENTIFIER, TokenType.KEYWORD) and self.__tokens[ pos + 1].get_value() != '.' and", "+ append_string + comment_string[i:] append_string = '' if len(throws) <", "0 else \"\"}\\n' \\ f'{indent} */' update_token_value(self.__file, comment_token, comment_string) insert_pos", "The {visibility} {field_names} {\"constant\" if self.__is_final(pos) else \"variable\"}{\"s\" if len(field_names)", "('' if len(params) <= 0 else ' ') + \\", "in self.__to_fix.keys(): pos = link.find(name) if pos != -1 and", "or link[pos - 1] == '_'): link = link.replace(name, self.__to_fix[name])", "all_params.append(\"\\n\".join([f\"{indent} * @throws {param}\" for param in throws])) return_type =", "self.__fix_method_body(pos, parameters) pos += 1 return pos def __fix_method_name(self, i,", "+ 1) if self.__tokens[i].get_value() == '{': pos = i +", "comment_token): i = 0 link = None comment_string = comment_token.get_value()", "pos): parameters = [] while self.__tokens[pos].get_value() != '<': if self.__tokens[pos].get_value()", "0 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: if self.__tokens[pos].get_value() == ' ':", "method_parameters): params = dict() while self.__tokens[i].get_value() not in ('{', ';'):", "== 'static': i = self.__skip_ws_tokens(pos + 1) if self.__tokens[i].get_value() ==", "= Formatter.to_camel_lower_case(naming) return lower[0].upper() + lower[1:] @staticmethod def is_snake_lower_case(naming): return", "self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 field_name = self.__tokens[pos].get_value() is_value", "', i) end = comment_string.find('}', i) link = comment_string[start:end] if", "Token, update_token_value class Formatter: def __init__(self, files): self.__files = files", "[] while self.__tokens[pos].get_value() != '(': pos += 1 while self.__tokens[pos].get_value()", "i = pos while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1", "naming.isupper() @staticmethod def to_snake_upper_case(naming): return Formatter.to_snake_lower_case(naming).upper() @staticmethod def remove_underscores_around(naming): i", "not in (';', '}'): if self.__tokens[pos].get_value() == '=': is_value =", "self.__tokens[pos].get_value() == 'static': i = self.__skip_ws_tokens(pos + 1) if self.__tokens[i].get_value()", "0: value = comment_string[start + 1:end] new_value = self.__fix_link(value) if", "', start + 1), comment_string.find('\\n', start + 1)) if end", "if self.__tokens[pos].get_value() == '>': while self.__tokens[pos].get_value() != '<': return_type.append(self.__tokens[pos].get_value()) pos", "1 return pos def __fix_field_comment(self, pos): comment_token = self.__find_doc_comment_before(pos) indent", "= self.__get_field_names(pos) if self.__is_final(pos): for parameter in parameters: if not", "+= 1 continue elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD): if self.__is_parameter(pos):", "= Formatter.to_lower_case( (self.__tokens[pos].get_value())) pos += 1 return pos def __fix_class_body(self,", "class_name): while self.__tokens[pos].get_value() != '{': pos += 1 count =", "'static': i = self.__skip_ws_tokens(pos + 1) if self.__tokens[i].get_value() == '{':", "self.__skip_ws_tokens(0) return self.__tokens[i].get_type() == TokenType.COMMENT def __find_class_name(self, i=0): while self.__tokens[i].get_value()", "[] for file in self.__files: tokens.append(parse(open(file, 'r').read())) i = 0", "params = self.__get_parameter_list(pos) params.extend(self.__get_type_parameter_list(pos)) if len(params) > 0: all_params.append(\"\\n\".join([f\"{indent} *", "if (self.__tokens[type_pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and \\ self.__tokens[type_pos].get_value() not in", "dict() while self.__tokens[i].get_value() not in ('{', ';'): if self.__tokens[i].get_value() in", "+= 1 # Fix start comment def __add_start_comment(self): if not", "self.__get_return_type(pos) if len(return_type) > 0: all_params.append(f\"{indent} * @return {self.__get_return_type(pos)}\") comment_token", "0 params = [] throws = [] return_type = ''", "== TokenType.WHITESPACE: i -= 1 if self.__tokens[i].get_value() != class_name and", "'(': pos += 1 while self.__tokens[pos].get_value() != ')': if self.__tokens[pos", "while self.__tokens[pos].get_value() != '(': pos += 1 while self.__tokens[pos].get_value() !=", "- 1].get_value() in ('<', ','): i = pos while self.__tokens[i].get_type()", "+ \\ f'\\n{indent} */' update_token_value(self.__file, comment_token, comment_string) insert_pos = self.__find_token_before(pos,", "or link[ pos - 1].isdigit() or link[pos - 1] ==", "self.__tokens[ i].get_value() in params.keys(): update_token_value(self.__file, self.__tokens[i], params[self.__tokens[i].get_value()]) elif self.__tokens[i].get_type() ==", "!= '@see': i += 1 continue end = comment_string.find('\\n', i)", "brace_count += 1 elif self.__tokens[i].get_value() == '}': brace_count -= 1", "+ comment_string[i:] append_string = '' if len(throws) < len(throws_list): append_string", "pos < len(self.__tokens): if self.__tokens[pos].get_value() == '=': return True elif", "self.__skip_ws_tokens(pos + 1) if self.__tokens[i].get_value() == '{': pos = i", "while pos < len(self.__tokens) and self.__tokens[pos].get_value() != value: pos +=", "pos = self.__find_token_before(pos, '\\n') count = 0 while self.__tokens[pos].get_type() ==", "and self.__tokens[i - 1].get_value() != '.': i = self.__skip_ws_tokens(i +", "!= ';': if self.__tokens[i + 1].get_value() in (';', '=', ','):", "= self.__get_throws(pos) return_type_value = self.__get_return_type(pos) params, throws, return_type = self.__fix_comment_params(comment_token)", "remove_underscores_around(naming): i = 0 while naming[i] == '_': i +=", "('=', ';', '('): if self.__tokens[pos].get_value() in ('private', 'public', 'protected'): return", "while self.__tokens[pos].get_type() == TokenType.WHITESPACE: if self.__tokens[pos].get_value() == ' ': count", "= self.__get_parameter_list(pos) params.extend(self.__get_type_parameter_list(pos)) if len(params) > 0: all_params.append(\"\\n\".join([f\"{indent} * @param", "+ comment_string[i:] append_string = '' i = comment_string.find('\\n', i) if", "f' * {datetime.date.today().strftime(\"%B %d, %Y\")}\\n' \\ f' */' update_token_value(self.__file, comment_token,", "__fix_class_comments(self, pos): comment_token = self.__find_doc_comment_before(pos) if comment_token is None: comment_token", "while self.__tokens[type_pos].get_type() == TokenType.WHITESPACE: type_pos -= 1 if (self.__tokens[type_pos].get_type() in", "throws, return_type def __skip_method(self, pos): while self.__tokens[pos].get_value() != '{': if", "component[1:].lower() if component.isupper() else component[0].upper() + component[1:] for component in", "'_': i += 1 naming = naming[i:] j = len(naming)", "[] if comment_token is None: params = self.__get_parameter_list(pos) params.extend(self.__get_type_parameter_list(pos)) if", "'.' and self.__tokens[pos].get_value() not in ('class', 'interface'): if self.__is_parameter(pos): pos", "self.__to_fix[token.get_value()]) def __fix_comments(self): self.__add_start_comment() i = 0 while i <", "1 while self.__tokens[i].get_value() != ')': if self.__tokens[i + 1].get_value() in", "\\ ('' if len(params) <= 0 else ' ') +", "__fix_comment_params(self, comment_token): i = 0 params = [] throws =", "self.__tokens[i].get_value() not in (';', '=', '('): if self.__tokens[i].get_value() == 'final':", "= comment_string.find('\\n', i) link = comment_string[start:end] elif comment_string[i] == '{':", "update_token_value(self.__file, comment_token, comment_string) return self.__skip_method(pos) @staticmethod def get_missing(before, after): missing_params", "self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 if self.__tokens[i].get_type() != TokenType.KEYWORD", "i) end = comment_string.find('}', i) link = comment_string[start:end] if link", "if self.__tokens[i].get_value() == '{': pos = i + 1 count", "= self.__tokens[i] if token.get_value() == 'package': i = self.__fix_package(i) elif", "'('): if self.__tokens[i].get_value() == 'final': return True i += 1", "self.__is_parameter(pos): pos = self.__fix_field_comment(pos) else: pos = self.__fix_method_comment(pos) pos +=", "not naming[0].isupper() @staticmethod def to_camel_lower_case(naming): naming = Formatter.remove_underscores_around(naming) components =", "= Formatter.to_camel_upper_case( self.__tokens[i].get_value()) i = self.__fix_class_body(i, self.__tokens[i].get_value()) i += 1", "self.__fix_comment_links(comment_token) return self.__fix_class_body_comments(pos) # Fix comments for methods and fields", "update_token_value(self.__file, token, self.__to_fix[token.get_value()]) def __fix_comments(self): self.__add_start_comment() i = 0 while", "TokenType.WHITESPACE: i += 1 parameters.append(self.__tokens[i].get_value()) pos += 1 return parameters", "self.__fix_method_comment(pos) pos += 1 return pos def __fix_field_comment(self, pos): comment_token", "if len(return_type) > 0: all_params.append(f\"{indent} * @return {self.__get_return_type(pos)}\") comment_token =", "if component.isupper() else component[0].upper() + component[1:] for component in naming.split('_')]", "= 1 i += 1 while brace_count != 0: if", "and self.__tokens[pos].get_value().startswith('/**'): return self.__tokens[pos] return None def __find_token_before(self, pos, value):", "self.__tokens[pos].get_value() == '{': count += 1 elif self.__tokens[pos].get_value() == '}':", "@throws {param}\" for param in Formatter.get_missing(throws, throws_list)]) i = comment_string.rfind('@throws')", "< len(tokens): self.__tokens = tokens[i] self.__file = self.__files[i] self.__find_to_fix() tokens[i]", "i -= 1 comment_string = comment_string[:i] + append_string + comment_string[i:]", "i].get_value() in params.keys(): update_token_value(self.__file, self.__tokens[i], params[self.__tokens[i].get_value()]) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER", "pos -= 1 while pos > 0 and self.__tokens[pos].get_type() ==", "1 while pos > 0 and self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos", "self.__tokens[i].get_value() not in ('{', ';'): if self.__tokens[i].get_value() in method_parameters.keys(): update_token_value(self.__file,", "new_link) link = None i += 1 if comment_string !=", "= 0 while i < len(tokens): self.__tokens = tokens[i] self.__file", "'\\n') self.__tokens.insert(insert_pos, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token)", "if self.__tokens[pos].get_type() == TokenType.COMMENT and self.__tokens[pos].get_value().startswith('/**'): return self.__tokens[pos] return None", "{param}\" for param in Formatter.get_missing(throws, throws_list)]) i = comment_string.rfind('@throws') if", "= dict() while self.__tokens[i].get_value() not in ('{', ';'): if self.__tokens[i].get_value()", "= fixed_value update_token_value(self.__file, self.__tokens[pos], fixed_value) i += 1 return parameters", "comment_token.get_value() append_string = '' i = 0 if len(params) <", "!= '\\n': pos -= 1 while pos > 0 and", "throws = [] return_type = '' comment_string = comment_token.get_value() while", "not None: new_link = self.__fix_link(link) comment_string = comment_string.replace(link, new_link) link", "= Formatter.to_camel_lower_case(parameter) pos = i else: self.__fix_method_name(pos, class_name) parameters =", "== '@': start = comment_string.find(' ', i) if comment_string[i:start] !=", "while naming[j] == '_': i -= 1 naming = naming[:j", "not in ('class', 'interface'): if self.__is_parameter(pos): pos = self.__fix_field_comment(pos) else:", "__fix_class_body(self, pos, class_name): while self.__tokens[pos].get_value() != '{': pos += 1", "param in Formatter.get_missing(throws, throws_list)]) i = comment_string.rfind('@throws') if i !=", "TokenType.COMMENT) comment_string = f'/**\\n' \\ f' * Implementation of {self.__find_class_name(pos)}\\n'", "class_name) parameters = self.__get_method_parameters(pos) pos = self.__fix_method_body(pos, parameters) pos +=", "+= 1 return True def __fix(self): for token in self.__tokens:", "continue elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD): if self.__is_parameter(pos): parameters, i", "1].get_value() != '.': i += 1 i = self.__skip_ws_tokens(i +", "self.__tokens[pos].get_value() not in ('class', 'interface'): if self.__is_parameter(pos): pos = self.__fix_field_comment(pos)", "len(comment_string): if comment_string[i] == '@': start = comment_string.find(' ', i)", "= 0 if len(params) < len(params_list): append_string += \"\\n\" +", "i += 1 naming = naming[i:] j = len(naming) -", "self.__tokens[pos].get_value() != '<': if self.__tokens[pos].get_value() == '(': return parameters pos", "{self.__get_return_type(pos)}\") comment_token = Token(None, TokenType.COMMENT) comment_string = f'{indent}/**\\n' + \\", "1 while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 if self.__tokens[i].get_value()", "[f\"{indent} * @throws {param}\" for param in Formatter.get_missing(throws, throws_list)]) i", "1 while self.__tokens[pos].get_value() != ')': if self.__tokens[pos + 1].get_value() in", "comment_string[:i] + append_string + comment_string[i:] append_string = '' if len(throws)", "TokenType.WHITESPACE: pos -= 1 if self.__tokens[pos].get_type() == TokenType.COMMENT and self.__tokens[pos].get_value().startswith('/**'):", "+= 1 i = 0 while i < len(tokens): self.__tokens", "def process(self): tokens = [] for file in self.__files: tokens.append(parse(open(file,", "files): self.__files = files self.__file = None self.__tokens = []", "= naming[i:] j = len(naming) - 1 while naming[j] ==", "self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token) return self.__fix_class_body_comments(pos) # Fix", "if comment_token is None: field_names = ', '.join(self.__get_field_names(pos)[0]) visibility =", "= [] while self.__tokens[pos].get_value() != '(': pos += 1 pos", "(')', ','): pos = i while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos", "self.__find_token_before(pos, '\\n') while self.__tokens[pos].get_value() not in ('=', ';', '('): if", "in ('class', 'identifier')) or self.__tokens[ type_pos].get_value() == ',': if not", "1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if self.__tokens[pos].get_value()", "1 count += 1 continue elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD):", "len(params_list): append_string += \"\\n\" + \"\\n\".join( [f\"{indent} * @param {param}\"", "link = None comment_string = comment_token.get_value() while i < len(comment_string):", "'': append_string += \"\\n\" + f\"\\n{indent} * @return {return_type_value}\" else:", "__find_class_name(self, i=0): while self.__tokens[i].get_value() not in ('class', 'interface') and self.__tokens[i", "not in (';', '=', '('): if self.__tokens[i].get_value() == 'final': return", "comment_string[i:] append_string = '' i = comment_string.find('\\n', i) if len(return_type)", "-= 1 field_name = self.__tokens[pos].get_value() is_value = False if self.__tokens[i", "i return params, end def __is_final(self, i): while self.__tokens[i].get_value() not", "0 else ' ') + \\ f'\\n{indent} */' update_token_value(self.__file, comment_token,", "comment_token = Token(None, TokenType.COMMENT) comment_string = f'/**\\n' \\ f' *", "+= 1 return False def __is_parameter(self, pos): while self.__tokens[pos].get_value() !=", "def __get_field_names(self, i): params = [] while self.__tokens[i].get_value() != ';':", "return naming.islower() @staticmethod def to_snake_lower_case(naming): naming = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', naming)", "value: pos += 1 return pos def __fix_comment_links(self, comment_token): i", "__get_type_parameter_list(self, pos): parameters = [] while self.__tokens[pos].get_value() != '<': if", "in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1 return i", "all_params.append(\"\\n\".join([f\"{indent} * @param {param}\" for param in params])) throws =", "is None: params = self.__get_parameter_list(pos) params.extend(self.__get_type_parameter_list(pos)) if len(params) > 0:", "if self.__tokens[pos + 1].get_value() in (')', ','): i = pos", "elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[ i].get_value() in method_parameters.keys(): update_token_value(self.__file,", "!= ')': if self.__tokens[i + 1].get_value() in (')', ','): pos", "1 while naming[j] == '_': i -= 1 naming =", "self.__get_field_names(pos) if self.__is_final(pos): for parameter in parameters: if not Formatter.is_snake_upper_case(parameter):", "self.__tokens[pos - 1].get_value() in ('<', ','): i = pos while", "return_type.append(self.__tokens[pos].get_value()) return_type.reverse() return ''.join(return_type) def __fix_comment_params(self, comment_token): i = 0", "params, throws, return_type def __skip_method(self, pos): while self.__tokens[pos].get_value() != '{':", "i=0): while self.__tokens[i].get_value() not in ('class', 'interface') and self.__tokens[i -", "!= '\\n': i -= 1 comment_string = comment_string[:i] + append_string", "while self.__tokens[pos].get_value() not in ('{', ';'): if self.__tokens[pos].get_value() == 'throws':", "while self.__tokens[pos].get_value() != '{': pos += 1 count = 1", "= comment_string[start + 1:end] new_value = self.__fix_link(value) if value !=", "to_snake_lower_case(naming): naming = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', naming) return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', naming).lower()", "while self.__tokens[pos].get_value() != '\\n': pos -= 1 while pos >", "= False while self.__tokens[pos].get_value() not in ('{', ';'): if self.__tokens[pos].get_value()", "while self.__tokens[pos].get_value() != ';' and pos < len(self.__tokens): if self.__tokens[pos].get_value()", "'package': i = self.__fix_package(i) elif token.get_value() in ('class', 'interface') and", "'.': i = self.__skip_ws_tokens(i + 1) if not Formatter.is_camel_upper_case(self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()]", "'\\n': i -= 1 comment_string = comment_string[:i] + append_string +", "self.__tokens[pos].get_value() != '\\n': pos -= 1 while pos > 0", "self.__tokens[pos].get_value() == '}': count -= 1 elif self.__tokens[pos].get_value() == 'static':", "components = [ component[0] + component[1:].lower() if component.isupper() else component[0].upper()", "__fix_method_name(self, i, class_name): while self.__tokens[i].get_value() not in ('(', ';'): i", "-1 and not naming.isupper() and naming[0].isupper() @staticmethod def to_camel_upper_case(naming): lower", "!= comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) def __fix_link(self, link): for name", "and not naming[0].isupper() @staticmethod def to_camel_lower_case(naming): naming = Formatter.remove_underscores_around(naming) components", "= False if self.__tokens[i + 1].get_value() in (';', ','): while", "+= 1 if self.__tokens[i].get_value() == ';': return i + 1", "+ 1].get_value() in (')', ','): i = pos while self.__tokens[i].get_type()", "!= -1: i = comment_string.find('\\n', i) if comment_string.find('\\n', i) !=", "pos += 1 return pos def __fix_class_body(self, pos, class_name): while", "else: i = comment_string.rfind('@return') while comment_string[i] != '\\n': i -=", "comment_token, comment_string) self.__tokens.insert(0, comment_token) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE))", "comment_string.find(' ', i) if comment_string[i:start] != '@see': i += 1", "= f'{indent}/**\\n' \\ f'{indent} * The {visibility} {field_names} {\"constant\" if", "self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1 if self.__tokens[i].get_value() == ';': return", "append_string += \"\\n\" + f\"\\n{indent} * @return {return_type_value}\" else: i", "< len(self.__tokens) and self.__tokens[pos].get_value() != value: pos += 1 return", "self.__fix_method_name(pos, class_name) parameters = self.__get_method_parameters(pos) pos = self.__fix_method_body(pos, parameters) pos", "i) if comment_string[i:start] != '@see': i += 1 continue end", "self.__skip_ws_tokens(i + 1) if not Formatter.is_camel_upper_case(self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_camel_upper_case( self.__tokens[i].get_value())", "= Formatter.to_camel_lower_case(self.__tokens[naming_pos].get_value()) params[self.__tokens[naming_pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[naming_pos], fixed_value) elif self.__tokens[i].get_type()", "return params, end def __is_final(self, i): while self.__tokens[i].get_value() not in", "+= 1 pos += 1 return ' ' * count", "return False pos += 1 return True def __fix(self): for", "= comment_string[:i] + append_string + comment_string[i:] if comment_string != comment_token.get_value():", "comment_string[start:end] if link is not None: new_link = self.__fix_link(link) comment_string", "Formatter.is_camel_upper_case(self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_camel_upper_case( self.__tokens[i].get_value()) i = self.__fix_class_body(i, self.__tokens[i].get_value()) i", "self.__tokens[pos].get_value().startswith('/**'): return self.__tokens[pos] return None def __find_token_before(self, pos, value): while", "len(self.__tokens) and self.__tokens[pos].get_value() != value: pos += 1 return pos", "comment_string[i:] if comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) return self.__skip_method(pos)", "self.__tokens[i].get_type() == TokenType.COMMENT def __find_class_name(self, i=0): while self.__tokens[i].get_value() not in", "'@throws': throws.append(value) elif macro == '@return': return_type = value i", "+ \\ ('' if len(params) <= 0 else ' ')", "self.__skip_ws_tokens(pos) while self.__tokens[pos].get_value() != ';': if self.__tokens[pos].get_type() == TokenType.IDENTIFIER and", "i < len(self.__tokens): token = self.__tokens[i] if token.get_value() == 'package':", "self.__tokens[i + 1].get_value() in (';', ','): while pos > 0", "= comment_string = f'{indent}/**\\n' \\ f'{indent} * The {visibility} {field_names}", "while self.__tokens[i].get_value() != ';': if self.__tokens[i + 1].get_value() in (';',", "+= 1 count = 1 pos += 1 while count", "1 return pos def __fix_comment_links(self, comment_token): i = 0 link", "if macro == '@param': params.append(value) elif macro == '@throws': throws.append(value)", "def get_missing(before, after): missing_params = [] for value in after:", "in ('}', ';'): return parameters while self.__tokens[pos].get_value() != '>': if", "def is_snake_upper_case(naming): return naming.isupper() @staticmethod def to_snake_upper_case(naming): return Formatter.to_snake_lower_case(naming).upper() @staticmethod", "i += 1 continue end = comment_string.find('\\n', i) link =", "self.__tokens[pos].get_type() != TokenType.WHITESPACE: pos -= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE:", "def __find_class_name(self, i=0): while self.__tokens[i].get_value() not in ('class', 'interface') and", "= [] for file in self.__files: tokens.append(parse(open(file, 'r').read())) i =", "pos): comment_token = self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) if comment_token is", "= len(naming) - 1 while naming[j] == '_': i -=", "not in ('{', ';'): if self.__tokens[i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i],", "(self.__tokens[type_pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and \\ self.__tokens[type_pos].get_value() not in ('class',", "import TokenType, Token, update_token_value class Formatter: def __init__(self, files): self.__files", "parameters, i = self.__get_field_names(pos) if self.__is_final(pos): for parameter in parameters:", "while self.__tokens[i].get_type() == TokenType.WHITESPACE: i += 1 parameters.append(self.__tokens[i].get_value()) pos +=", "1 elif self.__tokens[pos].get_value() == 'static': i = self.__skip_ws_tokens(pos + 1)", "parameters while self.__tokens[pos].get_value() != '>': if self.__tokens[pos - 1].get_value() in", "-= 1 return_type.append(self.__tokens[pos].get_value()) pos -= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE:", "@staticmethod def is_lower_case(naming): return naming.find('_') == -1 and naming.islower() @staticmethod", "self.__tokens[ pos + 1].get_value() != '.' and self.__tokens[pos].get_value() not in", "= self.__fix_comment_params(comment_token) comment_string = comment_token.get_value() append_string = '' i =", "-= 1 return_type.append(self.__tokens[pos].get_value()) return_type.reverse() return ''.join(return_type) def __fix_comment_params(self, comment_token): i", "- 1 while naming[j] == '_': i -= 1 naming", "comment_string.find('\\n', i) link = comment_string[start:end] elif comment_string[i] == '{': start", "parameters.append(self.__tokens[i].get_value()) pos += 1 return parameters def __get_type_parameter_list(self, pos): parameters", "if comment_token is None: comment_token = Token(None, TokenType.COMMENT) comment_string =", "before: missing_params.append(value) return missing_params def __get_parameter_list(self, pos): parameters = []", "in (';', ','): while pos > 0 and self.__tokens[pos].get_value() not", "return self.__fix_class_body_comments(pos) # Fix comments for methods and fields def", "in (TokenType.IDENTIFIER, TokenType.KEYWORD) and \\ self.__tokens[type_pos].get_value() not in ('class', 'identifier'))", "not in ('class', 'identifier')) or self.__tokens[ type_pos].get_value() == ',': if", "else: self.__fix_comment_links(comment_token) return self.__find_token_after(pos, ';') def __find_visibility(self, pos): pos =", "== '_': i -= 1 naming = naming[:j + 1]", "in self.__tokens: if token.get_value() in self.__to_fix and not token.is_fixed(): update_token_value(self.__file,", "self.__tokens[pos].get_value() != '<': return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value()) pos -=", "1 if self.__tokens[pos].get_type() == TokenType.COMMENT and self.__tokens[pos].get_value().startswith('/**'): return self.__tokens[pos] return", "Formatter.is_snake_upper_case(parameter): self.__to_fix[parameter] = Formatter.to_snake_upper_case(parameter) else: for parameter in parameters: if", "__get_return_type(self, pos): return_type = [] while self.__tokens[pos].get_value() != '(': pos", "= self.__fix_field_comment(pos) else: pos = self.__fix_method_comment(pos) pos += 1 return", "+= 1 i = pos - 1 while self.__tokens[i].get_type() ==", "'=': is_value = True pos -= 1 if not is_value:", "self.__tokens[naming_pos], fixed_value) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[ i].get_value() in", "(')', ','): i = pos while self.__tokens[i].get_type() == TokenType.WHITESPACE: i", "== TokenType.WHITESPACE: naming_pos -= 1 if self.__tokens[naming_pos].get_type() == TokenType.IDENTIFIER: type_pos", "+ 1 pos += 1 count = 1 pos +=", "';'): if self.__tokens[i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i +=", "\"variable\"}{\"s\" if len(field_names) > 0 else \"\"}\\n' \\ f'{indent} */'", "!= '<': if self.__tokens[pos].get_value() == '(': return parameters pos +=", "(self.__tokens[pos].get_value())) pos += 1 return pos def __fix_class_body(self, pos, class_name):", "-= 1 elif self.__tokens[pos].get_value() == 'static': i = self.__skip_ws_tokens(pos +", "self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) def __is_start_comment_exists(self): i = self.__skip_ws_tokens(0) return self.__tokens[i].get_type()", "len(throws_list): append_string += \"\\n\" + \"\\n\".join( [f\"{indent} * @throws {param}\"", "self.__tokens[pos].get_value() != value: pos += 1 return pos def __fix_comment_links(self,", "param in params])) throws = self.__get_throws(pos) if len(throws) > 0:", "self.__to_fix[self.__tokens[pos].get_value()] = Formatter.to_lower_case( (self.__tokens[pos].get_value())) pos += 1 return pos def", "('=', ';'): naming_pos = i - 1 while self.__tokens[naming_pos].get_type() ==", "1].get_value() in ('<', ','): i = pos while self.__tokens[i].get_type() ==", "token.is_fixed(): update_token_value(self.__file, token, self.__to_fix[token.get_value()]) def __fix_comments(self): self.__add_start_comment() i = 0", "def __is_start_comment_exists(self): i = self.__skip_ws_tokens(0) return self.__tokens[i].get_type() == TokenType.COMMENT def", "pos += 1 while self.__tokens[pos].get_value() != ')': if self.__tokens[pos +", "1 continue elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and self.__tokens[ pos", "while self.__tokens[i].get_value() not in ('class', 'interface') and self.__tokens[i - 1].get_value()", "';') def __find_visibility(self, pos): pos = self.__find_token_before(pos, '\\n') while self.__tokens[pos].get_value()", "count -= 1 pos += 1 return pos def __find_doc_comment_before(self,", "self.__tokens[i].get_value() == '}': brace_count -= 1 elif self.__tokens[i].get_value() in ('=',", "= [] while self.__tokens[pos].get_value() != '<': if self.__tokens[pos].get_value() == '(':", "link[pos - 1] == '_'): link = link.replace(name, self.__to_fix[name]) return", "update_token_value(self.__file, comment_token, comment_string) value = new_value if macro == '@param':", "self.__to_fix[parameter] = Formatter.to_camel_lower_case(parameter) pos = i else: self.__fix_method_name(pos, class_name) parameters", "if pos != -1 and not (link[pos - 1].isalpha() or", "to_snake_upper_case(naming): return Formatter.to_snake_lower_case(naming).upper() @staticmethod def remove_underscores_around(naming): i = 0 while", "self.__tokens[i].get_value()) i = self.__fix_class_body(i, self.__tokens[i].get_value()) i += 1 def __fix_package(self,", "parameters = [] while self.__tokens[pos].get_value() != '(': pos += 1", "i != -1: i = comment_string.find('\\n', i) if comment_string.find('\\n', i)", "TokenType.KEYWORD) and \\ self.__tokens[type_pos].get_value() not in ('class', 'identifier')) or self.__tokens[", "i): while self.__tokens[i].get_value() not in (';', '=', '('): if self.__tokens[i].get_value()", "== TokenType.WHITESPACE: pos += 1 return pos @staticmethod def is_lower_case(naming):", "< len(tokens): self.__tokens = tokens[i] self.__file = self.__files[i] self.__fix() self.__fix_comments()", "return self.__skip_method(pos) @staticmethod def get_missing(before, after): missing_params = [] for", "return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value()) pos -= 1 while self.__tokens[pos].get_type()", "i + 1 brace_count = 1 i += 1 while", "False pos += 1 return True def __fix(self): for token", "+= 1 while count != 0: if self.__tokens[pos].get_value() == '{':", "and self.__tokens[pos].get_value() not in (';', '}'): if self.__tokens[pos].get_value() == '=':", "= self.__find_token_before(pos, '\\n') count = 0 while self.__tokens[pos].get_type() == TokenType.WHITESPACE:", "insert_pos = self.__find_token_before(pos, '\\n') self.__tokens.insert(insert_pos, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1,", "def __find_token_after(self, pos, value): while pos < len(self.__tokens) and self.__tokens[pos].get_value()", "+ 1 count += 1 continue elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER,", "in ('class', 'interface') and self.__tokens[i - 1].get_value() != '.': i", "self.__tokens[i].get_type() == TokenType.WHITESPACE: i += 1 parameters.append(self.__tokens[i].get_value()) pos += 1", "end >= 0 else max(comment_string.find(' ', start + 1), comment_string.find('\\n',", "'{': pos += 1 count = 1 pos += 1", "__is_final(self, i): while self.__tokens[i].get_value() not in (';', '=', '('): if", "token.get_value() in self.__to_fix and not token.is_fixed(): update_token_value(self.__file, token, self.__to_fix[token.get_value()]) def", "!= 0: if self.__tokens[i].get_value() == '{': brace_count += 1 elif", "elif self.__tokens[pos].get_value() == '}': count -= 1 elif self.__tokens[pos].get_value() ==", "(TokenType.IDENTIFIER, TokenType.KEYWORD): if self.__is_parameter(pos): parameters, i = self.__get_field_names(pos) if self.__is_final(pos):", "= [ component[0] + component[1:].lower() if component.isupper() else component[0].upper() +", "update_token_value(self.__file, comment_token, comment_string) insert_pos = self.__find_token_before(pos, '\\n') self.__tokens.insert(insert_pos, Token('\\n', TokenType.WHITESPACE))", "naming.islower() @staticmethod def to_snake_lower_case(naming): naming = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', naming) return", "comment def __fix_class_comments(self, pos): comment_token = self.__find_doc_comment_before(pos) if comment_token is", "'protected'): return self.__tokens[pos].get_value() pos += 1 return 'package-private' def __fix_method_comment(self,", "i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1 return", "= [] while self.__tokens[i].get_value() != ';': if self.__tokens[i + 1].get_value()", "self.__tokens[pos].get_value() not in (';', '}'): if self.__tokens[pos].get_value() == '=': is_value", "comment_string.rfind('@throws') if i != -1: i = comment_string.find('\\n', i) if", "if self.__tokens[i].get_value() == ';': return i + 1 brace_count =", "';', '('): if self.__tokens[pos].get_value() in ('private', 'public', 'protected'): return self.__tokens[pos].get_value()", "parameters[self.__tokens[pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[pos], fixed_value) i += 1 return", "while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if self.__tokens[pos].get_value() ==", "update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1 return i def __get_field_names(self,", "!= ';': if self.__tokens[pos].get_type() == TokenType.IDENTIFIER and not Formatter.is_lower_case( self.__tokens[pos].get_value()):", "type_pos -= 1 if (self.__tokens[type_pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and \\", "'\\n') count = 0 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: if self.__tokens[pos].get_value()", "if comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) return self.__skip_method(pos) @staticmethod", "max(comment_string.find(' ', start + 1), comment_string.find('\\n', start + 1)) if", "self.__tokens[i].get_value() != ')': if self.__tokens[i + 1].get_value() in (')', ','):", "1 while self.__tokens[pos].get_type() != TokenType.WHITESPACE: pos -= 1 while self.__tokens[pos].get_type()", "class_name and not Formatter.is_snake_lower_case( self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_snake_lower_case(self.__tokens[i].get_value()) def __get_method_parameters(self,", "self.__files: tokens.append(parse(open(file, 'r').read())) i = 0 while i < len(tokens):", "token = self.__tokens[i] if token.get_value() == 'package': i = self.__fix_package(i)", "= Formatter.to_snake_lower_case(self.__tokens[i].get_value()) def __get_method_parameters(self, i): parameters = dict() while self.__tokens[i].get_value()", "while self.__tokens[i].get_value() != '(': i += 1 while self.__tokens[i].get_value() !=", "', i) if comment_string[i:start] != '@see': i += 1 continue", "def __find_token_before(self, pos, value): while pos > 0 and self.__tokens[pos].get_value()", "self.__to_fix and not token.is_fixed(): update_token_value(self.__file, token, self.__to_fix[token.get_value()]) def __fix_comments(self): self.__add_start_comment()", "'\\n': pos -= 1 while pos > 0 and self.__tokens[pos].get_type()", "lower[0].upper() + lower[1:] @staticmethod def is_snake_lower_case(naming): return naming.islower() @staticmethod def", "re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', naming).lower() @staticmethod def is_snake_upper_case(naming): return naming.isupper() @staticmethod def", "get_missing(before, after): missing_params = [] for value in after: if", "in throws])) return_type = self.__get_return_type(pos) if len(return_type) > 0: all_params.append(f\"{indent}", "pos def __find_token_after(self, pos, value): while pos < len(self.__tokens) and", "0 and self.__tokens[pos].get_value() != value: pos -= 1 return pos", "!= -1 else comment_string.find('*', i) - 1 comment_string = comment_string[:i]", "1 return parameters def __fix_method_body(self, i, method_parameters): params = dict()", "= self.__fix_class_body(i, self.__tokens[i].get_value()) i += 1 def __fix_package(self, pos): pos", "* @param {param}\" for param in params])) throws = self.__get_throws(pos)", "TokenType.WHITESPACE: pos -= 1 if self.__tokens[pos].get_value() == '>': while self.__tokens[pos].get_value()", "+ \\ '\\n'.join(all_params) + \\ ('' if len(params) <= 0", "return parameters def __get_type_parameter_list(self, pos): parameters = [] while self.__tokens[pos].get_value()", "== '}': brace_count -= 1 elif self.__tokens[i].get_value() in ('=', ';'):", "return throws def __get_return_type(self, pos): return_type = [] while self.__tokens[pos].get_value()", "while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 if self.__tokens[i].get_value() !=", "param in Formatter.get_missing(params, params_list)]) i = comment_string.rfind('@param') if i !=", "not in ('}', ';'): return parameters while self.__tokens[pos].get_value() != '>':", "not in ('{', ';'): if self.__tokens[pos].get_value() == 'throws': is_throws =", "';': return i + 1 brace_count = 1 i +=", "self.__to_fix = dict() def process(self): tokens = [] for file", "# Fix class comment def __fix_class_comments(self, pos): comment_token = self.__find_doc_comment_before(pos)", "+= 1 return pos @staticmethod def is_lower_case(naming): return naming.find('_') ==", "not Formatter.is_camel_lower_case(self.__tokens[pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[pos].get_value()) parameters[self.__tokens[pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[pos],", "== '_': i += 1 naming = naming[i:] j =", "for param in params])) throws = self.__get_throws(pos) if len(throws) >", "append_string += \"\\n\" + \"\\n\".join( [f\"{indent} * @throws {param}\" for", "def is_camel_upper_case(naming): return naming.find('_') == -1 and not naming.isupper() and", "self.__tokens[i].get_value() == '{': pos = i + 1 count +=", "TokenType.WHITESPACE: pos -= 1 if not Formatter.is_camel_lower_case(self.__tokens[pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[pos].get_value())", "tokens = [] for file in self.__files: tokens.append(parse(open(file, 'r').read())) i", "all_params = [] if comment_token is None: params = self.__get_parameter_list(pos)", "= comment_string.find(' ', i) macro = comment_string[i:start] end = min(comment_string.find('", "= i while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 field_name", "from javaccflab.lexer import parse from javaccflab.java_token import TokenType, Token, update_token_value", "elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[ i].get_value() in params.keys(): update_token_value(self.__file,", "and self.__tokens[i - 1].get_value() != '.': i += 1 i", "Formatter.to_lower_case( (self.__tokens[pos].get_value())) pos += 1 return pos def __fix_class_body(self, pos,", "1 i = self.__skip_ws_tokens(i + 1) return self.__tokens[i].get_value() # Fix", "True elif is_throws and self.__tokens[pos].get_type() == TokenType.IDENTIFIER: throws.append(self.__tokens[pos].get_value()) pos +=", "'.': i += 1 i = self.__skip_ws_tokens(i + 1) return", "__get_throws(self, pos): throws = [] is_throws = False while self.__tokens[pos].get_value()", "in self.__to_fix and not token.is_fixed(): update_token_value(self.__file, token, self.__to_fix[token.get_value()]) def __fix_comments(self):", "is_camel_lower_case(naming): return naming.find('_') == -1 and not naming.isupper() and not", "!= TokenType.KEYWORD or self.__tokens[i].get_value() not in ('}', ';'): return parameters", "== TokenType.WHITESPACE: pos -= 1 if self.__tokens[pos].get_type() == TokenType.COMMENT and", "== '}': count -= 1 elif self.__tokens[pos].get_value() == 'static': i", "'_'): link = link.replace(name, self.__to_fix[name]) return link def __get_indent(self, pos):", "self.__tokens[pos] return None def __find_token_before(self, pos, value): while pos >", "== TokenType.WHITESPACE: type_pos -= 1 if (self.__tokens[type_pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD)", "!= 0: if self.__tokens[pos].get_value() == '{': count += 1 elif", "'@see': i += 1 continue end = comment_string.find('\\n', i) link", "len(self.__tokens): token = self.__tokens[i] if token.get_value() == 'package': i =", "1)) if end > 0: value = comment_string[start + 1:end]", "append_string + comment_string[i:] append_string = '' if len(throws) < len(throws_list):", "{datetime.date.today().strftime(\"%B %d, %Y\")}\\n' \\ f' */' update_token_value(self.__file, comment_token, comment_string) self.__tokens.insert(0,", "TokenType, Token, update_token_value class Formatter: def __init__(self, files): self.__files =", "= files self.__file = None self.__tokens = [] self.__to_fix =", "i = comment_string.find('\\n', i) if comment_string.find('\\n', i) != -1 else", "self.__is_parameter(pos): parameters, i = self.__get_field_names(pos) if self.__is_final(pos): for parameter in", "comment_string = comment_string = f'{indent}/**\\n' \\ f'{indent} * The {visibility}", "1 elif self.__tokens[pos].get_value() == '}': count -= 1 pos +=", "class comment def __fix_class_comments(self, pos): comment_token = self.__find_doc_comment_before(pos) if comment_token", "comment_string) return self.__skip_method(pos) @staticmethod def get_missing(before, after): missing_params = []", "%d, %Y\")}\\n' \\ f' */' update_token_value(self.__file, comment_token, comment_string) self.__tokens.insert(0, comment_token)", "lower[1:] @staticmethod def is_snake_lower_case(naming): return naming.islower() @staticmethod def to_snake_lower_case(naming): naming", "i = comment_string.rfind('@throws') if i != -1: i = comment_string.find('\\n',", "'(', ')'): return False pos += 1 return True def", "while comment_string[i] != '\\n': i -= 1 comment_string = comment_string[:i]", "len(field_names) > 0 else \"\"}\\n' \\ f'{indent} */' update_token_value(self.__file, comment_token,", "-= 1 if self.__tokens[i].get_value() != class_name and not Formatter.is_snake_lower_case( self.__tokens[i].get_value()):", "self.__tokens[pos].get_value() != ';' and pos < len(self.__tokens): if self.__tokens[pos].get_value() ==", "pos -= 1 return_type.append(self.__tokens[pos].get_value()) pos -= 1 while self.__tokens[pos].get_type() ==", "link is not None: new_link = self.__fix_link(link) comment_string = comment_string.replace(link,", "Formatter.to_camel_upper_case( self.__tokens[i].get_value()) i = self.__fix_class_body(i, self.__tokens[i].get_value()) i += 1 def", "self.__tokens[i].get_type() != TokenType.KEYWORD or self.__tokens[i].get_value() not in ('}', ';'): return", "self.__tokens[pos].get_value() != '{': pos += 1 count = 1 pos", "= Token(None, TokenType.COMMENT) comment_string = f'/**\\n' \\ f' * Implementation", "__fix_method_comment(self, pos): comment_token = self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) all_params =", "count += 1 continue elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD): if", "pos): pos = self.__find_token_before(pos, '\\n') while self.__tokens[pos].get_value() not in ('=',", "and self.__tokens[ i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i +=", "== TokenType.IDENTIFIER and not Formatter.is_lower_case( self.__tokens[pos].get_value()): self.__to_fix[self.__tokens[pos].get_value()] = Formatter.to_lower_case( (self.__tokens[pos].get_value()))", "\\ self.__tokens[type_pos].get_value() not in ('class', 'identifier')) or self.__tokens[ type_pos].get_value() ==", "self.__tokens[pos + 1].get_value() in (')', ','): i = pos while", "i += 1 if comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string)", "min(comment_string.find(' ', start + 1), comment_string.find('\\n', start + 1)) end", "return parameters while self.__tokens[pos].get_value() != '>': if self.__tokens[pos - 1].get_value()", "== TokenType.IDENTIFIER and self.__tokens[ i].get_value() in params.keys(): update_token_value(self.__file, self.__tokens[i], params[self.__tokens[i].get_value()])", "< len(comment_string): if comment_string[i] == '@': start = comment_string.find(' ',", "if self.__is_parameter(pos): parameters, i = self.__get_field_names(pos) if self.__is_final(pos): for parameter", "parameter in parameters: if not Formatter.is_camel_lower_case(parameter): self.__to_fix[parameter] = Formatter.to_camel_lower_case(parameter) pos", "= link.find(name) if pos != -1 and not (link[pos -", "1 return 'package-private' def __fix_method_comment(self, pos): comment_token = self.__find_doc_comment_before(pos) indent", "i = pos - 1 while self.__tokens[i].get_type() == TokenType.WHITESPACE: i", "if len(return_type) == '': append_string += \"\\n\" + f\"\\n{indent} *", "comment_string.find('\\n', i) if comment_string.find('\\n', i) != -1 else comment_string.find('*', i)", "from javaccflab.java_token import TokenType, Token, update_token_value class Formatter: def __init__(self,", "-= 1 if (self.__tokens[type_pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and \\ self.__tokens[type_pos].get_value()", "== TokenType.COMMENT def __find_class_name(self, i=0): while self.__tokens[i].get_value() not in ('class',", "== -1 and naming.islower() @staticmethod def to_lower_case(naming): return ''.join([component.lower() for", "len(params) <= 0 else ' ') + \\ f'\\n{indent} */'", "comment_token): i = 0 params = [] throws = []", "= i + 1 count += 1 continue elif self.__tokens[pos].get_type()", "pos += 1 count = 1 pos += 1 while", "params = [] while self.__tokens[i].get_value() != ';': if self.__tokens[i +", "'\\n') while self.__tokens[pos].get_value() not in ('=', ';', '('): if self.__tokens[pos].get_value()", "self.__fix_class_comments(i) i += 1 i += 1 # Fix start", "None: comment_token = Token(None, TokenType.COMMENT) comment_string = f'/**\\n' \\ f'", "= value i += 1 return params, throws, return_type def", "'interface', '(', ')'): return False pos += 1 return True", "pos): while self.__tokens[pos].get_value() != '{': if self.__tokens[pos].get_value() == ';': return", "= '' if len(throws) < len(throws_list): append_string += \"\\n\" +", "end def __is_final(self, i): while self.__tokens[i].get_value() not in (';', '=',", "', start + 1), comment_string.find('\\n', start + 1)) end =", "return_type = value i += 1 return params, throws, return_type", "1 pos -= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -=", "value = comment_string[start + 1:end] new_value = self.__fix_link(value) if value", "Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token) return self.__find_token_after(pos,", "fixed_value = Formatter.to_camel_lower_case(self.__tokens[pos].get_value()) parameters[self.__tokens[pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[pos], fixed_value) i", "append_string = '' if len(throws) < len(throws_list): append_string += \"\\n\"", "def __fix(self): for token in self.__tokens: if token.get_value() in self.__to_fix", "self.__tokens[naming_pos].get_type() == TokenType.IDENTIFIER: type_pos = naming_pos - 1 while self.__tokens[type_pos].get_type()", "if self.__tokens[i + 1].get_value() in (';', '=', ','): pos =", "+ 1, comment_token) else: self.__fix_comment_links(comment_token) return self.__find_token_after(pos, ';') def __find_visibility(self,", "f'{indent} */' update_token_value(self.__file, comment_token, comment_string) insert_pos = self.__find_token_before(pos, '\\n') self.__tokens.insert(insert_pos,", "pos = i + 1 count += 1 continue elif", "count += 1 elif self.__tokens[pos].get_value() == '}': count -= 1", "i = comment_string.rfind('@param') if i != -1: i = comment_string.find('\\n',", "new_value if macro == '@param': params.append(value) elif macro == '@throws':", "elif self.__tokens[pos].get_value() == 'static': i = self.__skip_ws_tokens(pos + 1) if", "None self.__tokens = [] self.__to_fix = dict() def process(self): tokens", "after: if value not in before: missing_params.append(value) return missing_params def", "Formatter.is_camel_lower_case(self.__tokens[pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[pos].get_value()) parameters[self.__tokens[pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[pos], fixed_value)", "= f'{indent}/**\\n' + \\ '\\n'.join(all_params) + \\ ('' if len(params)", "params = dict() while self.__tokens[i].get_value() not in ('{', ';'): if", "in naming.split('_')]) @staticmethod def is_camel_lower_case(naming): return naming.find('_') == -1 and", "* @param {param}\" for param in Formatter.get_missing(params, params_list)]) i =", "+ 1 brace_count = 1 i += 1 while brace_count", "while self.__tokens[pos].get_value() != '(': pos += 1 pos -= 1", "@return {return_type_value}\" else: i = comment_string.rfind('@return') while comment_string[i] != '\\n':", "comment_string[i:start] end = min(comment_string.find(' ', start + 1), comment_string.find('\\n', start", "', '.join(self.__get_field_names(pos)[0]) visibility = self.__find_visibility(pos) comment_token = Token(None, TokenType.COMMENT) comment_string", "\\ '\\n'.join(all_params) + \\ ('' if len(params) <= 0 else", "tokens[i] = self.__tokens i += 1 i = 0 while", "+= 1 return i def __get_field_names(self, i): params = []", "return_type = self.__get_return_type(pos) if len(return_type) > 0: all_params.append(f\"{indent} * @return", "1 return i def __get_field_names(self, i): params = [] while", "('<', ','): i = pos while self.__tokens[i].get_type() == TokenType.WHITESPACE: i", "pos): while self.__tokens[pos].get_value() != ';' and pos < len(self.__tokens): if", "not Formatter.is_camel_lower_case(self.__tokens[naming_pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[naming_pos].get_value()) params[self.__tokens[naming_pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[naming_pos],", "True i += 1 return False def __is_parameter(self, pos): while", "Token(None, TokenType.COMMENT) comment_string = comment_string = f'{indent}/**\\n' \\ f'{indent} *", "None: params = self.__get_parameter_list(pos) params.extend(self.__get_type_parameter_list(pos)) if len(params) > 0: all_params.append(\"\\n\".join([f\"{indent}", "def is_camel_lower_case(naming): return naming.find('_') == -1 and not naming.isupper() and", "> 0 and self.__tokens[pos].get_value() not in (';', '}'): if self.__tokens[pos].get_value()", "return_type_value = self.__get_return_type(pos) params, throws, return_type = self.__fix_comment_params(comment_token) comment_string =", "while self.__tokens[i].get_value() not in (';', '=', '('): if self.__tokens[i].get_value() ==", "in (TokenType.IDENTIFIER, TokenType.KEYWORD): if self.__is_parameter(pos): parameters, i = self.__get_field_names(pos) if", "== 'package': i = self.__fix_package(i) elif token.get_value() in ('class', 'interface')", "(link[pos - 1].isalpha() or link[ pos - 1].isdigit() or link[pos", "comment_string.replace(value, new_value) update_token_value(self.__file, comment_token, comment_string) value = new_value if macro", "@return {self.__get_return_type(pos)}\") comment_token = Token(None, TokenType.COMMENT) comment_string = f'{indent}/**\\n' +", "return naming.find('_') == -1 and naming.islower() @staticmethod def to_lower_case(naming): return", "in ('private', 'public', 'protected'): return self.__tokens[pos].get_value() pos += 1 return", "None: new_link = self.__fix_link(link) comment_string = comment_string.replace(link, new_link) link =", "self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if self.__tokens[pos].get_type() == TokenType.COMMENT", "0 while i < len(self.__tokens): if self.__tokens[i].get_value() in ('class', 'interface'):", "= comment_string.find('\\n', i) if len(return_type) == '': append_string += \"\\n\"", "= [] for value in after: if value not in", "')': if self.__tokens[i + 1].get_value() in (')', ','): pos =", "'}': count -= 1 elif self.__tokens[pos].get_value() == 'static': i =", "fixed_value update_token_value(self.__file, self.__tokens[pos], fixed_value) i += 1 return parameters def", "return i + 1 brace_count = 1 i += 1", "'{': count += 1 elif self.__tokens[pos].get_value() == '}': count -=", "= self.__fix_package(i) elif token.get_value() in ('class', 'interface') and self.__tokens[i -", "__skip_method(self, pos): while self.__tokens[pos].get_value() != '{': if self.__tokens[pos].get_value() == ';':", "value != new_value: comment_string = comment_string.replace(value, new_value) update_token_value(self.__file, comment_token, comment_string)", "type_pos].get_value() == ',': if not Formatter.is_camel_lower_case(self.__tokens[naming_pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[naming_pos].get_value()) params[self.__tokens[naming_pos].get_value()]", "= naming_pos - 1 while self.__tokens[type_pos].get_type() == TokenType.WHITESPACE: type_pos -=", "= new_value if macro == '@param': params.append(value) elif macro ==", "pos + 1 pos += 1 count = 1 pos", "= 0 while i < len(self.__tokens): token = self.__tokens[i] if", "for component in naming.split('_')]) @staticmethod def is_camel_lower_case(naming): return naming.find('_') ==", "1 i += 1 # Fix start comment def __add_start_comment(self):", "'}'): if self.__tokens[pos].get_value() == '=': is_value = True pos -=", "@param {param}\" for param in params])) throws = self.__get_throws(pos) if", "= link.replace(name, self.__to_fix[name]) return link def __get_indent(self, pos): pos =", "'\\n'.join(all_params) + \\ ('' if len(params) <= 0 else '", "i = self.__skip_ws_tokens(i + 1) return self.__tokens[i].get_value() # Fix class", "1].get_value() in (';', ','): while pos > 0 and self.__tokens[pos].get_value()", "('class', 'interface'): i = self.__fix_class_comments(i) i += 1 i +=", "def to_snake_upper_case(naming): return Formatter.to_snake_lower_case(naming).upper() @staticmethod def remove_underscores_around(naming): i = 0", "'interface'): if self.__is_parameter(pos): pos = self.__fix_field_comment(pos) else: pos = self.__fix_method_comment(pos)", "TokenType.COMMENT) comment_string = f'/*\\n' \\ f' * {self.__find_class_name()}\\n' \\ f'", "comment_string.find('\\n', start + 1)) if end > 0: value =", "TokenType.WHITESPACE)) def __is_start_comment_exists(self): i = self.__skip_ws_tokens(0) return self.__tokens[i].get_type() == TokenType.COMMENT", "!= '.': i += 1 i = self.__skip_ws_tokens(i + 1)", "comment_string = f'/*\\n' \\ f' * {self.__find_class_name()}\\n' \\ f' *\\n'", "self.__tokens[pos], fixed_value) i += 1 return parameters def __fix_method_body(self, i,", "parameters = self.__get_method_parameters(pos) pos = self.__fix_method_body(pos, parameters) pos += 1", "naming.find('_') == -1 and not naming.isupper() and naming[0].isupper() @staticmethod def", "';'): i += 1 i -= 1 while self.__tokens[i].get_type() ==", "i += 1 i -= 1 while self.__tokens[i].get_type() == TokenType.WHITESPACE:", "else: self.__fix_method_name(pos, class_name) parameters = self.__get_method_parameters(pos) pos = self.__fix_method_body(pos, parameters)", "- 1].isalpha() or link[ pos - 1].isdigit() or link[pos -", "pos while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 parameters.append(self.__tokens[i].get_value()) pos", "= comment_string.find(' ', i) end = comment_string.find('}', i) link =", "def __get_throws(self, pos): throws = [] is_throws = False while", "new_value: comment_string = comment_string.replace(value, new_value) update_token_value(self.__file, comment_token, comment_string) value =", "comment_token = self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) if comment_token is None:", "start = comment_string.find(' ', i) macro = comment_string[i:start] end =", "- 1].isdigit() or link[pos - 1] == '_'): link =", "naming) return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', naming).lower() @staticmethod def is_snake_upper_case(naming): return naming.isupper()", "pos += 1 return throws def __get_return_type(self, pos): return_type =", "= None comment_string = comment_token.get_value() while i < len(comment_string): if", "len(self.__tokens): if self.__tokens[pos].get_value() == '=': return True elif self.__tokens[pos].get_value() in", "__skip_ws_tokens(self, pos): while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos += 1 return", "','): pos = i while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -=", "process(self): tokens = [] for file in self.__files: tokens.append(parse(open(file, 'r').read()))", "class Formatter: def __init__(self, files): self.__files = files self.__file =", "1 i += 1 while brace_count != 0: if self.__tokens[i].get_value()", "') + \\ f'\\n{indent} */' update_token_value(self.__file, comment_token, comment_string) insert_pos =", "throws, return_type = self.__fix_comment_params(comment_token) comment_string = comment_token.get_value() append_string = ''", "self.__to_fix.keys(): pos = link.find(name) if pos != -1 and not", "comment_string[i:] append_string = '' if len(throws) < len(throws_list): append_string +=", "+= \"\\n\" + f\"\\n{indent} * @return {return_type_value}\" else: i =", "'}': brace_count -= 1 elif self.__tokens[i].get_value() in ('=', ';'): naming_pos", "';': return pos + 1 pos += 1 count =", "== '@throws': throws.append(value) elif macro == '@return': return_type = value", "dict() def process(self): tokens = [] for file in self.__files:", "in ('{', ';'): if self.__tokens[i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()])", "in (';', '}'): if self.__tokens[pos].get_value() == '=': is_value = True", "TokenType.COMMENT def __find_class_name(self, i=0): while self.__tokens[i].get_value() not in ('class', 'interface')", "value in after: if value not in before: missing_params.append(value) return", "'}': count -= 1 pos += 1 return pos def", "+= 1 return parameters def __get_type_parameter_list(self, pos): parameters = []", "i < len(comment_string): if comment_string[i] == '@': start = comment_string.find('", "parameters.append(self.__tokens[i].get_value()) pos += 1 return parameters def __get_throws(self, pos): throws", "def __fix_link(self, link): for name in self.__to_fix.keys(): pos = link.find(name)", "1 return parameters def __get_type_parameter_list(self, pos): parameters = [] while", "- 1 while self.__tokens[type_pos].get_type() == TokenType.WHITESPACE: type_pos -= 1 if", "Formatter.is_lower_case( self.__tokens[pos].get_value()): self.__to_fix[self.__tokens[pos].get_value()] = Formatter.to_lower_case( (self.__tokens[pos].get_value())) pos += 1 return", "= dict() def process(self): tokens = [] for file in", "end = end if end >= 0 else max(comment_string.find(' ',", "def __get_type_parameter_list(self, pos): parameters = [] while self.__tokens[pos].get_value() != '<':", "return pos def __find_token_after(self, pos, value): while pos < len(self.__tokens)", "def __get_indent(self, pos): pos = self.__find_token_before(pos, '\\n') count = 0", "i) != -1 else comment_string.find('*', i) - 1 comment_string =", "fixed_value update_token_value(self.__file, self.__tokens[naming_pos], fixed_value) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[", "[] throws = [] return_type = '' comment_string = comment_token.get_value()", "\"\\n\" + f\"\\n{indent} * @return {return_type_value}\" else: i = comment_string.rfind('@return')", "component[0].upper() + component[1:] for component in naming.split('_')] return components[0][0].lower() +", "+ 1].get_value() in (')', ','): pos = i while self.__tokens[pos].get_type()", "'=', '('): if self.__tokens[i].get_value() == 'final': return True i +=", "'interface') and self.__tokens[i - 1].get_value() != '.': i = self.__skip_ws_tokens(i", "components[0][1:] + ''.join(components[1:]) @staticmethod def is_camel_upper_case(naming): return naming.find('_') == -1", "end = min(comment_string.find(' ', start + 1), comment_string.find('\\n', start +", "self.__fix_class_body(i, self.__tokens[i].get_value()) i += 1 def __fix_package(self, pos): pos =", "parameters) pos += 1 return pos def __fix_method_name(self, i, class_name):", "in ('class', 'interface', '(', ')'): return False pos += 1", "= self.__files[i] self.__fix() self.__fix_comments() tokens[i] = self.__tokens i += 1", "('private', 'public', 'protected'): return self.__tokens[pos].get_value() pos += 1 return 'package-private'", "\\ f'{indent} * The {visibility} {field_names} {\"constant\" if self.__is_final(pos) else", "@staticmethod def get_missing(before, after): missing_params = [] for value in", "= self.__fix_link(link) comment_string = comment_string.replace(link, new_link) link = None i", "- 1].get_value() != '.': i = self.__skip_ws_tokens(i + 1) if", "naming_pos = i - 1 while self.__tokens[naming_pos].get_type() == TokenType.WHITESPACE: naming_pos", "('}', ';'): return parameters while self.__tokens[pos].get_value() != '>': if self.__tokens[pos", "''.join(return_type) def __fix_comment_params(self, comment_token): i = 0 params = []", "',': if not Formatter.is_camel_lower_case(self.__tokens[naming_pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[naming_pos].get_value()) params[self.__tokens[naming_pos].get_value()] = fixed_value", "{param}\" for param in Formatter.get_missing(params, params_list)]) i = comment_string.rfind('@param') if", "naming[0].isupper() @staticmethod def to_camel_lower_case(naming): naming = Formatter.remove_underscores_around(naming) components = [", "self.__fix_link(link) comment_string = comment_string.replace(link, new_link) link = None i +=", "self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token) params_list = self.__get_parameter_list(pos) params_list.extend(self.__get_type_parameter_list(pos))", "Formatter.to_camel_lower_case(self.__tokens[pos].get_value()) parameters[self.__tokens[pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[pos], fixed_value) i += 1", "1 if (self.__tokens[type_pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and \\ self.__tokens[type_pos].get_value() not", "+ 1) return self.__tokens[i].get_value() # Fix class comment def __fix_class_comments(self,", "def to_camel_lower_case(naming): naming = Formatter.remove_underscores_around(naming) components = [ component[0] +", "1) return self.__tokens[i].get_value() # Fix class comment def __fix_class_comments(self, pos):", "is_value = True pos -= 1 if not is_value: params.append(field_name)", "not Formatter.is_snake_upper_case(parameter): self.__to_fix[parameter] = Formatter.to_snake_upper_case(parameter) else: for parameter in parameters:", "self.__tokens[pos].get_value() == '>': while self.__tokens[pos].get_value() != '<': return_type.append(self.__tokens[pos].get_value()) pos -=", "* {self.__find_class_name()}\\n' \\ f' *\\n' \\ f' * {datetime.date.today().strftime(\"%B %d,", "'@return': return_type = value i += 1 return params, throws,", "while self.__tokens[i].get_value() not in ('{', ';'): if self.__tokens[i].get_value() in method_parameters.keys():", "__fix_field_comment(self, pos): comment_token = self.__find_doc_comment_before(pos) indent = self.__get_indent(pos) if comment_token", "self.__get_throws(pos) return_type_value = self.__get_return_type(pos) params, throws, return_type = self.__fix_comment_params(comment_token) comment_string", "and self.__tokens[ pos + 1].get_value() != '.' and self.__tokens[pos].get_value() not", "naming = naming[i:] j = len(naming) - 1 while naming[j]", "component[1:] for component in naming.split('_')] return components[0][0].lower() + components[0][1:] +", "pos def __fix_comment_links(self, comment_token): i = 0 link = None", "self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos += 1 return pos @staticmethod def", "pos += 1 while count != 0: if self.__tokens[pos].get_value() ==", "and not Formatter.is_lower_case( self.__tokens[pos].get_value()): self.__to_fix[self.__tokens[pos].get_value()] = Formatter.to_lower_case( (self.__tokens[pos].get_value())) pos +=", "= comment_string[:i] + append_string + comment_string[i:] append_string = '' if", "for parameter in parameters: if not Formatter.is_snake_upper_case(parameter): self.__to_fix[parameter] = Formatter.to_snake_upper_case(parameter)", "= '' i = 0 if len(params) < len(params_list): append_string", "self.__fix_comments() tokens[i] = self.__tokens i += 1 return tokens def", "TokenType.IDENTIFIER and self.__tokens[ i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i", "1 while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 if self.__tokens[i].get_type()", "i = 0 while naming[i] == '_': i += 1", "== 'throws': is_throws = True elif is_throws and self.__tokens[pos].get_type() ==", "= f'/**\\n' \\ f' * Implementation of {self.__find_class_name(pos)}\\n' \\ f'", "'>': if self.__tokens[pos - 1].get_value() in ('<', ','): i =", "1].get_value() in (')', ','): pos = i while self.__tokens[pos].get_type() ==", "* @return {return_type_value}\" else: i = comment_string.rfind('@return') while comment_string[i] !=", "1 i = pos - 1 while self.__tokens[i].get_type() == TokenType.WHITESPACE:", "@staticmethod def remove_underscores_around(naming): i = 0 while naming[i] == '_':", "TokenType.IDENTIFIER: type_pos = naming_pos - 1 while self.__tokens[type_pos].get_type() == TokenType.WHITESPACE:", "self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_snake_lower_case(self.__tokens[i].get_value()) def __get_method_parameters(self, i): parameters = dict() while", "''.join(components[1:]) @staticmethod def is_camel_upper_case(naming): return naming.find('_') == -1 and not", "< len(self.__tokens): if self.__tokens[pos].get_value() == '=': return True elif self.__tokens[pos].get_value()", "1 i -= 1 while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -=", "to_camel_lower_case(naming): naming = Formatter.remove_underscores_around(naming) components = [ component[0] + component[1:].lower()", "0 and self.__tokens[pos].get_value() not in (';', '}'): if self.__tokens[pos].get_value() ==", "new_link = self.__fix_link(link) comment_string = comment_string.replace(link, new_link) link = None", "1 if self.__tokens[naming_pos].get_type() == TokenType.IDENTIFIER: type_pos = naming_pos - 1", "!= ';' and pos < len(self.__tokens): if self.__tokens[pos].get_value() == '=':", "end if end >= 0 else max(comment_string.find(' ', start +", "__fix_comment_links(self, comment_token): i = 0 link = None comment_string =", "'('): if self.__tokens[pos].get_value() in ('private', 'public', 'protected'): return self.__tokens[pos].get_value() pos", "tokens def __find_to_fix(self): i = 0 while i < len(self.__tokens):", "return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value()) return_type.reverse() return ''.join(return_type) def __fix_comment_params(self,", "TokenType.WHITESPACE: pos -= 1 while self.__tokens[pos].get_type() != TokenType.WHITESPACE: pos -=", "comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) return self.__skip_method(pos) @staticmethod def get_missing(before, after):", "and naming.islower() @staticmethod def to_lower_case(naming): return ''.join([component.lower() for component in", "-= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 while", "TokenType.WHITESPACE)) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) def __is_start_comment_exists(self): i = self.__skip_ws_tokens(0) return", "== TokenType.IDENTIFIER: throws.append(self.__tokens[pos].get_value()) pos += 1 return throws def __get_return_type(self,", "def __fix_method_name(self, i, class_name): while self.__tokens[i].get_value() not in ('(', ';'):", "= i else: self.__fix_method_name(pos, class_name) parameters = self.__get_method_parameters(pos) pos =", "naming.find('_') == -1 and naming.islower() @staticmethod def to_lower_case(naming): return ''.join([component.lower()", "+= 1 i = self.__skip_ws_tokens(i + 1) return self.__tokens[i].get_value() #", "i = 0 while i < len(tokens): self.__tokens = tokens[i]", "if not Formatter.is_camel_lower_case(parameter): self.__to_fix[parameter] = Formatter.to_camel_lower_case(parameter) pos = i else:", "import parse from javaccflab.java_token import TokenType, Token, update_token_value class Formatter:", "!= value: pos -= 1 return pos def __find_token_after(self, pos,", "'_': i -= 1 naming = naming[:j + 1] return", "self.__find_token_after(pos, ';') def __find_visibility(self, pos): pos = self.__find_token_before(pos, '\\n') while", "== TokenType.WHITESPACE: return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value()) return_type.reverse() return ''.join(return_type)", "in parameters: if not Formatter.is_snake_upper_case(parameter): self.__to_fix[parameter] = Formatter.to_snake_upper_case(parameter) else: for", "Fix comments for methods and fields def __fix_class_body_comments(self, pos): while", "';'): naming_pos = i - 1 while self.__tokens[naming_pos].get_type() == TokenType.WHITESPACE:", "def __find_visibility(self, pos): pos = self.__find_token_before(pos, '\\n') while self.__tokens[pos].get_value() not", "@staticmethod def to_snake_upper_case(naming): return Formatter.to_snake_lower_case(naming).upper() @staticmethod def remove_underscores_around(naming): i =", "1 return ' ' * count def __skip_ws_tokens(self, pos): while", "!= '.': i = self.__skip_ws_tokens(i + 1) if not Formatter.is_camel_upper_case(self.__tokens[i].get_value()):", "self.__find_token_before(pos, '\\n') count = 0 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: if", "else ' ') + \\ f'\\n{indent} */' update_token_value(self.__file, comment_token, comment_string)", "self.__file = None self.__tokens = [] self.__to_fix = dict() def", "else comment_string.find('*', i) - 1 comment_string = comment_string[:i] + append_string", "parameters def __get_type_parameter_list(self, pos): parameters = [] while self.__tokens[pos].get_value() !=", "('{', ';'): if self.__tokens[i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i", "for param in Formatter.get_missing(throws, throws_list)]) i = comment_string.rfind('@throws') if i", "'{': start = comment_string.find(' ', i) end = comment_string.find('}', i)", "params, throws, return_type = self.__fix_comment_params(comment_token) comment_string = comment_token.get_value() append_string =", "return pos def __fix_method_name(self, i, class_name): while self.__tokens[i].get_value() not in", "count -= 1 elif self.__tokens[pos].get_value() == 'static': i = self.__skip_ws_tokens(pos", "token.get_value() == 'package': i = self.__fix_package(i) elif token.get_value() in ('class',", "link.find(name) if pos != -1 and not (link[pos - 1].isalpha()", "end = i return params, end def __is_final(self, i): while", "1 brace_count = 1 i += 1 while brace_count !=", "is_throws = False while self.__tokens[pos].get_value() not in ('{', ';'): if", "i += 1 return params, throws, return_type def __skip_method(self, pos):", "while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1 if self.__tokens[i].get_type() !=", "while self.__tokens[i].get_value() != ')': if self.__tokens[i + 1].get_value() in (')',", "= self.__skip_ws_tokens(i + 1) return self.__tokens[i].get_value() # Fix class comment", "* Implementation of {self.__find_class_name(pos)}\\n' \\ f' */' update_token_value(self.__file, comment_token, comment_string)", "';': if self.__tokens[pos].get_type() == TokenType.IDENTIFIER and not Formatter.is_lower_case( self.__tokens[pos].get_value()): self.__to_fix[self.__tokens[pos].get_value()]", "while self.__tokens[naming_pos].get_type() == TokenType.WHITESPACE: naming_pos -= 1 if self.__tokens[naming_pos].get_type() ==", "while self.__tokens[pos].get_type() != TokenType.WHITESPACE: pos -= 1 while self.__tokens[pos].get_type() ==", "is_value = False if self.__tokens[i + 1].get_value() in (';', ','):", "__fix_link(self, link): for name in self.__to_fix.keys(): pos = link.find(name) if", "and self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if self.__tokens[pos].get_type() ==", "append_string + comment_string[i:] append_string = '' i = comment_string.find('\\n', i)", "if self.__tokens[pos].get_value() == '{': count += 1 elif self.__tokens[pos].get_value() ==", "comment_token, comment_string) insert_pos = self.__find_token_before(pos, '\\n') self.__tokens.insert(insert_pos, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(insert_pos", "1 while brace_count != 0: if self.__tokens[i].get_value() == '{': brace_count", "= self.__find_token_before(pos, '\\n') self.__tokens.insert(insert_pos, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1, comment_token)", "self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_camel_upper_case( self.__tokens[i].get_value()) i = self.__fix_class_body(i, self.__tokens[i].get_value()) i +=", "i = self.__skip_ws_tokens(i + 1) if not Formatter.is_camel_upper_case(self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] =", "throws = [] is_throws = False while self.__tokens[pos].get_value() not in", "not is_value: params.append(field_name) i += 1 end = i return", "while self.__tokens[pos].get_value() != '<': if self.__tokens[pos].get_value() == '(': return parameters", "__find_doc_comment_before(self, pos): while self.__tokens[pos].get_value() != '\\n': pos -= 1 while", "comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) def __fix_link(self, link): for name in", "= min(comment_string.find(' ', start + 1), comment_string.find('\\n', start + 1))", "to_lower_case(naming): return ''.join([component.lower() for component in naming.split('_')]) @staticmethod def is_camel_lower_case(naming):", "and not naming.isupper() and naming[0].isupper() @staticmethod def to_camel_upper_case(naming): lower =", "comment_string[:i] + append_string + comment_string[i:] if comment_string != comment_token.get_value(): update_token_value(self.__file,", "1 return False def __is_parameter(self, pos): while self.__tokens[pos].get_value() != ';'", "params[self.__tokens[naming_pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[naming_pos], fixed_value) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER", "update_token_value(self.__file, self.__tokens[naming_pos], fixed_value) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[ i].get_value()", "= [] self.__to_fix = dict() def process(self): tokens = []", "TokenType.WHITESPACE: pos += 1 return pos @staticmethod def is_lower_case(naming): return", "-1 and not (link[pos - 1].isalpha() or link[ pos -", "f' * {self.__find_class_name()}\\n' \\ f' *\\n' \\ f' * {datetime.date.today().strftime(\"%B", "import datetime from javaccflab.lexer import parse from javaccflab.java_token import TokenType,", "1 parameters.append(self.__tokens[i].get_value()) pos += 1 return parameters def __get_type_parameter_list(self, pos):", "0 while i < len(self.__tokens): token = self.__tokens[i] if token.get_value()", "elif self.__tokens[pos].get_value() == '}': count -= 1 pos += 1", "-= 1 pos += 1 return pos def __find_doc_comment_before(self, pos):", "i) link = comment_string[start:end] elif comment_string[i] == '{': start =", "throws.append(self.__tokens[pos].get_value()) pos += 1 return throws def __get_return_type(self, pos): return_type", "self.__tokens.insert(0, comment_token) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) def __is_start_comment_exists(self):", "continue elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and self.__tokens[ pos +", "@throws {param}\" for param in throws])) return_type = self.__get_return_type(pos) if", "= self.__skip_ws_tokens(i + 1) if not Formatter.is_camel_upper_case(self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_camel_upper_case(", "self.__is_start_comment_exists(): comment_token = Token(None, TokenType.COMMENT) comment_string = f'/*\\n' \\ f'", "@staticmethod def to_camel_lower_case(naming): naming = Formatter.remove_underscores_around(naming) components = [ component[0]", "'{': pos = i + 1 count += 1 continue", "for param in Formatter.get_missing(params, params_list)]) i = comment_string.rfind('@param') if i", "not self.__is_start_comment_exists(): comment_token = Token(None, TokenType.COMMENT) comment_string = f'/*\\n' \\", "in (TokenType.IDENTIFIER, TokenType.KEYWORD) and self.__tokens[ pos + 1].get_value() != '.'", ">= 0 else max(comment_string.find(' ', start + 1), comment_string.find('\\n', start", "self.__tokens[ i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1", "pos += 1 return pos @staticmethod def is_lower_case(naming): return naming.find('_')", "if self.__tokens[pos].get_value() == '=': is_value = True pos -= 1", "= self.__skip_ws_tokens(0) return self.__tokens[i].get_type() == TokenType.COMMENT def __find_class_name(self, i=0): while", "1 end = i return params, end def __is_final(self, i):", "self.__tokens[pos].get_type() == TokenType.COMMENT and self.__tokens[pos].get_value().startswith('/**'): return self.__tokens[pos] return None def", "self.__tokens = [] self.__to_fix = dict() def process(self): tokens =", "return_type = '' comment_string = comment_token.get_value() while i < len(comment_string):", "in (')', ','): pos = i while self.__tokens[pos].get_type() == TokenType.WHITESPACE:", "i += 1 parameters.append(self.__tokens[i].get_value()) pos += 1 return parameters def", "pos): pos = self.__find_token_before(pos, '\\n') count = 0 while self.__tokens[pos].get_type()", "fields def __fix_class_body_comments(self, pos): while self.__tokens[pos].get_value() != '{': pos +=", "-1 else comment_string.find('*', i) - 1 comment_string = comment_string[:i] +", "for name in self.__to_fix.keys(): pos = link.find(name) if pos !=", "self.__fix_link(value) if value != new_value: comment_string = comment_string.replace(value, new_value) update_token_value(self.__file,", "== '@return': return_type = value i += 1 return params,", "or self.__tokens[i].get_value() not in ('}', ';'): return parameters while self.__tokens[pos].get_value()", "1 return tokens def __find_to_fix(self): i = 0 while i", "0: if self.__tokens[i].get_value() == '{': brace_count += 1 elif self.__tokens[i].get_value()", "False if self.__tokens[i + 1].get_value() in (';', ','): while pos", "r'\\1_\\2', naming).lower() @staticmethod def is_snake_upper_case(naming): return naming.isupper() @staticmethod def to_snake_upper_case(naming):", "i = pos while self.__tokens[i].get_type() == TokenType.WHITESPACE: i += 1", "self.__tokens[pos].get_value() != value: pos -= 1 return pos def __find_token_after(self,", "if value not in before: missing_params.append(value) return missing_params def __get_parameter_list(self,", "i) - 1 comment_string = comment_string[:i] + append_string + comment_string[i:]", "= self.__fix_method_body(pos, parameters) pos += 1 return pos def __fix_method_name(self,", "comment_token, comment_string) return self.__skip_method(pos) @staticmethod def get_missing(before, after): missing_params =", "while brace_count != 0: if self.__tokens[i].get_value() == '{': brace_count +=", "return_type.reverse() return ''.join(return_type) def __fix_comment_params(self, comment_token): i = 0 params", "__get_method_parameters(self, i): parameters = dict() while self.__tokens[i].get_value() != '(': i", "0: if self.__tokens[pos].get_value() == '{': count += 1 elif self.__tokens[pos].get_value()", "not naming.isupper() and naming[0].isupper() @staticmethod def to_camel_upper_case(naming): lower = Formatter.to_camel_lower_case(naming)", "= comment_string.rfind('@param') if i != -1: i = comment_string.find('\\n', i)", "pos): pos = self.__skip_ws_tokens(pos) while self.__tokens[pos].get_value() != ';': if self.__tokens[pos].get_type()", "return pos + 1 pos += 1 count = 1", "self.__tokens[type_pos].get_type() == TokenType.WHITESPACE: type_pos -= 1 if (self.__tokens[type_pos].get_type() in (TokenType.IDENTIFIER,", "= self.__get_indent(pos) all_params = [] if comment_token is None: params", "0: all_params.append(\"\\n\".join([f\"{indent} * @throws {param}\" for param in throws])) return_type", "= True elif is_throws and self.__tokens[pos].get_type() == TokenType.IDENTIFIER: throws.append(self.__tokens[pos].get_value()) pos", "and not naming.isupper() and not naming[0].isupper() @staticmethod def to_camel_lower_case(naming): naming", "i += 1 def __fix_package(self, pos): pos = self.__skip_ws_tokens(pos) while", "1].get_value() in (')', ','): i = pos while self.__tokens[i].get_type() ==", "return self.__find_token_after(pos, ';') def __find_visibility(self, pos): pos = self.__find_token_before(pos, '\\n')", "i -= 1 if self.__tokens[i].get_type() != TokenType.KEYWORD or self.__tokens[i].get_value() not", "self.__tokens[i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()]) i += 1 if", "self.__get_indent(pos) if comment_token is None: field_names = ', '.join(self.__get_field_names(pos)[0]) visibility", "TokenType.WHITESPACE: return_type.append(self.__tokens[pos].get_value()) pos -= 1 return_type.append(self.__tokens[pos].get_value()) return_type.reverse() return ''.join(return_type) def", "pos): parameters = [] while self.__tokens[pos].get_value() != '(': pos +=", "self.__find_to_fix() tokens[i] = self.__tokens i += 1 i = 0", "+ append_string + comment_string[i:] append_string = '' i = comment_string.find('\\n',", "pos += 1 return parameters def __get_throws(self, pos): throws =", "params, end def __is_final(self, i): while self.__tokens[i].get_value() not in (';',", "in ('class', 'interface'): if self.__is_parameter(pos): pos = self.__fix_field_comment(pos) else: pos", "== '{': brace_count += 1 elif self.__tokens[i].get_value() == '}': brace_count", "if self.__is_final(pos): for parameter in parameters: if not Formatter.is_snake_upper_case(parameter): self.__to_fix[parameter]", "!= '{': if self.__tokens[pos].get_value() == ';': return pos + 1", "= comment_string[start:end] if link is not None: new_link = self.__fix_link(link)", "i -= 1 parameters.append(self.__tokens[i].get_value()) pos += 1 return parameters def", "for parameter in parameters: if not Formatter.is_camel_lower_case(parameter): self.__to_fix[parameter] = Formatter.to_camel_lower_case(parameter)", "')': if self.__tokens[pos + 1].get_value() in (')', ','): i =", "elif self.__tokens[i].get_value() in ('=', ';'): naming_pos = i - 1", "else \"\"}\\n' \\ f'{indent} */' update_token_value(self.__file, comment_token, comment_string) insert_pos =", "if len(params) <= 0 else ' ') + \\ f'\\n{indent}", "= 0 params = [] throws = [] return_type =", "* @return {self.__get_return_type(pos)}\") comment_token = Token(None, TokenType.COMMENT) comment_string = f'{indent}/**\\n'", "link.replace(name, self.__to_fix[name]) return link def __get_indent(self, pos): pos = self.__find_token_before(pos,", "+ \"\\n\".join( [f\"{indent} * @throws {param}\" for param in Formatter.get_missing(throws,", "return naming.find('_') == -1 and not naming.isupper() and naming[0].isupper() @staticmethod", "!= '(': pos += 1 pos -= 1 while self.__tokens[pos].get_type()", "(TokenType.IDENTIFIER, TokenType.KEYWORD) and \\ self.__tokens[type_pos].get_value() not in ('class', 'identifier')) or", "comment_token) else: self.__fix_comment_links(comment_token) params_list = self.__get_parameter_list(pos) params_list.extend(self.__get_type_parameter_list(pos)) throws_list = self.__get_throws(pos)", "= self.__fix_class_comments(i) i += 1 i += 1 # Fix", "TokenType.COMMENT) comment_string = f'{indent}/**\\n' + \\ '\\n'.join(all_params) + \\ (''", "= Formatter.to_camel_lower_case(self.__tokens[pos].get_value()) parameters[self.__tokens[pos].get_value()] = fixed_value update_token_value(self.__file, self.__tokens[pos], fixed_value) i +=", "Formatter.to_camel_lower_case(naming) return lower[0].upper() + lower[1:] @staticmethod def is_snake_lower_case(naming): return naming.islower()", "pos = self.__fix_method_body(pos, parameters) pos += 1 return pos def", "not Formatter.is_snake_lower_case( self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_snake_lower_case(self.__tokens[i].get_value()) def __get_method_parameters(self, i): parameters", "> 0: all_params.append(\"\\n\".join([f\"{indent} * @throws {param}\" for param in throws]))", "= i while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if", "+ comment_string[i:] if comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) return", "pos -= 1 return pos def __find_token_after(self, pos, value): while", "pos -= 1 if not Formatter.is_camel_lower_case(self.__tokens[pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[pos].get_value()) parameters[self.__tokens[pos].get_value()]", "return pos @staticmethod def is_lower_case(naming): return naming.find('_') == -1 and", "= Token(None, TokenType.COMMENT) comment_string = comment_string = f'{indent}/**\\n' \\ f'{indent}", "\\ f' */' update_token_value(self.__file, comment_token, comment_string) insert_pos = self.__find_token_before(pos, '\\n')", "params.append(value) elif macro == '@throws': throws.append(value) elif macro == '@return':", "while self.__tokens[pos].get_value() != ')': if self.__tokens[pos + 1].get_value() in (')',", "*\\n' \\ f' * {datetime.date.today().strftime(\"%B %d, %Y\")}\\n' \\ f' */'", "', i) macro = comment_string[i:start] end = min(comment_string.find(' ', start", "1 parameters.append(self.__tokens[i].get_value()) pos += 1 return parameters def __get_throws(self, pos):", "while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos += 1 return pos @staticmethod", "brace_count -= 1 elif self.__tokens[i].get_value() in ('=', ';'): naming_pos =", "i, class_name): while self.__tokens[i].get_value() not in ('(', ';'): i +=", "comment_string = comment_string[:i] + append_string + comment_string[i:] if comment_string !=", "params_list)]) i = comment_string.rfind('@param') if i != -1: i =", "while self.__tokens[pos].get_value() != ';': if self.__tokens[pos].get_type() == TokenType.IDENTIFIER and not", "value): while pos < len(self.__tokens) and self.__tokens[pos].get_value() != value: pos", "and self.__tokens[pos].get_value() != value: pos += 1 return pos def", "pos, class_name): while self.__tokens[pos].get_value() != '{': pos += 1 count", "-= 1 comment_string = comment_string[:i] + append_string + comment_string[i:] if", "= None i += 1 if comment_string != comment_token.get_value(): update_token_value(self.__file,", "1 pos += 1 while count != 0: if self.__tokens[pos].get_value()", "elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and self.__tokens[ pos + 1].get_value()", "i - 1 while self.__tokens[naming_pos].get_type() == TokenType.WHITESPACE: naming_pos -= 1", "+= 1 i += 1 # Fix start comment def", "-= 1 parameters.append(self.__tokens[i].get_value()) pos += 1 return parameters def __get_type_parameter_list(self,", "if self.__tokens[i + 1].get_value() in (')', ','): pos = i", "while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 while self.__tokens[pos].get_type() !=", "is_throws and self.__tokens[pos].get_type() == TokenType.IDENTIFIER: throws.append(self.__tokens[pos].get_value()) pos += 1 return", "+ 1)) end = end if end >= 0 else", "== TokenType.WHITESPACE: pos -= 1 if self.__tokens[pos].get_value() == '>': while", "re import datetime from javaccflab.lexer import parse from javaccflab.java_token import", "!= value: pos += 1 return pos def __fix_comment_links(self, comment_token):", "parameters: if not Formatter.is_snake_upper_case(parameter): self.__to_fix[parameter] = Formatter.to_snake_upper_case(parameter) else: for parameter", "class_name): while self.__tokens[i].get_value() not in ('(', ';'): i += 1", "__fix(self): for token in self.__tokens: if token.get_value() in self.__to_fix and", "self.__tokens[pos].get_type() == TokenType.WHITESPACE: if self.__tokens[pos].get_value() == ' ': count +=", "1 return_type.append(self.__tokens[pos].get_value()) return_type.reverse() return ''.join(return_type) def __fix_comment_params(self, comment_token): i =", "value not in before: missing_params.append(value) return missing_params def __get_parameter_list(self, pos):", "not in ('=', ';', '('): if self.__tokens[pos].get_value() in ('private', 'public',", "','): while pos > 0 and self.__tokens[pos].get_value() not in (';',", "throws def __get_return_type(self, pos): return_type = [] while self.__tokens[pos].get_value() !=", "in (';', '=', '('): if self.__tokens[i].get_value() == 'final': return True", "self.__get_indent(pos) all_params = [] if comment_token is None: params =", "tokens[i] self.__file = self.__files[i] self.__fix() self.__fix_comments() tokens[i] = self.__tokens i", "+= 1 def __fix_package(self, pos): pos = self.__skip_ws_tokens(pos) while self.__tokens[pos].get_value()", "def __fix_method_body(self, i, method_parameters): params = dict() while self.__tokens[i].get_value() not", "macro == '@param': params.append(value) elif macro == '@throws': throws.append(value) elif", "if not is_value: params.append(field_name) i += 1 end = i", "__fix_comments(self): self.__add_start_comment() i = 0 while i < len(self.__tokens): if", "i): params = [] while self.__tokens[i].get_value() != ';': if self.__tokens[i", "for value in after: if value not in before: missing_params.append(value)", "pos def __fix_class_body(self, pos, class_name): while self.__tokens[pos].get_value() != '{': pos", "comment_string.find('\\n', i) if len(return_type) == '': append_string += \"\\n\" +", "{\"constant\" if self.__is_final(pos) else \"variable\"}{\"s\" if len(field_names) > 0 else", "else: pos = self.__fix_method_comment(pos) pos += 1 return pos def", "'' comment_string = comment_token.get_value() while i < len(comment_string): if comment_string[i]", "+= 1 return parameters def __get_throws(self, pos): throws = []", "= self.__find_token_before(pos, '\\n') while self.__tokens[pos].get_value() not in ('=', ';', '('):", "def __fix_comment_links(self, comment_token): i = 0 link = None comment_string", "= comment_string.find('}', i) link = comment_string[start:end] if link is not", "('class', 'interface') and self.__tokens[i - 1].get_value() != '.': i +=", "i while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 field_name =", "TokenType.WHITESPACE)) self.__tokens.insert(insert_pos + 1, comment_token) else: self.__fix_comment_links(comment_token) params_list = self.__get_parameter_list(pos)", "self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[ i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i],", "- 1 comment_string = comment_string[:i] + append_string + comment_string[i:] append_string", "self.__fix_package(i) elif token.get_value() in ('class', 'interface') and self.__tokens[i - 1].get_value()", "Formatter.get_missing(params, params_list)]) i = comment_string.rfind('@param') if i != -1: i", "== TokenType.WHITESPACE: i += 1 parameters.append(self.__tokens[i].get_value()) pos += 1 return", "\\ f'\\n{indent} */' update_token_value(self.__file, comment_token, comment_string) insert_pos = self.__find_token_before(pos, '\\n')", "+ 1, comment_token) else: self.__fix_comment_links(comment_token) params_list = self.__get_parameter_list(pos) params_list.extend(self.__get_type_parameter_list(pos)) throws_list", "comment_token.get_value() while i < len(comment_string): if comment_string[i] == '@': start", "+= 1 return ' ' * count def __skip_ws_tokens(self, pos):", "if self.__tokens[pos].get_value() == ';': return pos + 1 pos +=", "1 return_type.append(self.__tokens[pos].get_value()) pos -= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: return_type.append(self.__tokens[pos].get_value())", "0: all_params.append(\"\\n\".join([f\"{indent} * @param {param}\" for param in params])) throws", "count += 1 pos += 1 return ' ' *", "1 pos += 1 return ' ' * count def", "comment_token) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) self.__tokens.insert(1, Token('\\n', TokenType.WHITESPACE)) def __is_start_comment_exists(self): i", "+= 1 parameters.append(self.__tokens[i].get_value()) pos += 1 return parameters def __get_throws(self,", "= ', '.join(self.__get_field_names(pos)[0]) visibility = self.__find_visibility(pos) comment_token = Token(None, TokenType.COMMENT)", "link def __get_indent(self, pos): pos = self.__find_token_before(pos, '\\n') count =", "return self.__tokens[pos] return None def __find_token_before(self, pos, value): while pos", "pos > 0 and self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1", "1, comment_token) else: self.__fix_comment_links(comment_token) return self.__fix_class_body_comments(pos) # Fix comments for", "'r').read())) i = 0 while i < len(tokens): self.__tokens =", "self.__fix_comment_params(comment_token) comment_string = comment_token.get_value() append_string = '' i = 0", "pos - 1 while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1", "comment_string = comment_token.get_value() append_string = '' i = 0 if", "pos -= 1 return_type.append(self.__tokens[pos].get_value()) return_type.reverse() return ''.join(return_type) def __fix_comment_params(self, comment_token):", "+= 1 return 'package-private' def __fix_method_comment(self, pos): comment_token = self.__find_doc_comment_before(pos)", "if self.__tokens[i].get_value() in ('class', 'interface'): i = self.__fix_class_comments(i) i +=", "1 return pos @staticmethod def is_lower_case(naming): return naming.find('_') == -1", "component in naming.split('_')]) @staticmethod def is_camel_lower_case(naming): return naming.find('_') == -1", "[ component[0] + component[1:].lower() if component.isupper() else component[0].upper() + component[1:]", "not token.is_fixed(): update_token_value(self.__file, token, self.__to_fix[token.get_value()]) def __fix_comments(self): self.__add_start_comment() i =", "'=': return True elif self.__tokens[pos].get_value() in ('class', 'interface', '(', ')'):", "in before: missing_params.append(value) return missing_params def __get_parameter_list(self, pos): parameters =", "= comment_string.replace(value, new_value) update_token_value(self.__file, comment_token, comment_string) value = new_value if", "self.__tokens[i].get_value()): self.__to_fix[self.__tokens[i].get_value()] = Formatter.to_snake_lower_case(self.__tokens[i].get_value()) def __get_method_parameters(self, i): parameters = dict()", "return_type = self.__fix_comment_params(comment_token) comment_string = comment_token.get_value() append_string = '' i", "1 count = 1 pos += 1 while count !=", "1 return pos def __find_token_after(self, pos, value): while pos <", "value = new_value if macro == '@param': params.append(value) elif macro", "return i def __get_field_names(self, i): params = [] while self.__tokens[i].get_value()", "pos while self.__tokens[i].get_type() == TokenType.WHITESPACE: i += 1 parameters.append(self.__tokens[i].get_value()) pos", "missing_params def __get_parameter_list(self, pos): parameters = [] while self.__tokens[pos].get_value() !=", "if self.__tokens[pos].get_value() == '=': return True elif self.__tokens[pos].get_value() in ('class',", "self.__tokens[pos].get_value() != '{': if self.__tokens[pos].get_value() == ';': return pos +", "True elif self.__tokens[pos].get_value() in ('class', 'interface', '(', ')'): return False", "i -= 1 while self.__tokens[i].get_type() == TokenType.WHITESPACE: i -= 1", "self.__tokens[i].get_value() == ';': return i + 1 brace_count = 1", "i = self.__skip_ws_tokens(pos + 1) if self.__tokens[i].get_value() == '{': pos", "i += 1 while brace_count != 0: if self.__tokens[i].get_value() ==", "self.__tokens[pos].get_value() != '>': if self.__tokens[pos - 1].get_value() in ('<', ','):", "self.__fix_comment_links(comment_token) return self.__find_token_after(pos, ';') def __find_visibility(self, pos): pos = self.__find_token_before(pos,", "while self.__tokens[i].get_value() not in ('(', ';'): i += 1 i", "!= '(': i += 1 while self.__tokens[i].get_value() != ')': if", "throws])) return_type = self.__get_return_type(pos) if len(return_type) > 0: all_params.append(f\"{indent} *", "def __get_parameter_list(self, pos): parameters = [] while self.__tokens[pos].get_value() != '(':", "comment_string != comment_token.get_value(): update_token_value(self.__file, comment_token, comment_string) return self.__skip_method(pos) @staticmethod def", "('class', 'identifier')) or self.__tokens[ type_pos].get_value() == ',': if not Formatter.is_camel_lower_case(self.__tokens[naming_pos].get_value()):", "elif is_throws and self.__tokens[pos].get_type() == TokenType.IDENTIFIER: throws.append(self.__tokens[pos].get_value()) pos += 1", "'@param': params.append(value) elif macro == '@throws': throws.append(value) elif macro ==", "comment_token = Token(None, TokenType.COMMENT) comment_string = f'{indent}/**\\n' + \\ '\\n'.join(all_params)", "if i != -1: i = comment_string.find('\\n', i) if comment_string.find('\\n',", "1 if self.__tokens[i].get_type() != TokenType.KEYWORD or self.__tokens[i].get_value() not in ('}',", "self.__tokens[pos].get_value() == ';': return pos + 1 pos += 1", "self.__tokens[i].get_value() not in ('(', ';'): i += 1 i -=", "in parameters: if not Formatter.is_camel_lower_case(parameter): self.__to_fix[parameter] = Formatter.to_camel_lower_case(parameter) pos =", "in Formatter.get_missing(throws, throws_list)]) i = comment_string.rfind('@throws') if i != -1:", "elif token.get_value() in ('class', 'interface') and self.__tokens[i - 1].get_value() !=", "file in self.__files: tokens.append(parse(open(file, 'r').read())) i = 0 while i", "pos def __fix_method_name(self, i, class_name): while self.__tokens[i].get_value() not in ('(',", "is_snake_upper_case(naming): return naming.isupper() @staticmethod def to_snake_upper_case(naming): return Formatter.to_snake_lower_case(naming).upper() @staticmethod def", "i + 1 count += 1 continue elif self.__tokens[pos].get_type() in", "Token('\\n', TokenType.WHITESPACE)) def __is_start_comment_exists(self): i = self.__skip_ws_tokens(0) return self.__tokens[i].get_type() ==", "self.__tokens[pos].get_value() not in ('{', ';'): if self.__tokens[pos].get_value() == 'throws': is_throws", "= self.__tokens i += 1 i = 0 while i", "and self.__tokens[pos].get_value() != value: pos -= 1 return pos def", "is_camel_upper_case(naming): return naming.find('_') == -1 and not naming.isupper() and naming[0].isupper()", "and self.__tokens[pos].get_value() not in ('class', 'interface'): if self.__is_parameter(pos): pos =", "in ('(', ';'): i += 1 i -= 1 while", "len(naming) - 1 while naming[j] == '_': i -= 1", "if len(throws) > 0: all_params.append(\"\\n\".join([f\"{indent} * @throws {param}\" for param", "== 'final': return True i += 1 return False def", "return 'package-private' def __fix_method_comment(self, pos): comment_token = self.__find_doc_comment_before(pos) indent =", "= 0 while naming[i] == '_': i += 1 naming", "re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', naming) return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', naming).lower() @staticmethod def is_snake_upper_case(naming):", "Formatter.remove_underscores_around(naming) components = [ component[0] + component[1:].lower() if component.isupper() else", "TokenType.IDENTIFIER and not Formatter.is_lower_case( self.__tokens[pos].get_value()): self.__to_fix[self.__tokens[pos].get_value()] = Formatter.to_lower_case( (self.__tokens[pos].get_value())) pos", "comment_string.rfind('@param') if i != -1: i = comment_string.find('\\n', i) if", "= True pos -= 1 if not is_value: params.append(field_name) i", "pos def __fix_field_comment(self, pos): comment_token = self.__find_doc_comment_before(pos) indent = self.__get_indent(pos)", "return ' ' * count def __skip_ws_tokens(self, pos): while self.__tokens[pos].get_type()", "i += 1 if self.__tokens[i].get_value() == ';': return i +", "pos += 1 return pos def __fix_comment_links(self, comment_token): i =", "count += 1 continue elif self.__tokens[pos].get_type() in (TokenType.IDENTIFIER, TokenType.KEYWORD) and", "def __skip_method(self, pos): while self.__tokens[pos].get_value() != '{': if self.__tokens[pos].get_value() ==", "= self.__fix_link(value) if value != new_value: comment_string = comment_string.replace(value, new_value)", "1 i = 0 while i < len(tokens): self.__tokens =", "= self.__get_method_parameters(pos) pos = self.__fix_method_body(pos, parameters) pos += 1 return", "self.__tokens[pos].get_value() in ('class', 'interface', '(', ')'): return False pos +=", "while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if not Formatter.is_camel_lower_case(self.__tokens[pos].get_value()):", "parameters: if not Formatter.is_camel_lower_case(parameter): self.__to_fix[parameter] = Formatter.to_camel_lower_case(parameter) pos = i", "!= TokenType.WHITESPACE: pos -= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos", "is_value: params.append(field_name) i += 1 end = i return params,", "comment_token = Token(None, TokenType.COMMENT) comment_string = comment_string = f'{indent}/**\\n' \\", "def __fix_comments(self): self.__add_start_comment() i = 0 while i < len(self.__tokens):", "{param}\" for param in params])) throws = self.__get_throws(pos) if len(throws)", "elif macro == '@throws': throws.append(value) elif macro == '@return': return_type", "self.__tokens[pos].get_value() is_value = False if self.__tokens[i + 1].get_value() in (';',", "i += 1 i = 0 while i < len(tokens):", "== TokenType.IDENTIFIER: type_pos = naming_pos - 1 while self.__tokens[type_pos].get_type() ==", "comment_string) def __fix_link(self, link): for name in self.__to_fix.keys(): pos =", "else \"variable\"}{\"s\" if len(field_names) > 0 else \"\"}\\n' \\ f'{indent}", "return_type def __skip_method(self, pos): while self.__tokens[pos].get_value() != '{': if self.__tokens[pos].get_value()", "lower = Formatter.to_camel_lower_case(naming) return lower[0].upper() + lower[1:] @staticmethod def is_snake_lower_case(naming):", "return missing_params def __get_parameter_list(self, pos): parameters = [] while self.__tokens[pos].get_value()", "self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[ i].get_value() in params.keys(): update_token_value(self.__file, self.__tokens[i],", "self.__tokens[i - 1].get_value() != '.': i += 1 i =", "0 and self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if self.__tokens[pos].get_type()", "not Formatter.is_lower_case( self.__tokens[pos].get_value()): self.__to_fix[self.__tokens[pos].get_value()] = Formatter.to_lower_case( (self.__tokens[pos].get_value())) pos += 1", "def __add_start_comment(self): if not self.__is_start_comment_exists(): comment_token = Token(None, TokenType.COMMENT) comment_string", "update_token_value(self.__file, self.__tokens[i], params[self.__tokens[i].get_value()]) elif self.__tokens[i].get_type() == TokenType.IDENTIFIER and self.__tokens[ i].get_value()", "= self.__fix_method_comment(pos) pos += 1 return pos def __fix_field_comment(self, pos):", "naming.split('_')] return components[0][0].lower() + components[0][1:] + ''.join(components[1:]) @staticmethod def is_camel_upper_case(naming):", "continue end = comment_string.find('\\n', i) link = comment_string[start:end] elif comment_string[i]", "pos += 1 return parameters def __get_type_parameter_list(self, pos): parameters =", "= self.__skip_ws_tokens(pos + 1) if self.__tokens[i].get_value() == '{': pos =", "if not Formatter.is_camel_lower_case(self.__tokens[naming_pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[naming_pos].get_value()) params[self.__tokens[naming_pos].get_value()] = fixed_value update_token_value(self.__file,", "pos += 1 return pos def __find_doc_comment_before(self, pos): while self.__tokens[pos].get_value()", "1 if not Formatter.is_camel_lower_case(self.__tokens[pos].get_value()): fixed_value = Formatter.to_camel_lower_case(self.__tokens[pos].get_value()) parameters[self.__tokens[pos].get_value()] = fixed_value", "while pos > 0 and self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -=", "pos += 1 return pos def __fix_field_comment(self, pos): comment_token =", "in params])) throws = self.__get_throws(pos) if len(throws) > 0: all_params.append(\"\\n\".join([f\"{indent}", "return_type.append(self.__tokens[pos].get_value()) pos -= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: return_type.append(self.__tokens[pos].get_value()) pos", "TokenType.IDENTIFIER: throws.append(self.__tokens[pos].get_value()) pos += 1 return throws def __get_return_type(self, pos):", "not naming.isupper() and not naming[0].isupper() @staticmethod def to_camel_lower_case(naming): naming =", "self.__file = self.__files[i] self.__fix() self.__fix_comments() tokens[i] = self.__tokens i +=", "[] while self.__tokens[pos].get_value() != '<': if self.__tokens[pos].get_value() == '(': return", "parameters def __get_throws(self, pos): throws = [] is_throws = False", "pos != -1 and not (link[pos - 1].isalpha() or link[", "pos, value): while pos > 0 and self.__tokens[pos].get_value() != value:", "import re import datetime from javaccflab.lexer import parse from javaccflab.java_token", "start comment def __add_start_comment(self): if not self.__is_start_comment_exists(): comment_token = Token(None,", "i = comment_string.find('\\n', i) if len(return_type) == '': append_string +=", "comment_string[start:end] elif comment_string[i] == '{': start = comment_string.find(' ', i)", "-= 1 while self.__tokens[pos].get_type() == TokenType.WHITESPACE: pos -= 1 if", "comment_token is None: params = self.__get_parameter_list(pos) params.extend(self.__get_type_parameter_list(pos)) if len(params) >", "return parameters def __fix_method_body(self, i, method_parameters): params = dict() while", "!= '.' and self.__tokens[pos].get_value() not in ('class', 'interface'): if self.__is_parameter(pos):", "component[0] + component[1:].lower() if component.isupper() else component[0].upper() + component[1:] for", "return lower[0].upper() + lower[1:] @staticmethod def is_snake_lower_case(naming): return naming.islower() @staticmethod", "i -= 1 naming = naming[:j + 1] return naming", "i = self.__skip_ws_tokens(0) return self.__tokens[i].get_type() == TokenType.COMMENT def __find_class_name(self, i=0):", "missing_params = [] for value in after: if value not", "> 0: all_params.append(f\"{indent} * @return {self.__get_return_type(pos)}\") comment_token = Token(None, TokenType.COMMENT)", "return Formatter.to_snake_lower_case(naming).upper() @staticmethod def remove_underscores_around(naming): i = 0 while naming[i]", "== ';': return i + 1 brace_count = 1 i", "i) link = comment_string[start:end] if link is not None: new_link", "= f'/*\\n' \\ f' * {self.__find_class_name()}\\n' \\ f' *\\n' \\", "naming).lower() @staticmethod def is_snake_upper_case(naming): return naming.isupper() @staticmethod def to_snake_upper_case(naming): return", "in ('=', ';'): naming_pos = i - 1 while self.__tokens[naming_pos].get_type()", "-= 1 if self.__tokens[naming_pos].get_type() == TokenType.IDENTIFIER: type_pos = naming_pos -", "1 return pos def __fix_method_name(self, i, class_name): while self.__tokens[i].get_value() not", "self.__fix() self.__fix_comments() tokens[i] = self.__tokens i += 1 return tokens", "elif comment_string[i] == '{': start = comment_string.find(' ', i) end", "Formatter.to_camel_lower_case(parameter) pos = i else: self.__fix_method_name(pos, class_name) parameters = self.__get_method_parameters(pos)", "return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', naming).lower() @staticmethod def is_snake_upper_case(naming): return naming.isupper() @staticmethod", "TokenType.WHITESPACE: i -= 1 parameters.append(self.__tokens[i].get_value()) pos += 1 return parameters", "\"\\n\".join( [f\"{indent} * @param {param}\" for param in Formatter.get_missing(params, params_list)])", "# Fix comments for methods and fields def __fix_class_body_comments(self, pos):", "field_name = self.__tokens[pos].get_value() is_value = False if self.__tokens[i + 1].get_value()", "naming.split('_')]) @staticmethod def is_camel_lower_case(naming): return naming.find('_') == -1 and not", "+ components[0][1:] + ''.join(components[1:]) @staticmethod def is_camel_upper_case(naming): return naming.find('_') ==", "def __fix_class_comments(self, pos): comment_token = self.__find_doc_comment_before(pos) if comment_token is None:", "elif macro == '@return': return_type = value i += 1", "== TokenType.IDENTIFIER and self.__tokens[ i].get_value() in method_parameters.keys(): update_token_value(self.__file, self.__tokens[i], method_parameters[self.__tokens[i].get_value()])", "not in before: missing_params.append(value) return missing_params def __get_parameter_list(self, pos): parameters", "1 return True def __fix(self): for token in self.__tokens: if" ]
[ "bool, optional If True (default), use double initialization point. Needs", "using a standard projected gradient solver. This attack uses a", "a single point # (targeted evasion) or an array of", "parameters will be used. See :class:`COptimizerPGDExp` for more information. Attributes", "point # (targeted evasion) or an array of multiple points,", "line search. This class implements the maximum-confidence evasion attacks proposed", "int or None, optional If None an error-generic attack will", "if all classes can be manipulated. solver_params : dict or", "features. If CArray, a different bound can be specified for", "of our original work in: - https://arxiv.org/abs/1708.06131, ECML 2013, implemented", "'all' or CArray, optional Array with the classes that can", ":class:`COptimizerPGDExp` for more information. Attributes ---------- class_type : 'e-pgd-exp' \"\"\"", "'l2'}, optional Norm to use for computing the distance of", "by projecting a point from another class onto the feasible", "to initialize an alternative init point (double init). double_init :", "or None, optional Dataset used to initialize an alternative init", "EURASIP JIS, 2020. - https://arxiv.org/abs/1708.06939, ICCV W. ViPAR, 2017. It", "feature. Default `lb = 0`, `ub = 1`. y_target :", "computing the distance of the adversarial example from the original", "See :class:`COptimizerPGDExp` for more information. Attributes ---------- class_type : 'e-pgd-exp'", "our original work in: - https://arxiv.org/abs/1708.06131, ECML 2013, implemented using", "Descent. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from secml.adv.attacks.evasion import CAttackEvasionPGDLS", "2015 If the attack is not successful when starting from", "classifier=classifier, double_init_ds=double_init_ds, double_init=double_init, distance=distance, dmax=dmax, lb=lb, ub=ub, y_target=y_target, attack_classes=attack_classes, solver_params=solver_params)", "double_init_ds not to be None. distance : {'l1' or 'l2'},", "Attributes ---------- class_type : 'e-pgd-exp' \"\"\" __class_type = 'e-pgd-exp' def", "one for each # class (indiscriminate evasion). See _get_point_with_min_f_obj() self._xk", "PGD-LS. In all our attacks, we use a smart double", "belonging to the `y_target` class. attack_classes : 'all' or CArray,", "class (indiscriminate evasion). See _get_point_with_min_f_obj() self._xk = None super(CAttackEvasionPGDExp, self).__init__(", "classifier, double_init_ds=None, double_init=True, distance='l1', dmax=0, lb=0, ub=1, y_target=None, attack_classes='all', solver_params=None):", "int, the same bound will be applied to all the", "same bound will be applied to all the features. If", "error-generic attack will be performed, else a error-specific attack to", "distance : {'l1' or 'l2'}, optional Norm to use for", "our attacks, we use a smart double initialization to avoid", "distance='l1', dmax=0, lb=0, ub=1, y_target=None, attack_classes='all', solver_params=None): # INTERNALS self._x0", "is not successful when starting from x0, we initialize the", "<<EMAIL>> \"\"\" from secml.adv.attacks.evasion import CAttackEvasionPGDLS class CAttackEvasionPGDExp(CAttackEvasionPGDLS): \"\"\"Evasion attacks", "points, one for each # class (indiscriminate evasion). See _get_point_with_min_f_obj()", "be manipulated by the attacker or 'all' (default) if all", "evasion). See _get_point_with_min_f_obj() self._xk = None super(CAttackEvasionPGDExp, self).__init__( classifier=classifier, double_init_ds=double_init_ds,", "= 1`. y_target : int or None, optional If None", "`lb = 0`, `ub = 1`. y_target : int or", "TCYB, 2015 If the attack is not successful when starting", "for each feature. Default `lb = 0`, `ub = 1`.", "maximum-confidence evasion attacks proposed in: - https://arxiv.org/abs/1910.00470, EURASIP JIS, 2020.", "`y_target` class. attack_classes : 'all' or CArray, optional Array with", "If int, the same bound will be applied to all", "self._xk = None super(CAttackEvasionPGDExp, self).__init__( classifier=classifier, double_init_ds=double_init_ds, double_init=double_init, distance=distance, dmax=dmax,", "def __init__(self, classifier, double_init_ds=None, double_init=True, distance='l1', dmax=0, lb=0, ub=1, y_target=None,", "evasion attacks proposed in: - https://arxiv.org/abs/1910.00470, EURASIP JIS, 2020. -", "2013, implemented using a standard projected gradient solver. This attack", "be a single point # (targeted evasion) or an array", "attack is not successful when starting from x0, we initialize", "used to initialize an alternative init point (double init). double_init", "the attacker or 'all' (default) if all classes can be", "else a error-specific attack to have the samples misclassified as", "__class_type = 'e-pgd-exp' def __init__(self, classifier, double_init_ds=None, double_init=True, distance='l1', dmax=0,", "\"\"\"Evasion attacks using Projected Gradient Descent with Exponential line search.", "domain and try again. Parameters ---------- classifier : CClassifier Target", "If CArray, a different bound can be specified for each", "with the classes that can be manipulated by the attacker", "or CArray, optional Array with the classes that can be", "attack to have the samples misclassified as belonging to the", "used. See :class:`COptimizerPGDExp` for more information. Attributes ---------- class_type :", "`ub = 1`. y_target : int or None, optional If", "'all' (default) if all classes can be manipulated. solver_params :", "projecting a point from another class onto the feasible domain", "init). double_init : bool, optional If True (default), use double", "initialization to avoid using the mimicry term from our ECML", "(indiscriminate evasion). See _get_point_with_min_f_obj() self._xk = None super(CAttackEvasionPGDExp, self).__init__( classifier=classifier,", "x0, we initialize the optimization by projecting a point from", "avoid using the mimicry term from our ECML 2013 paper,", "implemented using a standard projected gradient solver. This attack uses", "a point from another class onto the feasible domain and", "# INTERNALS self._x0 = None self._y0 = None # this", "alternative init point. This could be a single point #", "CDataset or None, optional Dataset used to initialize an alternative", "This could be a single point # (targeted evasion) or", "for each # class (indiscriminate evasion). See _get_point_with_min_f_obj() self._xk =", "applied to all the features. If CArray, a different bound", "we initialize the optimization by projecting a point from another", "optimization by projecting a point from another class onto the", "the original sample. Default 'l2'. dmax : scalar, optional Maximum", "Parameters ---------- classifier : CClassifier Target classifier. double_init_ds : CDataset", "multiple points, one for each # class (indiscriminate evasion). See", "work in: - https://arxiv.org/abs/1708.06131, ECML 2013, implemented using a standard", "an array of multiple points, one for each # class", ": 'e-pgd-exp' \"\"\" __class_type = 'e-pgd-exp' def __init__(self, classifier, double_init_ds=None,", "using Projected Gradient Descent. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from", "0`, `ub = 1`. y_target : int or None, optional", "that default parameters will be used. See :class:`COptimizerPGDExp` for more", "solver_params=None): # INTERNALS self._x0 = None self._y0 = None #", "solver. This attack uses a faster line search than PGD-LS.", "paper, as described in: - https://pralab.diee.unica.it/sites/default/files/zhang15-tcyb.pdf, IEEE TCYB, 2015 If", "https://arxiv.org/abs/1910.00470, EURASIP JIS, 2020. - https://arxiv.org/abs/1708.06939, ICCV W. ViPAR, 2017.", "double initialization point. Needs double_init_ds not to be None. distance", "double_init_ds=None, double_init=True, distance='l1', dmax=0, lb=0, ub=1, y_target=None, attack_classes='all', solver_params=None): #", "scalar, optional Maximum value of the perturbation. Default 1. lb,", "dmax=0, lb=0, ub=1, y_target=None, attack_classes='all', solver_params=None): # INTERNALS self._x0 =", "ViPAR, 2017. It is the multi-class extension of our original", "or 'all' (default) if all classes can be manipulated. solver_params", "# this is an alternative init point. This could be", "initialize the optimization by projecting a point from another class", ": bool, optional If True (default), use double initialization point.", "distance of the adversarial example from the original sample. Default", "- https://arxiv.org/abs/1708.06131, ECML 2013, implemented using a standard projected gradient", "Gradient Descent. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from secml.adv.attacks.evasion import", "2017. It is the multi-class extension of our original work", "None super(CAttackEvasionPGDExp, self).__init__( classifier=classifier, double_init_ds=double_init_ds, double_init=double_init, distance=distance, dmax=dmax, lb=lb, ub=ub,", "attack uses a faster line search than PGD-LS. In all", "bounds. If int, the same bound will be applied to", "information. Attributes ---------- class_type : 'e-pgd-exp' \"\"\" __class_type = 'e-pgd-exp'", "successful when starting from x0, we initialize the optimization by", ".. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from secml.adv.attacks.evasion import CAttackEvasionPGDLS class", "= 'e-pgd-exp' def __init__(self, classifier, double_init_ds=None, double_init=True, distance='l1', dmax=0, lb=0,", "\"\"\" .. module:: CAttackEvasionPGDExp :synopsis: Evasion attack using Projected Gradient", "the optimization by projecting a point from another class onto", "array of multiple points, one for each # class (indiscriminate", "Exponential line search. This class implements the maximum-confidence evasion attacks", "or None, optional Parameters for the solver. Default None, meaning", "to all the features. If CArray, a different bound can", "the solver. Default None, meaning that default parameters will be", "will be used. See :class:`COptimizerPGDExp` for more information. Attributes ----------", "proposed in: - https://arxiv.org/abs/1910.00470, EURASIP JIS, 2020. - https://arxiv.org/abs/1708.06939, ICCV", "y_target=None, attack_classes='all', solver_params=None): # INTERNALS self._x0 = None self._y0 =", ": CClassifier Target classifier. double_init_ds : CDataset or None, optional", "from the original sample. Default 'l2'. dmax : scalar, optional", "not to be None. distance : {'l1' or 'l2'}, optional", "dict or None, optional Parameters for the solver. Default None,", "is an alternative init point. This could be a single", "import CAttackEvasionPGDLS class CAttackEvasionPGDExp(CAttackEvasionPGDLS): \"\"\"Evasion attacks using Projected Gradient Descent", "Projected Gradient Descent with Exponential line search. This class implements", "Dataset used to initialize an alternative init point (double init).", "from secml.adv.attacks.evasion import CAttackEvasionPGDLS class CAttackEvasionPGDExp(CAttackEvasionPGDLS): \"\"\"Evasion attacks using Projected", "'e-pgd-exp' \"\"\" __class_type = 'e-pgd-exp' def __init__(self, classifier, double_init_ds=None, double_init=True,", "for the solver. Default None, meaning that default parameters will", "or an array of multiple points, one for each #", "attack_classes : 'all' or CArray, optional Array with the classes", "each # class (indiscriminate evasion). See _get_point_with_min_f_obj() self._xk = None", "to use for computing the distance of the adversarial example", "all our attacks, we use a smart double initialization to", "optional Maximum value of the perturbation. Default 1. lb, ub", "ECML 2013, implemented using a standard projected gradient solver. This", "2020. - https://arxiv.org/abs/1708.06939, ICCV W. ViPAR, 2017. It is the", ": scalar, optional Maximum value of the perturbation. Default 1.", "and try again. Parameters ---------- classifier : CClassifier Target classifier.", "of multiple points, one for each # class (indiscriminate evasion).", "solver_params : dict or None, optional Parameters for the solver.", "a faster line search than PGD-LS. In all our attacks,", "to the `y_target` class. attack_classes : 'all' or CArray, optional", "---------- class_type : 'e-pgd-exp' \"\"\" __class_type = 'e-pgd-exp' def __init__(self,", "implements the maximum-confidence evasion attacks proposed in: - https://arxiv.org/abs/1910.00470, EURASIP", "CArray, a different bound can be specified for each feature.", "ub=1, y_target=None, attack_classes='all', solver_params=None): # INTERNALS self._x0 = None self._y0", "# (targeted evasion) or an array of multiple points, one", "described in: - https://pralab.diee.unica.it/sites/default/files/zhang15-tcyb.pdf, IEEE TCYB, 2015 If the attack", "<NAME> <<EMAIL>> \"\"\" from secml.adv.attacks.evasion import CAttackEvasionPGDLS class CAttackEvasionPGDExp(CAttackEvasionPGDLS): \"\"\"Evasion", "a smart double initialization to avoid using the mimicry term", "This class implements the maximum-confidence evasion attacks proposed in: -", "Descent with Exponential line search. This class implements the maximum-confidence", "will be applied to all the features. If CArray, a", "can be specified for each feature. Default `lb = 0`,", "more information. Attributes ---------- class_type : 'e-pgd-exp' \"\"\" __class_type =", "multi-class extension of our original work in: - https://arxiv.org/abs/1708.06131, ECML", "the distance of the adversarial example from the original sample.", "class. attack_classes : 'all' or CArray, optional Array with the", "perturbation. Default 1. lb, ub : int or CArray, optional", "can be manipulated. solver_params : dict or None, optional Parameters", "again. Parameters ---------- classifier : CClassifier Target classifier. double_init_ds :", "be performed, else a error-specific attack to have the samples", "point (double init). double_init : bool, optional If True (default),", "dmax : scalar, optional Maximum value of the perturbation. Default", "ub : int or CArray, optional Lower/Upper bounds. If int,", "extension of our original work in: - https://arxiv.org/abs/1708.06131, ECML 2013,", "ICCV W. ViPAR, 2017. It is the multi-class extension of", "as belonging to the `y_target` class. attack_classes : 'all' or", "Default 1. lb, ub : int or CArray, optional Lower/Upper", "the feasible domain and try again. Parameters ---------- classifier :", "double_init=double_init, distance=distance, dmax=dmax, lb=lb, ub=ub, y_target=y_target, attack_classes=attack_classes, solver_params=solver_params) self.solver_type =", "initialization point. Needs double_init_ds not to be None. distance :", "None, optional Parameters for the solver. Default None, meaning that", "attacker or 'all' (default) if all classes can be manipulated.", "2013 paper, as described in: - https://pralab.diee.unica.it/sites/default/files/zhang15-tcyb.pdf, IEEE TCYB, 2015", "be None. distance : {'l1' or 'l2'}, optional Norm to", ": CDataset or None, optional Dataset used to initialize an", "different bound can be specified for each feature. Default `lb", "line search than PGD-LS. In all our attacks, we use", "be manipulated. solver_params : dict or None, optional Parameters for", "Array with the classes that can be manipulated by the", "moduleauthor:: <NAME> <<EMAIL>> \"\"\" from secml.adv.attacks.evasion import CAttackEvasionPGDLS class CAttackEvasionPGDExp(CAttackEvasionPGDLS):", "JIS, 2020. - https://arxiv.org/abs/1708.06939, ICCV W. ViPAR, 2017. It is", "when starting from x0, we initialize the optimization by projecting", "CClassifier Target classifier. double_init_ds : CDataset or None, optional Dataset", "Maximum value of the perturbation. Default 1. lb, ub :", "in: - https://arxiv.org/abs/1910.00470, EURASIP JIS, 2020. - https://arxiv.org/abs/1708.06939, ICCV W.", "= 0`, `ub = 1`. y_target : int or None,", "attacks using Projected Gradient Descent with Exponential line search. This", "self).__init__( classifier=classifier, double_init_ds=double_init_ds, double_init=double_init, distance=distance, dmax=dmax, lb=lb, ub=ub, y_target=y_target, attack_classes=attack_classes,", "value of the perturbation. Default 1. lb, ub : int", "or CArray, optional Lower/Upper bounds. If int, the same bound", "smart double initialization to avoid using the mimicry term from", "True (default), use double initialization point. Needs double_init_ds not to", "_get_point_with_min_f_obj() self._xk = None super(CAttackEvasionPGDExp, self).__init__( classifier=classifier, double_init_ds=double_init_ds, double_init=double_init, distance=distance,", "(default), use double initialization point. Needs double_init_ds not to be", "super(CAttackEvasionPGDExp, self).__init__( classifier=classifier, double_init_ds=double_init_ds, double_init=double_init, distance=distance, dmax=dmax, lb=lb, ub=ub, y_target=y_target,", "bound will be applied to all the features. If CArray,", "Evasion attack using Projected Gradient Descent. .. moduleauthor:: <NAME> <<EMAIL>>", "\"\"\" from secml.adv.attacks.evasion import CAttackEvasionPGDLS class CAttackEvasionPGDExp(CAttackEvasionPGDLS): \"\"\"Evasion attacks using", "attack will be performed, else a error-specific attack to have", "INTERNALS self._x0 = None self._y0 = None # this is", "not successful when starting from x0, we initialize the optimization", "evasion) or an array of multiple points, one for each", "module:: CAttackEvasionPGDExp :synopsis: Evasion attack using Projected Gradient Descent. ..", "W. ViPAR, 2017. It is the multi-class extension of our", "than PGD-LS. In all our attacks, we use a smart", "class CAttackEvasionPGDExp(CAttackEvasionPGDLS): \"\"\"Evasion attacks using Projected Gradient Descent with Exponential", "- https://arxiv.org/abs/1708.06939, ICCV W. ViPAR, 2017. It is the multi-class", "https://arxiv.org/abs/1708.06131, ECML 2013, implemented using a standard projected gradient solver.", "using the mimicry term from our ECML 2013 paper, as", "CArray, optional Lower/Upper bounds. If int, the same bound will", "double_init_ds=double_init_ds, double_init=double_init, distance=distance, dmax=dmax, lb=lb, ub=ub, y_target=y_target, attack_classes=attack_classes, solver_params=solver_params) self.solver_type", "attacks, we use a smart double initialization to avoid using", "specified for each feature. Default `lb = 0`, `ub =", "None an error-generic attack will be performed, else a error-specific", "as described in: - https://pralab.diee.unica.it/sites/default/files/zhang15-tcyb.pdf, IEEE TCYB, 2015 If the", "None # this is an alternative init point. This could", "Parameters for the solver. Default None, meaning that default parameters", "{'l1' or 'l2'}, optional Norm to use for computing the", "faster line search than PGD-LS. In all our attacks, we", "double initialization to avoid using the mimicry term from our", "lb, ub : int or CArray, optional Lower/Upper bounds. If", "for computing the distance of the adversarial example from the", "CAttackEvasionPGDExp(CAttackEvasionPGDLS): \"\"\"Evasion attacks using Projected Gradient Descent with Exponential line", "default parameters will be used. See :class:`COptimizerPGDExp` for more information.", "<filename>src/secml/adv/attacks/evasion/c_attack_evasion_pgd_exp.py \"\"\" .. module:: CAttackEvasionPGDExp :synopsis: Evasion attack using Projected", "---------- classifier : CClassifier Target classifier. double_init_ds : CDataset or", "None, optional Dataset used to initialize an alternative init point", "starting from x0, we initialize the optimization by projecting a", "projected gradient solver. This attack uses a faster line search", "int or CArray, optional Lower/Upper bounds. If int, the same", "can be manipulated by the attacker or 'all' (default) if", "of the perturbation. Default 1. lb, ub : int or", "ECML 2013 paper, as described in: - https://pralab.diee.unica.it/sites/default/files/zhang15-tcyb.pdf, IEEE TCYB,", "to be None. distance : {'l1' or 'l2'}, optional Norm", "None. distance : {'l1' or 'l2'}, optional Norm to use", "the samples misclassified as belonging to the `y_target` class. attack_classes", "sample. Default 'l2'. dmax : scalar, optional Maximum value of", "by the attacker or 'all' (default) if all classes can", "- https://arxiv.org/abs/1910.00470, EURASIP JIS, 2020. - https://arxiv.org/abs/1708.06939, ICCV W. ViPAR,", "self._y0 = None # this is an alternative init point.", "__init__(self, classifier, double_init_ds=None, double_init=True, distance='l1', dmax=0, lb=0, ub=1, y_target=None, attack_classes='all',", "classes that can be manipulated by the attacker or 'all'", "1`. y_target : int or None, optional If None an", "search. This class implements the maximum-confidence evasion attacks proposed in:", "IEEE TCYB, 2015 If the attack is not successful when", "of the adversarial example from the original sample. Default 'l2'.", "double_init : bool, optional If True (default), use double initialization", "point. This could be a single point # (targeted evasion)", "classifier : CClassifier Target classifier. double_init_ds : CDataset or None,", "Default None, meaning that default parameters will be used. See", "an error-generic attack will be performed, else a error-specific attack", "an alternative init point (double init). double_init : bool, optional", "use double initialization point. Needs double_init_ds not to be None.", "or 'l2'}, optional Norm to use for computing the distance", "to avoid using the mimicry term from our ECML 2013", "uses a faster line search than PGD-LS. In all our", "this is an alternative init point. This could be a", "In all our attacks, we use a smart double initialization", "= None # this is an alternative init point. This", "= None self._y0 = None # this is an alternative", "feasible domain and try again. Parameters ---------- classifier : CClassifier", "Default 'l2'. dmax : scalar, optional Maximum value of the", "attack using Projected Gradient Descent. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\"", "self._x0 = None self._y0 = None # this is an", ": 'all' or CArray, optional Array with the classes that", "double_init_ds : CDataset or None, optional Dataset used to initialize", "term from our ECML 2013 paper, as described in: -", "our ECML 2013 paper, as described in: - https://pralab.diee.unica.it/sites/default/files/zhang15-tcyb.pdf, IEEE", "solver. Default None, meaning that default parameters will be used.", "meaning that default parameters will be used. See :class:`COptimizerPGDExp` for", "= None super(CAttackEvasionPGDExp, self).__init__( classifier=classifier, double_init_ds=double_init_ds, double_init=double_init, distance=distance, dmax=dmax, lb=lb,", ": {'l1' or 'l2'}, optional Norm to use for computing", "secml.adv.attacks.evasion import CAttackEvasionPGDLS class CAttackEvasionPGDExp(CAttackEvasionPGDLS): \"\"\"Evasion attacks using Projected Gradient", "the same bound will be applied to all the features.", "to have the samples misclassified as belonging to the `y_target`", "https://arxiv.org/abs/1708.06939, ICCV W. ViPAR, 2017. It is the multi-class extension", "performed, else a error-specific attack to have the samples misclassified", "using Projected Gradient Descent with Exponential line search. This class", "optional Parameters for the solver. Default None, meaning that default", "It is the multi-class extension of our original work in:", "the `y_target` class. attack_classes : 'all' or CArray, optional Array", ": int or None, optional If None an error-generic attack", ".. module:: CAttackEvasionPGDExp :synopsis: Evasion attack using Projected Gradient Descent.", "class onto the feasible domain and try again. Parameters ----------", "single point # (targeted evasion) or an array of multiple", "the maximum-confidence evasion attacks proposed in: - https://arxiv.org/abs/1910.00470, EURASIP JIS,", "manipulated. solver_params : dict or None, optional Parameters for the", "will be performed, else a error-specific attack to have the", "None self._y0 = None # this is an alternative init", "Lower/Upper bounds. If int, the same bound will be applied", "optional If None an error-generic attack will be performed, else", "be specified for each feature. Default `lb = 0`, `ub", ": int or CArray, optional Lower/Upper bounds. If int, the", "for more information. Attributes ---------- class_type : 'e-pgd-exp' \"\"\" __class_type", "be used. See :class:`COptimizerPGDExp` for more information. Attributes ---------- class_type", "If True (default), use double initialization point. Needs double_init_ds not", "mimicry term from our ECML 2013 paper, as described in:", "CAttackEvasionPGDExp :synopsis: Evasion attack using Projected Gradient Descent. .. moduleauthor::", "Projected Gradient Descent. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from secml.adv.attacks.evasion", "point. Needs double_init_ds not to be None. distance : {'l1'", "use for computing the distance of the adversarial example from", "from our ECML 2013 paper, as described in: - https://pralab.diee.unica.it/sites/default/files/zhang15-tcyb.pdf,", "is the multi-class extension of our original work in: -", "misclassified as belonging to the `y_target` class. attack_classes : 'all'", "each feature. Default `lb = 0`, `ub = 1`. y_target", "- https://pralab.diee.unica.it/sites/default/files/zhang15-tcyb.pdf, IEEE TCYB, 2015 If the attack is not", "https://pralab.diee.unica.it/sites/default/files/zhang15-tcyb.pdf, IEEE TCYB, 2015 If the attack is not successful", "original sample. Default 'l2'. dmax : scalar, optional Maximum value", "use a smart double initialization to avoid using the mimicry", "CAttackEvasionPGDLS class CAttackEvasionPGDExp(CAttackEvasionPGDLS): \"\"\"Evasion attacks using Projected Gradient Descent with", "the classes that can be manipulated by the attacker or", "all classes can be manipulated. solver_params : dict or None,", "another class onto the feasible domain and try again. Parameters", "None, optional If None an error-generic attack will be performed,", "double_init=True, distance='l1', dmax=0, lb=0, ub=1, y_target=None, attack_classes='all', solver_params=None): # INTERNALS", "a standard projected gradient solver. This attack uses a faster", "# class (indiscriminate evasion). See _get_point_with_min_f_obj() self._xk = None super(CAttackEvasionPGDExp,", "class_type : 'e-pgd-exp' \"\"\" __class_type = 'e-pgd-exp' def __init__(self, classifier,", "the features. If CArray, a different bound can be specified", "all the features. If CArray, a different bound can be", "(default) if all classes can be manipulated. solver_params : dict", "Norm to use for computing the distance of the adversarial", "could be a single point # (targeted evasion) or an", "gradient solver. This attack uses a faster line search than", "a error-specific attack to have the samples misclassified as belonging", "in: - https://pralab.diee.unica.it/sites/default/files/zhang15-tcyb.pdf, IEEE TCYB, 2015 If the attack is", "example from the original sample. Default 'l2'. dmax : scalar,", "alternative init point (double init). double_init : bool, optional If", "This attack uses a faster line search than PGD-LS. In", "search than PGD-LS. In all our attacks, we use a", "error-specific attack to have the samples misclassified as belonging to", "Gradient Descent with Exponential line search. This class implements the", "point from another class onto the feasible domain and try", "try again. Parameters ---------- classifier : CClassifier Target classifier. double_init_ds", "1. lb, ub : int or CArray, optional Lower/Upper bounds.", "the multi-class extension of our original work in: - https://arxiv.org/abs/1708.06131,", "If the attack is not successful when starting from x0,", "Needs double_init_ds not to be None. distance : {'l1' or", "distance=distance, dmax=dmax, lb=lb, ub=ub, y_target=y_target, attack_classes=attack_classes, solver_params=solver_params) self.solver_type = 'pgd-exp'", ":synopsis: Evasion attack using Projected Gradient Descent. .. moduleauthor:: <NAME>", "in: - https://arxiv.org/abs/1708.06131, ECML 2013, implemented using a standard projected", "onto the feasible domain and try again. Parameters ---------- classifier", "with Exponential line search. This class implements the maximum-confidence evasion", "the perturbation. Default 1. lb, ub : int or CArray,", "class implements the maximum-confidence evasion attacks proposed in: - https://arxiv.org/abs/1910.00470,", "Default `lb = 0`, `ub = 1`. y_target : int", "init point (double init). double_init : bool, optional If True", "attack_classes='all', solver_params=None): # INTERNALS self._x0 = None self._y0 = None", "(targeted evasion) or an array of multiple points, one for", "the attack is not successful when starting from x0, we", "y_target : int or None, optional If None an error-generic", "a different bound can be specified for each feature. Default", "optional If True (default), use double initialization point. Needs double_init_ds", "Target classifier. double_init_ds : CDataset or None, optional Dataset used", "that can be manipulated by the attacker or 'all' (default)", ": dict or None, optional Parameters for the solver. Default", "optional Norm to use for computing the distance of the", "have the samples misclassified as belonging to the `y_target` class.", "initialize an alternative init point (double init). double_init : bool,", "lb=0, ub=1, y_target=None, attack_classes='all', solver_params=None): # INTERNALS self._x0 = None", "classes can be manipulated. solver_params : dict or None, optional", "init point. This could be a single point # (targeted", "If None an error-generic attack will be performed, else a", "'e-pgd-exp' def __init__(self, classifier, double_init_ds=None, double_init=True, distance='l1', dmax=0, lb=0, ub=1,", "optional Lower/Upper bounds. If int, the same bound will be", "from x0, we initialize the optimization by projecting a point", "optional Array with the classes that can be manipulated by", "manipulated by the attacker or 'all' (default) if all classes", "standard projected gradient solver. This attack uses a faster line", "the mimicry term from our ECML 2013 paper, as described", "CArray, optional Array with the classes that can be manipulated", "None, meaning that default parameters will be used. See :class:`COptimizerPGDExp`", "from another class onto the feasible domain and try again.", "optional Dataset used to initialize an alternative init point (double", "bound can be specified for each feature. Default `lb =", "'l2'. dmax : scalar, optional Maximum value of the perturbation.", "the adversarial example from the original sample. Default 'l2'. dmax", "samples misclassified as belonging to the `y_target` class. attack_classes :", "we use a smart double initialization to avoid using the", "an alternative init point. This could be a single point", "See _get_point_with_min_f_obj() self._xk = None super(CAttackEvasionPGDExp, self).__init__( classifier=classifier, double_init_ds=double_init_ds, double_init=double_init,", "attacks proposed in: - https://arxiv.org/abs/1910.00470, EURASIP JIS, 2020. - https://arxiv.org/abs/1708.06939,", "(double init). double_init : bool, optional If True (default), use", "or None, optional If None an error-generic attack will be", "original work in: - https://arxiv.org/abs/1708.06131, ECML 2013, implemented using a", "\"\"\" __class_type = 'e-pgd-exp' def __init__(self, classifier, double_init_ds=None, double_init=True, distance='l1',", "adversarial example from the original sample. Default 'l2'. dmax :", "be applied to all the features. If CArray, a different", "classifier. double_init_ds : CDataset or None, optional Dataset used to" ]
[ "PRIMARY KEY, num_of_letters_sent INTEGER)''') def transfer_data(self): for email, num_of_letters in", "len(fields) == 2: ID, client_email = (f[1] for f in", "del self.queue_tracker_db[ID] elif len(fields) == 2: ID, client_email = (f[1]", "delivery_tracker_db def manage_queue_tracker(self, fields): \"\"\" Receive one of the following", "ID): \"\"\" Go through all receivers of <ID> queue of", "(f[1] for f in fields) self.queue_tracker_db[ID]['client_email'] = client_email elif len(fields)", "= email_tracker_db self.delivery_tracker_db = delivery_tracker_db def manage_queue_tracker(self, fields): \"\"\" Receive", "if status == 'sent': code = 1 else: code =", "client_email in self.email_tracker_db: self.email_tracker_db[client_email] += len(delivered_mail) else: self.email_tracker_db[client_email] = len(delivered_mail)", "def __init__(self, path, *args, **kwargs): self.path = path super().__init__(*args, **kwargs)", "sqlite3 class ManageData: def __init__(self, queue_tracker_db, email_tracker_db, delivery_tracker_db): self.queue_tracker_db =", "**kwargs): self.path = path super().__init__(*args, **kwargs) def _execute_command(self, *command): con", "3: ID, receiver, status = (f[1] for f in fields)", "= delivery_tracker_db def manage_queue_tracker(self, fields): \"\"\" Receive one of the", "result = cursor.execute(*command) if result: result = result.fetchall() con.commit() con.close()", "client_email = self.queue_tracker_db[ID]['client_email'] receivers = self.queue_tracker_db[ID]['receivers'] delivered_mail = [r for", "\"\"\" Receive one of the following located groups as <fields>:", "receivers if receivers[r] == 1] if client_email in self.email_tracker_db: self.email_tracker_db[client_email]", "their delivery statuses to the <delivery_tracker_db> counter \"\"\" receivers =", "**kwargs) def _execute_command(self, *command): con = sqlite3.connect(self.path) cursor = con.cursor()", "if result: result = result.fetchall() con.commit() con.close() return result def", "<email>)]; [('ID', <id>), ('receivers', <email>), ('status', <status>)]; [('ID', <id>)]; and", "self.queue_tracker_db[ID]['receivers'] delivered_mail = [r for r in receivers if receivers[r]", "KEY, num_of_letters_sent INTEGER)''') def transfer_data(self): for email, num_of_letters in self.email_tracker_db.items():", "self.email_tracker_db[client_email] = len(delivered_mail) def manage_delivery_tracker(self, ID): \"\"\" Go through all", "[('ID', <id>)]; and manage the <queue_tracker_db> accordingly. \"\"\" if len(fields)", "email, num_of_letters in self.email_tracker_db.items(): self._execute_command('''INSERT INTO email_tracker VALUES (?, ?)''',", "in the <email_tracker_db>. \"\"\" client_email = self.queue_tracker_db[ID]['client_email'] receivers = self.queue_tracker_db[ID]['receivers']", "'sent': code = 1 else: code = 0 self.queue_tracker_db[ID]['receivers'][receiver] =", "= code def manage_email_tracker(self, ID): \"\"\" Retrieve client's email from", "the <queue_tracker_db> accordingly. \"\"\" if len(fields) == 1: ID =", "1 else: self.delivery_tracker_db['undelivered'] += 1 class ManageDatabase(ManageData): def __init__(self, path,", "*command): con = sqlite3.connect(self.path) cursor = con.cursor() result = cursor.execute(*command)", "accordingly. \"\"\" if len(fields) == 1: ID = fields[0][1] self.manage_email_tracker(ID)", "in receivers: if receivers[receiver] == 1: self.delivery_tracker_db['delivered'] += 1 else:", "in receivers if receivers[r] == 1] if client_email in self.email_tracker_db:", "return result def create_db(self): self._execute_command('''CREATE TABLE IF NOT EXISTS email_tracker", "[('ID', <id>), ('client_email', <email>)]; [('ID', <id>), ('receivers', <email>), ('status', <status>)];", "result = result.fetchall() con.commit() con.close() return result def create_db(self): self._execute_command('''CREATE", "receivers = self.queue_tracker_db[ID]['receivers'] for receiver in receivers: if receivers[receiver] ==", "email_tracker (client_email TEXT PRIMARY KEY, num_of_letters_sent INTEGER)''') def transfer_data(self): for", "one of the following located groups as <fields>: [('ID', <id>),", "\"\"\" Retrieve client's email from the <queue_tracker_db> by <ID> with", "in fields) if status == 'sent': code = 1 else:", "__init__(self, queue_tracker_db, email_tracker_db, delivery_tracker_db): self.queue_tracker_db = queue_tracker_db self.email_tracker_db = email_tracker_db", "fields[0][1] self.manage_email_tracker(ID) self.manage_delivery_tracker(ID) del self.queue_tracker_db[ID] elif len(fields) == 2: ID,", "if client_email in self.email_tracker_db: self.email_tracker_db[client_email] += len(delivered_mail) else: self.email_tracker_db[client_email] =", "<delivery_tracker_db> counter \"\"\" receivers = self.queue_tracker_db[ID]['receivers'] for receiver in receivers:", "in fields) self.queue_tracker_db[ID]['client_email'] = client_email elif len(fields) == 3: ID,", "self.queue_tracker_db = queue_tracker_db self.email_tracker_db = email_tracker_db self.delivery_tracker_db = delivery_tracker_db def", "self.queue_tracker_db[ID]['client_email'] = client_email elif len(fields) == 3: ID, receiver, status", "== 1 and store it in the <email_tracker_db>. \"\"\" client_email", "('receivers', <email>), ('status', <status>)]; [('ID', <id>)]; and manage the <queue_tracker_db>", "client's email from the <queue_tracker_db> by <ID> with the amount", "add their delivery statuses to the <delivery_tracker_db> counter \"\"\" receivers", "for receiver in receivers: if receivers[receiver] == 1: self.delivery_tracker_db['delivered'] +=", "queue of <queue_tracker_db>, and add their delivery statuses to the", "1: ID = fields[0][1] self.manage_email_tracker(ID) self.manage_delivery_tracker(ID) del self.queue_tracker_db[ID] elif len(fields)", "amount of 'receivers' whose 'status' == 1 and store it", "fields): \"\"\" Receive one of the following located groups as", "self.manage_email_tracker(ID) self.manage_delivery_tracker(ID) del self.queue_tracker_db[ID] elif len(fields) == 2: ID, client_email", "manage_email_tracker(self, ID): \"\"\" Retrieve client's email from the <queue_tracker_db> by", "self.email_tracker_db: self.email_tracker_db[client_email] += len(delivered_mail) else: self.email_tracker_db[client_email] = len(delivered_mail) def manage_delivery_tracker(self,", "= fields[0][1] self.manage_email_tracker(ID) self.manage_delivery_tracker(ID) del self.queue_tracker_db[ID] elif len(fields) == 2:", "class ManageDatabase(ManageData): def __init__(self, path, *args, **kwargs): self.path = path", "+= 1 else: self.delivery_tracker_db['undelivered'] += 1 class ManageDatabase(ManageData): def __init__(self,", "of <queue_tracker_db>, and add their delivery statuses to the <delivery_tracker_db>", "def _execute_command(self, *command): con = sqlite3.connect(self.path) cursor = con.cursor() result", "num_of_letters in self.email_tracker_db.items(): self._execute_command('''INSERT INTO email_tracker VALUES (?, ?)''', (email,", "<email>), ('status', <status>)]; [('ID', <id>)]; and manage the <queue_tracker_db> accordingly.", "all receivers of <ID> queue of <queue_tracker_db>, and add their", "<id>), ('receivers', <email>), ('status', <status>)]; [('ID', <id>)]; and manage the", "<email_tracker_db>. \"\"\" client_email = self.queue_tracker_db[ID]['client_email'] receivers = self.queue_tracker_db[ID]['receivers'] delivered_mail =", "if len(fields) == 1: ID = fields[0][1] self.manage_email_tracker(ID) self.manage_delivery_tracker(ID) del", "<id>), ('client_email', <email>)]; [('ID', <id>), ('receivers', <email>), ('status', <status>)]; [('ID',", "statuses to the <delivery_tracker_db> counter \"\"\" receivers = self.queue_tracker_db[ID]['receivers'] for", "= result.fetchall() con.commit() con.close() return result def create_db(self): self._execute_command('''CREATE TABLE", "if receivers[r] == 1] if client_email in self.email_tracker_db: self.email_tracker_db[client_email] +=", "+= len(delivered_mail) else: self.email_tracker_db[client_email] = len(delivered_mail) def manage_delivery_tracker(self, ID): \"\"\"", "for email, num_of_letters in self.email_tracker_db.items(): self._execute_command('''INSERT INTO email_tracker VALUES (?,", "+= 1 class ManageDatabase(ManageData): def __init__(self, path, *args, **kwargs): self.path", "con.close() return result def create_db(self): self._execute_command('''CREATE TABLE IF NOT EXISTS", "of <ID> queue of <queue_tracker_db>, and add their delivery statuses", "1 and store it in the <email_tracker_db>. \"\"\" client_email =", "elif len(fields) == 3: ID, receiver, status = (f[1] for", "in self.email_tracker_db.items(): self._execute_command('''INSERT INTO email_tracker VALUES (?, ?)''', (email, num_of_letters))", "\"\"\" Go through all receivers of <ID> queue of <queue_tracker_db>,", "self.delivery_tracker_db = delivery_tracker_db def manage_queue_tracker(self, fields): \"\"\" Receive one of", "len(fields) == 3: ID, receiver, status = (f[1] for f", "located groups as <fields>: [('ID', <id>), ('client_email', <email>)]; [('ID', <id>),", "= self.queue_tracker_db[ID]['receivers'] delivered_mail = [r for r in receivers if", "receivers of <ID> queue of <queue_tracker_db>, and add their delivery", "con = sqlite3.connect(self.path) cursor = con.cursor() result = cursor.execute(*command) if", "con.cursor() result = cursor.execute(*command) if result: result = result.fetchall() con.commit()", "import sqlite3 class ManageData: def __init__(self, queue_tracker_db, email_tracker_db, delivery_tracker_db): self.queue_tracker_db", "queue_tracker_db, email_tracker_db, delivery_tracker_db): self.queue_tracker_db = queue_tracker_db self.email_tracker_db = email_tracker_db self.delivery_tracker_db", "receivers = self.queue_tracker_db[ID]['receivers'] delivered_mail = [r for r in receivers", "for r in receivers if receivers[r] == 1] if client_email", "len(fields) == 1: ID = fields[0][1] self.manage_email_tracker(ID) self.manage_delivery_tracker(ID) del self.queue_tracker_db[ID]", "self.queue_tracker_db[ID] elif len(fields) == 2: ID, client_email = (f[1] for", "== 1: self.delivery_tracker_db['delivered'] += 1 else: self.delivery_tracker_db['undelivered'] += 1 class", "f in fields) self.queue_tracker_db[ID]['client_email'] = client_email elif len(fields) == 3:", "of 'receivers' whose 'status' == 1 and store it in", "('client_email', <email>)]; [('ID', <id>), ('receivers', <email>), ('status', <status>)]; [('ID', <id>)];", "num_of_letters_sent INTEGER)''') def transfer_data(self): for email, num_of_letters in self.email_tracker_db.items(): self._execute_command('''INSERT", "= path super().__init__(*args, **kwargs) def _execute_command(self, *command): con = sqlite3.connect(self.path)", "email_tracker_db, delivery_tracker_db): self.queue_tracker_db = queue_tracker_db self.email_tracker_db = email_tracker_db self.delivery_tracker_db =", "TABLE IF NOT EXISTS email_tracker (client_email TEXT PRIMARY KEY, num_of_letters_sent", "path super().__init__(*args, **kwargs) def _execute_command(self, *command): con = sqlite3.connect(self.path) cursor", "<queue_tracker_db> accordingly. \"\"\" if len(fields) == 1: ID = fields[0][1]", "with the amount of 'receivers' whose 'status' == 1 and", "def manage_delivery_tracker(self, ID): \"\"\" Go through all receivers of <ID>", "def create_db(self): self._execute_command('''CREATE TABLE IF NOT EXISTS email_tracker (client_email TEXT", "by <ID> with the amount of 'receivers' whose 'status' ==", "ID): \"\"\" Retrieve client's email from the <queue_tracker_db> by <ID>", "and store it in the <email_tracker_db>. \"\"\" client_email = self.queue_tracker_db[ID]['client_email']", "through all receivers of <ID> queue of <queue_tracker_db>, and add", "if receivers[receiver] == 1: self.delivery_tracker_db['delivered'] += 1 else: self.delivery_tracker_db['undelivered'] +=", "= sqlite3.connect(self.path) cursor = con.cursor() result = cursor.execute(*command) if result:", "client_email elif len(fields) == 3: ID, receiver, status = (f[1]", "receivers[receiver] == 1: self.delivery_tracker_db['delivered'] += 1 else: self.delivery_tracker_db['undelivered'] += 1", "the amount of 'receivers' whose 'status' == 1 and store", "= (f[1] for f in fields) if status == 'sent':", "path, *args, **kwargs): self.path = path super().__init__(*args, **kwargs) def _execute_command(self,", "of the following located groups as <fields>: [('ID', <id>), ('client_email',", "cursor.execute(*command) if result: result = result.fetchall() con.commit() con.close() return result", "result.fetchall() con.commit() con.close() return result def create_db(self): self._execute_command('''CREATE TABLE IF", "1: self.delivery_tracker_db['delivered'] += 1 else: self.delivery_tracker_db['undelivered'] += 1 class ManageDatabase(ManageData):", "<id>)]; and manage the <queue_tracker_db> accordingly. \"\"\" if len(fields) ==", "= (f[1] for f in fields) self.queue_tracker_db[ID]['client_email'] = client_email elif", "client_email = (f[1] for f in fields) self.queue_tracker_db[ID]['client_email'] = client_email", "== 'sent': code = 1 else: code = 0 self.queue_tracker_db[ID]['receivers'][receiver]", "self.queue_tracker_db[ID]['receivers'] for receiver in receivers: if receivers[receiver] == 1: self.delivery_tracker_db['delivered']", "receivers: if receivers[receiver] == 1: self.delivery_tracker_db['delivered'] += 1 else: self.delivery_tracker_db['undelivered']", "status == 'sent': code = 1 else: code = 0", "('status', <status>)]; [('ID', <id>)]; and manage the <queue_tracker_db> accordingly. \"\"\"", "\"\"\" client_email = self.queue_tracker_db[ID]['client_email'] receivers = self.queue_tracker_db[ID]['receivers'] delivered_mail = [r", "self.email_tracker_db[client_email] += len(delivered_mail) else: self.email_tracker_db[client_email] = len(delivered_mail) def manage_delivery_tracker(self, ID):", "= len(delivered_mail) def manage_delivery_tracker(self, ID): \"\"\" Go through all receivers", "\"\"\" if len(fields) == 1: ID = fields[0][1] self.manage_email_tracker(ID) self.manage_delivery_tracker(ID)", "whose 'status' == 1 and store it in the <email_tracker_db>.", "groups as <fields>: [('ID', <id>), ('client_email', <email>)]; [('ID', <id>), ('receivers',", "<ID> queue of <queue_tracker_db>, and add their delivery statuses to", "TEXT PRIMARY KEY, num_of_letters_sent INTEGER)''') def transfer_data(self): for email, num_of_letters", "== 1] if client_email in self.email_tracker_db: self.email_tracker_db[client_email] += len(delivered_mail) else:", "code = 1 else: code = 0 self.queue_tracker_db[ID]['receivers'][receiver] = code", "len(delivered_mail) else: self.email_tracker_db[client_email] = len(delivered_mail) def manage_delivery_tracker(self, ID): \"\"\" Go", "con.commit() con.close() return result def create_db(self): self._execute_command('''CREATE TABLE IF NOT", "<fields>: [('ID', <id>), ('client_email', <email>)]; [('ID', <id>), ('receivers', <email>), ('status',", "def manage_queue_tracker(self, fields): \"\"\" Receive one of the following located", "<ID> with the amount of 'receivers' whose 'status' == 1", "for f in fields) if status == 'sent': code =", "receiver in receivers: if receivers[receiver] == 1: self.delivery_tracker_db['delivered'] += 1", "f in fields) if status == 'sent': code = 1", "def transfer_data(self): for email, num_of_letters in self.email_tracker_db.items(): self._execute_command('''INSERT INTO email_tracker", "'receivers' whose 'status' == 1 and store it in the", "email_tracker_db self.delivery_tracker_db = delivery_tracker_db def manage_queue_tracker(self, fields): \"\"\" Receive one", "to the <delivery_tracker_db> counter \"\"\" receivers = self.queue_tracker_db[ID]['receivers'] for receiver", "\"\"\" receivers = self.queue_tracker_db[ID]['receivers'] for receiver in receivers: if receivers[receiver]", "sqlite3.connect(self.path) cursor = con.cursor() result = cursor.execute(*command) if result: result", "1 else: code = 0 self.queue_tracker_db[ID]['receivers'][receiver] = code def manage_email_tracker(self,", "self.delivery_tracker_db['undelivered'] += 1 class ManageDatabase(ManageData): def __init__(self, path, *args, **kwargs):", "def __init__(self, queue_tracker_db, email_tracker_db, delivery_tracker_db): self.queue_tracker_db = queue_tracker_db self.email_tracker_db =", "and add their delivery statuses to the <delivery_tracker_db> counter \"\"\"", "ManageDatabase(ManageData): def __init__(self, path, *args, **kwargs): self.path = path super().__init__(*args,", "= con.cursor() result = cursor.execute(*command) if result: result = result.fetchall()", "queue_tracker_db self.email_tracker_db = email_tracker_db self.delivery_tracker_db = delivery_tracker_db def manage_queue_tracker(self, fields):", "status = (f[1] for f in fields) if status ==", "Go through all receivers of <ID> queue of <queue_tracker_db>, and", "== 2: ID, client_email = (f[1] for f in fields)", "self._execute_command('''CREATE TABLE IF NOT EXISTS email_tracker (client_email TEXT PRIMARY KEY,", "the <email_tracker_db>. \"\"\" client_email = self.queue_tracker_db[ID]['client_email'] receivers = self.queue_tracker_db[ID]['receivers'] delivered_mail", "= [r for r in receivers if receivers[r] == 1]", "= client_email elif len(fields) == 3: ID, receiver, status =", "ManageData: def __init__(self, queue_tracker_db, email_tracker_db, delivery_tracker_db): self.queue_tracker_db = queue_tracker_db self.email_tracker_db", "manage_queue_tracker(self, fields): \"\"\" Receive one of the following located groups", "EXISTS email_tracker (client_email TEXT PRIMARY KEY, num_of_letters_sent INTEGER)''') def transfer_data(self):", "fields) self.queue_tracker_db[ID]['client_email'] = client_email elif len(fields) == 3: ID, receiver,", "<queue_tracker_db> by <ID> with the amount of 'receivers' whose 'status'", "self.manage_delivery_tracker(ID) del self.queue_tracker_db[ID] elif len(fields) == 2: ID, client_email =", "counter \"\"\" receivers = self.queue_tracker_db[ID]['receivers'] for receiver in receivers: if", "create_db(self): self._execute_command('''CREATE TABLE IF NOT EXISTS email_tracker (client_email TEXT PRIMARY", "Retrieve client's email from the <queue_tracker_db> by <ID> with the", "class ManageData: def __init__(self, queue_tracker_db, email_tracker_db, delivery_tracker_db): self.queue_tracker_db = queue_tracker_db", "result def create_db(self): self._execute_command('''CREATE TABLE IF NOT EXISTS email_tracker (client_email", "<status>)]; [('ID', <id>)]; and manage the <queue_tracker_db> accordingly. \"\"\" if", "(f[1] for f in fields) if status == 'sent': code", "INTEGER)''') def transfer_data(self): for email, num_of_letters in self.email_tracker_db.items(): self._execute_command('''INSERT INTO", "== 3: ID, receiver, status = (f[1] for f in", "receivers[r] == 1] if client_email in self.email_tracker_db: self.email_tracker_db[client_email] += len(delivered_mail)", "= 0 self.queue_tracker_db[ID]['receivers'][receiver] = code def manage_email_tracker(self, ID): \"\"\" Retrieve", "cursor = con.cursor() result = cursor.execute(*command) if result: result =", "else: code = 0 self.queue_tracker_db[ID]['receivers'][receiver] = code def manage_email_tracker(self, ID):", "== 1: ID = fields[0][1] self.manage_email_tracker(ID) self.manage_delivery_tracker(ID) del self.queue_tracker_db[ID] elif", "Receive one of the following located groups as <fields>: [('ID',", "1] if client_email in self.email_tracker_db: self.email_tracker_db[client_email] += len(delivered_mail) else: self.email_tracker_db[client_email]", "len(delivered_mail) def manage_delivery_tracker(self, ID): \"\"\" Go through all receivers of", "elif len(fields) == 2: ID, client_email = (f[1] for f", "ID, receiver, status = (f[1] for f in fields) if", "the <queue_tracker_db> by <ID> with the amount of 'receivers' whose", "else: self.email_tracker_db[client_email] = len(delivered_mail) def manage_delivery_tracker(self, ID): \"\"\" Go through", "receiver, status = (f[1] for f in fields) if status", "and manage the <queue_tracker_db> accordingly. \"\"\" if len(fields) == 1:", "def manage_email_tracker(self, ID): \"\"\" Retrieve client's email from the <queue_tracker_db>", "code def manage_email_tracker(self, ID): \"\"\" Retrieve client's email from the", "from the <queue_tracker_db> by <ID> with the amount of 'receivers'", "[r for r in receivers if receivers[r] == 1] if", "it in the <email_tracker_db>. \"\"\" client_email = self.queue_tracker_db[ID]['client_email'] receivers =", "store it in the <email_tracker_db>. \"\"\" client_email = self.queue_tracker_db[ID]['client_email'] receivers", "self.delivery_tracker_db['delivered'] += 1 else: self.delivery_tracker_db['undelivered'] += 1 class ManageDatabase(ManageData): def", "ID = fields[0][1] self.manage_email_tracker(ID) self.manage_delivery_tracker(ID) del self.queue_tracker_db[ID] elif len(fields) ==", "manage_delivery_tracker(self, ID): \"\"\" Go through all receivers of <ID> queue", "*args, **kwargs): self.path = path super().__init__(*args, **kwargs) def _execute_command(self, *command):", "[('ID', <id>), ('receivers', <email>), ('status', <status>)]; [('ID', <id>)]; and manage", "the <delivery_tracker_db> counter \"\"\" receivers = self.queue_tracker_db[ID]['receivers'] for receiver in", "as <fields>: [('ID', <id>), ('client_email', <email>)]; [('ID', <id>), ('receivers', <email>),", "following located groups as <fields>: [('ID', <id>), ('client_email', <email>)]; [('ID',", "delivered_mail = [r for r in receivers if receivers[r] ==", "self.email_tracker_db = email_tracker_db self.delivery_tracker_db = delivery_tracker_db def manage_queue_tracker(self, fields): \"\"\"", "<queue_tracker_db>, and add their delivery statuses to the <delivery_tracker_db> counter", "self.path = path super().__init__(*args, **kwargs) def _execute_command(self, *command): con =", "delivery_tracker_db): self.queue_tracker_db = queue_tracker_db self.email_tracker_db = email_tracker_db self.delivery_tracker_db = delivery_tracker_db", "fields) if status == 'sent': code = 1 else: code", "= self.queue_tracker_db[ID]['receivers'] for receiver in receivers: if receivers[receiver] == 1:", "in self.email_tracker_db: self.email_tracker_db[client_email] += len(delivered_mail) else: self.email_tracker_db[client_email] = len(delivered_mail) def", "manage the <queue_tracker_db> accordingly. \"\"\" if len(fields) == 1: ID", "2: ID, client_email = (f[1] for f in fields) self.queue_tracker_db[ID]['client_email']", "code = 0 self.queue_tracker_db[ID]['receivers'][receiver] = code def manage_email_tracker(self, ID): \"\"\"", "_execute_command(self, *command): con = sqlite3.connect(self.path) cursor = con.cursor() result =", "NOT EXISTS email_tracker (client_email TEXT PRIMARY KEY, num_of_letters_sent INTEGER)''') def", "(client_email TEXT PRIMARY KEY, num_of_letters_sent INTEGER)''') def transfer_data(self): for email,", "transfer_data(self): for email, num_of_letters in self.email_tracker_db.items(): self._execute_command('''INSERT INTO email_tracker VALUES", "= self.queue_tracker_db[ID]['client_email'] receivers = self.queue_tracker_db[ID]['receivers'] delivered_mail = [r for r", "0 self.queue_tracker_db[ID]['receivers'][receiver] = code def manage_email_tracker(self, ID): \"\"\" Retrieve client's", "IF NOT EXISTS email_tracker (client_email TEXT PRIMARY KEY, num_of_letters_sent INTEGER)''')", "super().__init__(*args, **kwargs) def _execute_command(self, *command): con = sqlite3.connect(self.path) cursor =", "delivery statuses to the <delivery_tracker_db> counter \"\"\" receivers = self.queue_tracker_db[ID]['receivers']", "result: result = result.fetchall() con.commit() con.close() return result def create_db(self):", "= 1 else: code = 0 self.queue_tracker_db[ID]['receivers'][receiver] = code def", "'status' == 1 and store it in the <email_tracker_db>. \"\"\"", "else: self.delivery_tracker_db['undelivered'] += 1 class ManageDatabase(ManageData): def __init__(self, path, *args,", "1 class ManageDatabase(ManageData): def __init__(self, path, *args, **kwargs): self.path =", "= cursor.execute(*command) if result: result = result.fetchall() con.commit() con.close() return", "for f in fields) self.queue_tracker_db[ID]['client_email'] = client_email elif len(fields) ==", "ID, client_email = (f[1] for f in fields) self.queue_tracker_db[ID]['client_email'] =", "self.queue_tracker_db[ID]['client_email'] receivers = self.queue_tracker_db[ID]['receivers'] delivered_mail = [r for r in", "email from the <queue_tracker_db> by <ID> with the amount of", "the following located groups as <fields>: [('ID', <id>), ('client_email', <email>)];", "= queue_tracker_db self.email_tracker_db = email_tracker_db self.delivery_tracker_db = delivery_tracker_db def manage_queue_tracker(self,", "self.queue_tracker_db[ID]['receivers'][receiver] = code def manage_email_tracker(self, ID): \"\"\" Retrieve client's email", "__init__(self, path, *args, **kwargs): self.path = path super().__init__(*args, **kwargs) def", "r in receivers if receivers[r] == 1] if client_email in" ]
[ "* fake_img.shape[3] ) grad, = autograd.grad( outputs=(fake_img * noise).sum(), inputs=latents,", "latents, mean_path_length, decay=0.01): noise = torch.randn_like(fake_img) / math.sqrt( fake_img.shape[2] *", "math def g_path_regularize(fake_img, latents, mean_path_length, decay=0.01): noise = torch.randn_like(fake_img) /", "mean_path_length + decay * (path_lengths.mean() - mean_path_length) path_penalty = (path_lengths", ") path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1)) path_mean = mean_path_length + decay *", "noise = torch.randn_like(fake_img) / math.sqrt( fake_img.shape[2] * fake_img.shape[3] ) grad,", "grad, = autograd.grad( outputs=(fake_img * noise).sum(), inputs=latents, create_graph=True ) path_lengths", "g_path_regularize(fake_img, latents, mean_path_length, decay=0.01): noise = torch.randn_like(fake_img) / math.sqrt( fake_img.shape[2]", "mean_path_length, decay=0.01): noise = torch.randn_like(fake_img) / math.sqrt( fake_img.shape[2] * fake_img.shape[3]", ") grad, = autograd.grad( outputs=(fake_img * noise).sum(), inputs=latents, create_graph=True )", "decay=0.01): noise = torch.randn_like(fake_img) / math.sqrt( fake_img.shape[2] * fake_img.shape[3] )", "autograd.grad( outputs=(fake_img * noise).sum(), inputs=latents, create_graph=True ) path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1))", "path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1)) path_mean = mean_path_length + decay * (path_lengths.mean()", "math.sqrt( fake_img.shape[2] * fake_img.shape[3] ) grad, = autograd.grad( outputs=(fake_img *", "torch.sqrt(grad.pow(2).sum(2).mean(1)) path_mean = mean_path_length + decay * (path_lengths.mean() - mean_path_length)", "= autograd.grad( outputs=(fake_img * noise).sum(), inputs=latents, create_graph=True ) path_lengths =", "- mean_path_length) path_penalty = (path_lengths - path_mean).pow(2).mean() return path_penalty, path_mean.detach(),", "torch.randn_like(fake_img) / math.sqrt( fake_img.shape[2] * fake_img.shape[3] ) grad, = autograd.grad(", "(path_lengths.mean() - mean_path_length) path_penalty = (path_lengths - path_mean).pow(2).mean() return path_penalty,", "/ math.sqrt( fake_img.shape[2] * fake_img.shape[3] ) grad, = autograd.grad( outputs=(fake_img", "import math def g_path_regularize(fake_img, latents, mean_path_length, decay=0.01): noise = torch.randn_like(fake_img)", "path_mean = mean_path_length + decay * (path_lengths.mean() - mean_path_length) path_penalty", "= torch.sqrt(grad.pow(2).sum(2).mean(1)) path_mean = mean_path_length + decay * (path_lengths.mean() -", "create_graph=True ) path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1)) path_mean = mean_path_length + decay", "* (path_lengths.mean() - mean_path_length) path_penalty = (path_lengths - path_mean).pow(2).mean() return", "fake_img.shape[3] ) grad, = autograd.grad( outputs=(fake_img * noise).sum(), inputs=latents, create_graph=True", "mean_path_length) path_penalty = (path_lengths - path_mean).pow(2).mean() return path_penalty, path_mean.detach(), path_lengths", "outputs=(fake_img * noise).sum(), inputs=latents, create_graph=True ) path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1)) path_mean", "noise).sum(), inputs=latents, create_graph=True ) path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1)) path_mean = mean_path_length", "= mean_path_length + decay * (path_lengths.mean() - mean_path_length) path_penalty =", "= torch.randn_like(fake_img) / math.sqrt( fake_img.shape[2] * fake_img.shape[3] ) grad, =", "+ decay * (path_lengths.mean() - mean_path_length) path_penalty = (path_lengths -", "fake_img.shape[2] * fake_img.shape[3] ) grad, = autograd.grad( outputs=(fake_img * noise).sum(),", "inputs=latents, create_graph=True ) path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1)) path_mean = mean_path_length +", "* noise).sum(), inputs=latents, create_graph=True ) path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1)) path_mean =", "decay * (path_lengths.mean() - mean_path_length) path_penalty = (path_lengths - path_mean).pow(2).mean()", "def g_path_regularize(fake_img, latents, mean_path_length, decay=0.01): noise = torch.randn_like(fake_img) / math.sqrt(" ]
[ "AS AN ENVIRONMENT VARIABLE IN PROD SECRET_KEY = \"dev\" ########################################################", "#Neo4j Database URI used by the Neomodel OGM ## THIS", "PROD SECRET_KEY = \"dev\" ######################################################## DATABSE SETTINGS #################################################### #Neo4j Database", "= \"dev\" ######################################################## DATABSE SETTINGS #################################################### #Neo4j Database URI used", "URI used by the Neomodel OGM ## THIS SHOULD BE", "BUT SHOULD BE SET AS AN ENVIRONMENT VARIABLE IN PROD", "SHOULD BE SET AS AN ENVIRONMENT VARIABLE IN PRODUCTION ##", "CONVENIENCE BUT SHOULD BE SET AS AN ENVIRONMENT VARIABLE IN", "\"dev\" ######################################################## DATABSE SETTINGS #################################################### #Neo4j Database URI used by", "##THIS IS SET IN DEV ENVIRONMENT FOR CONVENIENCE BUT SHOULD", "SHOULD BE SET AS AN ENVIRONMENT VARIABLE IN PROD SECRET_KEY", "## THIS SHOULD BE SET AS AN ENVIRONMENT VARIABLE IN", "SETTINGS #################################################### #Neo4j Database URI used by the Neomodel OGM", "Neomodel OGM ## THIS SHOULD BE SET AS AN ENVIRONMENT", "#################################################### #Neo4j Database URI used by the Neomodel OGM ##", "FLASK SETTINGS ############################################################## #Variable used to securly sign cookies ##THIS", "IN DEV ENVIRONMENT FOR CONVENIENCE BUT SHOULD BE SET AS", "AN ENVIRONMENT VARIABLE IN PROD SECRET_KEY = \"dev\" ######################################################## DATABSE", "OGM ## THIS SHOULD BE SET AS AN ENVIRONMENT VARIABLE", "SECRET_KEY = \"dev\" ######################################################## DATABSE SETTINGS #################################################### #Neo4j Database URI", "<gh_stars>0 ######################################################## FLASK SETTINGS ############################################################## #Variable used to securly sign", "############################################################## #Variable used to securly sign cookies ##THIS IS SET", "IS SET IN DEV ENVIRONMENT FOR CONVENIENCE BUT SHOULD BE", "SET AS AN ENVIRONMENT VARIABLE IN PRODUCTION ## DATABASE_URI =", "by the Neomodel OGM ## THIS SHOULD BE SET AS", "DATABSE SETTINGS #################################################### #Neo4j Database URI used by the Neomodel", "sign cookies ##THIS IS SET IN DEV ENVIRONMENT FOR CONVENIENCE", "#Variable used to securly sign cookies ##THIS IS SET IN", "Database URI used by the Neomodel OGM ## THIS SHOULD", "ENVIRONMENT FOR CONVENIENCE BUT SHOULD BE SET AS AN ENVIRONMENT", "VARIABLE IN PROD SECRET_KEY = \"dev\" ######################################################## DATABSE SETTINGS ####################################################", "FOR CONVENIENCE BUT SHOULD BE SET AS AN ENVIRONMENT VARIABLE", "######################################################## DATABSE SETTINGS #################################################### #Neo4j Database URI used by the", "ENVIRONMENT VARIABLE IN PROD SECRET_KEY = \"dev\" ######################################################## DATABSE SETTINGS", "DEV ENVIRONMENT FOR CONVENIENCE BUT SHOULD BE SET AS AN", "SET IN DEV ENVIRONMENT FOR CONVENIENCE BUT SHOULD BE SET", "BE SET AS AN ENVIRONMENT VARIABLE IN PRODUCTION ## DATABASE_URI", "securly sign cookies ##THIS IS SET IN DEV ENVIRONMENT FOR", "IN PROD SECRET_KEY = \"dev\" ######################################################## DATABSE SETTINGS #################################################### #Neo4j", "THIS SHOULD BE SET AS AN ENVIRONMENT VARIABLE IN PRODUCTION", "SETTINGS ############################################################## #Variable used to securly sign cookies ##THIS IS", "cookies ##THIS IS SET IN DEV ENVIRONMENT FOR CONVENIENCE BUT", "SET AS AN ENVIRONMENT VARIABLE IN PROD SECRET_KEY = \"dev\"", "the Neomodel OGM ## THIS SHOULD BE SET AS AN", "used to securly sign cookies ##THIS IS SET IN DEV", "AS AN ENVIRONMENT VARIABLE IN PRODUCTION ## DATABASE_URI = \"bolt://test:test@localhost:7687\"", "######################################################## FLASK SETTINGS ############################################################## #Variable used to securly sign cookies", "to securly sign cookies ##THIS IS SET IN DEV ENVIRONMENT", "used by the Neomodel OGM ## THIS SHOULD BE SET", "BE SET AS AN ENVIRONMENT VARIABLE IN PROD SECRET_KEY =" ]
[ "distance is larger, use the ratio of radial distances to", "1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixel_centres_2d = grid_pixel_centres_2d_from(grid_scaled_2d=grid_scaled_2d,", "the grid, which the scaled grid is shifted Returns -------", "= int( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1]) + centres_scaled[1] + 0.5", "np.ndarray The native grid of 2D (y,x) coordinates in scaled", "radial distances to move the coordinate to the border (if", ") upscale_index = 0 y_upscale_half = pixel_scales[0] / 2 y_upscale_step", "grid_2d_via_shape_native_from(shape_native=(3, 3), pixel_scales=(1.0, 1.0), sub_size=2, origin=(0.0, 0.0)) \"\"\" return grid_2d_via_mask_from(", "/ negative y and x axes). 2) Use the pixel-scale", "= geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for y in range(grid_scaled_2d.shape[0]):", "------------------- Using the centre x above, this function finds the", "= points[:, 1] y = points[:, 0] return 0.5 *", "Pixel coordinates are returned as floats such that they include", "False, True], [False, False, False] [True, False, True]]) grid_2d =", "origin=(0.0, 0.0)) \"\"\" total_sub_pixels = mask_2d_util.total_sub_pixels_2d_from(mask_2d, sub_size) grid_slim = np.zeros(shape=(total_sub_pixels,", "pixel_scales=pixel_scales, origin=origin ) for y in range(grid_scaled_2d.shape[0]): for x in", "> border_min_radii: closest_pixel_index = np.argmin( np.square(grid[pixel_index, 0] - border_grid[:, 0])", "coordinates by the input `angle` clockwise. A schematric is shown", "the 2D grid will correspond to index 1 of the", "their 1D grid pixel indexes. Parameters ---------- grid_scaled_2d: np.ndarray The", ") -> np.ndarray: \"\"\" For a slimmed 2D grid of", "shape (total_pixels, 2). The pixel coordinate origin is at the", "grid_pixels_2d_slim = np.array([[0,0], [0,1], [1,0], [1,1]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_pixels_2d_slim=grid_pixels_2d_slim, shape=(2,2),", "a native grid of 2D (y,x) scaled coordinates to a", "the radial distance of every grid coordinate from the origin.", "y_inside = [] x_inside = [] for i in range(len(grid_2d[:,", "def grid_pixels_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float,", "2, 2) ) upscale_index = 0 y_upscale_half = pixel_scales[0] /", "pixel unmasked pixel on the 2D mask array. The sub", "is shifted. Returns ------- ndarray A slimmed grid of 2d", "next sub-pixel has index 2, and so forth. Parameters ----------", "upscale_factor The upscaled resolution at which the new grid coordinates", "(scaled_distance == distance_to_positive_y) or ( scaled_distance == distance_to_negative_y ): pixel_scale", "border, where the border is defined as all pixels at", "of the 2D grid will correspond to index 1 of", "ndarray A sub grid of (y,x) scaled coordinates at the", "pixel on the 2D mask array. The sub grid array", "Returns the centre of a grid from a 1D grid.", "indexes with dimensions (y_pixels, x_pixels, 2). Examples -------- grid_scaled_2d =", "Convert a native grid of 2D (y,x) scaled coordinates to", "Sub-pixels that are part of the same mask array pixel", "2 y_upscale_step = pixel_scales[0] / upscale_factor x_upscale_half = pixel_scales[1] /", "sub_size=sub_size, origin=origin ) return grid_2d_native_from( grid_2d_slim=grid_2d_slim, mask_2d=mask_2d, sub_size=sub_size ) def", "nothing). The method can be used on uniform or irregular", "indexes with dimensions (total_pixels,). Examples -------- grid_scaled_2d_slim = np.array([[1.0, 1.0],", "clockwise. A schematric is shown below: ------------------- | | |<-", "into. shape_slim Manually choose the shape of the 1D projected", "grid going rights and then downwards. The input and output", "\"\"\" For a native 2D grid and mask of shape", "upscale_index += 1 return grid_2d_slim_upscaled def grid_2d_of_points_within_radius( radius: float, centre:", "cannot be used as a default value). Returns ------- ndarray", "grid is computed using, with format [xmin, xmax, ymin, ymax]", "4.0]]) grid_pixel_indexes_2d_slim = grid_pixel_indexes_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\"", "= np.mean(border_grid[:, 0]) border_origin[1] = np.mean(border_grid[:, 1]) border_grid_radii = np.sqrt(", "array_2d_native=grid_2d_native[:, :, 0], mask_2d=mask, sub_size=sub_size ) grid_1d_slim_x = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:,", "coordinate from the origin. 3: For every coordinate, find its", "not mask_2d[y, x]: y_scaled = (y - centres_scaled[0]) * pixel_scales[0]", "grid_radii[pixel_index] ) if move_factor < 1.0: grid_relocated[pixel_index, :] = (", "distance_to_positive_x, distance_to_positive_y, distance_to_negative_x, distance_to_negative_y, ] ) if (scaled_distance == distance_to_positive_y)", "ndarray A slimmed grid of 2d scaled coordinates with dimensions", "in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = ( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0])", "| | <-> = longest radial path from centre to", "if (grid_2d[i, 0] - centre[0]) ** 2 + ( grid_2d[i,", "of bools, where `False` values mean unmasked and are included", "np.zeros(shape=(total_sub_pixels, 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=mask_2d.shape, pixel_scales=pixel_scales, origin=origin ) sub_index", "increasing steps of the pixel-scale. 5) Rotate these radial coordinates", "2D mask array. The sub-grid is returned on an array", "where `False` values are unmasked and therefore included as part", ") -> np.ndarray: \"\"\" For a sub-grid, every unmasked pixel", "extent[3] - centre[0] distance_to_negative_x = centre[1] - extent[0] distance_to_negative_y =", "grid of 2D (y,x) coordinates in scaled units which is", "x above, this function finds the longest radial path to", "to a slimmed grid of 2D (y,x) scaled values. The", "as opposed to a 1D data structure so that it", "computing their 1D grid pixel coordinate values. Parameters ---------- grid_scaled_2d_slim:", "4 of the 1D grid. Parameters ---------- grid_2d_native : ndarray", "a grid to its border if they are outside the", "computed using, with format [xmin, xmax, ymin, ymax] centre :", "slimmed sub grid of (y,x) scaled coordinates at the centre", "0.0). Grids are defined from the top-left corner, where the", "grid's y and x coordinates to determine the origin of", ": Grid2D The grid (uniform or irregular) whose pixels are", "at an upscaled resolution to each grid coordinate, analogous to", "3), pixel_scales=(1.0, 1.0), sub_size=2, origin=(0.0, 0.0)) \"\"\" return grid_2d_via_mask_from( mask_2d=np.full(fill_value=False,", "= 0, ) -> np.ndarray: \"\"\" Determine a projected radial", "from the top-left corner, where the first unmasked sub-pixel corresponds", "coordinates are shifted to this origin after computing their values", "centres_scaled[0] + 0.5 ) grid_pixels_2d[y, x, 1] = int( (grid_scaled_2d[y,", "5) Rotate these radial coordinates by the input `angle` clockwise.", "sub_size=sub_size, origin=origin, ) @numba_util.jit() def grid_scaled_2d_slim_radial_projected_from( extent: np.ndarray, centre: Tuple[float,", "of the grid's y and x coordinates to determine the", "and mask of shape [total_y_pixels, total_x_pixels, 2], map the values", "array. The sub-grid is returned in its slimmed dimensions with", "is returned in its slimmed dimensions with shape (total_pixels**2*sub_size**2, 2).", "pixel on the second row, whose native index is [0,1],", "x = points[:, 1] y = points[:, 0] return 0.5", "extent of the grid the radii grid is computed using,", "the border, do nothing). The method can be used on", "+ (y_sub_step / 2.0) ) grid_slim[sub_index, 1] = ( x_scaled", "Union[float, Tuple[float, float]], sub_size: int, shape_slim: Optional[int] = 0, )", "the region defined by the extent [xmin, xmax, ymin, ymax],", "2.0 centre_x = (np.max(grid_2d_slim[:, 1]) + np.min(grid_2d_slim[:, 1])) / 2.0", "[total_y_pixels, total_x_pixels, 2], map the slimmed grid's coordinates back to", "set of points sampling the longest distance from the centre", "2). y coordinates are stored in the 0 index of", "that the second sub-pixel in the first pixel has index", ") sub_index = 0 y_sub_half = pixel_scales[0] / 2 y_sub_step", "= (0.0, 0.0), ) -> np.ndarray: \"\"\" Convert a slimmed", "The size of the sub-grid that each pixel of the", "the top row, whose native index is [0,5], corresponds to", "top left corner of the grid, such that the pixel", "the scaled grid is shifted Returns ------- ndarray A slimmed", "= centre[1] for slim_index in range(shape_slim): grid_scaled_2d_slim_radii[slim_index, 1] = radii", "A native grid of 2D (y,x) pixel indexes with dimensions", "Grid2D The grid (uniform or irregular) whose pixels are to", "(y,x) grid of radial points where all points are at", "whose pixels are to be relocated to the border edge", "def relocated_grid_via_jit_from(grid, border_grid): \"\"\" Relocate the coordinates of a grid", "np.array([[True, False, True], [False, False, False] [True, False, True]]) grid_slim", "points that in 1D sample the 2D grid outwards from", "0] - centres_scaled[0] - 0.5) * pixel_scales[0] ) grid_scaled_2d_slim[slim_index, 1]", "native grid of 2D (y,x) pixel indexes with dimensions (y_pixels,", "in 1D sample the 2D grid outwards from its centre.", "from typing import Tuple, Union, Optional from autoarray.structures.arrays.two_d import array_2d_util", "closest_pixel_index = np.argmin( np.square(grid[pixel_index, 0] - border_grid[:, 0]) + np.square(grid[pixel_index,", "index. Grid2D are defined from the top-left corner, where the", "which is converted to pixel indexes. shape_native The (y,x) shape", "a native 2D grid of shape [total_y_pixels, total_x_pixels, 2], map", "The (y,x) origin of the 2D array, which the sub-grid", "dimensions with shape (total_pixels**2*sub_size**2, 2). y coordinates are stored in", "origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim = grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim=grid_scaled_2d_slim, shape_native=shape_native, pixel_scales=pixel_scales, origin=origin,", "Masked pixels are given values (0.0, 0.0). Grids are defined", "the 1D grid. - pixel [1,0] of the 2D grid", "scaled units to pixel units conversion factor of the 2D", "[0,0] corresponds to the highest (most positive) y scaled coordinate", "the border of the 'image-plane' mask is used to define", "grid_2d_native_x), axis=-1) @numba_util.jit() def grid_2d_slim_upscaled_from( grid_slim: np.ndarray, upscale_factor: int, pixel_scales:", "pixel_scales[1]) + centres_scaled[1] + 0.5 ) return grid_pixels_2d_slim @numba_util.jit() def", "back to the native 2D grid where masked values are", "- (y_upscale_step / 2.0) ) grid_2d_slim_upscaled[upscale_index, 1] = ( x_grid", "to its border if they are outside the border, where", "2) ) upscale_index = 0 y_upscale_half = pixel_scales[0] / 2", "of a grid from a 1D grid. Parameters ---------- grid_2d_slim", ") if move_factor < 1.0: grid_relocated[pixel_index, :] = ( move_factor", "0. Sub-pixels that are part of the same mask array", "indexes. Pixel coordinates are returned as integers such that they", "the scaled grid is shifted. Returns ------- ndarray A slimmed", "shape [total_y_pixels, total_x_pixels, 2], map the values of all unmasked", "-------- grid_scaled_2d_slim = np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0,", "mapped to the native 2D grid. mask_2d A 2D array", "grid of 2D (y,x) scaled values. The input and output", "the origin to its paired border pixel's radial distance. 5:", "Determine a projected radial grid of points from a 2D", "np.ndarray The slimmed grid of (y,x) coordinates in pixel values", "True], [False, False, False] [True, False, True]]) grid_2d = grid_2d_via_mask_from(mask=mask,", "(total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- grid_2d = grid_2d_via_shape_native_from(shape_native=(3, 3), pixel_scales=(1.0, 1.0),", "of radial distances to move the coordinate to the border", "are added at an upscaled resolution to each grid coordinate,", "[3.0, 3.0], [4.0, 4.0]]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5),", "all pixels at the edge of the grid's mask (see", "- coordinate[0]) ** 2 if distance_to_centre_new >= distance_to_centre: distance_to_centre =", "0] x = grid_2d_slim[slim_index, 1] distance_to_centre_new = (x - coordinate[1])", "origin : (float, flloat) The (y,x) origin of the grid,", "+ np.min(grid_2d_slim[:, 0])) / 2.0 centre_x = (np.max(grid_2d_slim[:, 1]) +", "Tuple[float, float] = (0.0, 0.0), ) -> np.ndarray: \"\"\" For", "grid_scaled_2d_slim[slim_index, 1] = ( grid_pixels_2d_slim[slim_index, 1] - centres_scaled[1] - 0.5", "\"\"\" Relocate the coordinates of a grid to its border", "was computed by extracting the unmasked values from a native", "Parameters ---------- grid_slim The slimmed grid of (y,x) coordinates over", "positive / negative y and x axes). 2) Use the", "the input `angle` clockwise. A schematric is shown below: -------------------", "slim_index in range(grid_scaled_2d_slim.shape[0]): grid_scaled_2d_slim[slim_index, 0] = ( -(grid_pixels_2d_slim[slim_index, 0] -", "** 2 + (y - coordinate[0]) ** 2 if distance_to_centre_new", "ndarray A 1D grid of values mapped from the 2D", "if (scaled_distance == distance_to_positive_y) or ( scaled_distance == distance_to_negative_y ):", "and so forth. Parameters ---------- shape_native The (y,x) shape of", "+ 1 grid_scaled_2d_slim_radii = np.zeros((shape_slim, 2)) grid_scaled_2d_slim_radii[:, 0] += centre[0]", "shape_slim = sub_size * int((scaled_distance / pixel_scale)) + 1 grid_scaled_2d_slim_radii", "centre: Tuple[float, float], pixel_scales: Union[float, Tuple[float, float]], sub_size: int, shape_slim:", "of coordinates defined by an extent [xmin, xmax, ymin, ymax]", "grid of 2D (y,x) pixel values. Pixel coordinates are returned", "= ( -(grid_pixels_2d_slim[slim_index, 0] - centres_scaled[0] - 0.5) * pixel_scales[0]", "coordinates with dimensions (total_pixels, 2). Examples -------- grid_pixels_2d_slim = np.array([[0,0],", "(y,x) coordinates are added at an upscaled resolution to each", "extent [xmin, xmax, ymin, ymax], the algorithm finds the longest", "2D grid. - If slim_to_native[4] = [1,1], the fifth value", "grid_slim = grid_2d_slim_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\" total_sub_pixels", "above, this function finds the longest radial path to the", "grid of shape [total_unmasked_pixels, 2]. The pixel coordinate origin is", "is traced outwards from. pixel_scales The (y,x) scaled units to", "-------- mask = np.array([[True, False, True], [False, False, False] [True,", "of the 2D mask array is divided into. shape_slim Manually", "points from a 2D region of coordinates defined by an", "to be relocated to the border edge if outside it.", "if grid_radii[pixel_index] > border_min_radii: closest_pixel_index = np.argmin( np.square(grid[pixel_index, 0] -", "second value of the 1D array maps to the pixels", "x, 1] = int( (grid_scaled_2d[y, x, 1] / pixel_scales[1]) +", "pixel [0,1] of the 2D grid will correspond to index", "max( [ distance_to_positive_x, distance_to_positive_y, distance_to_negative_x, distance_to_negative_y, ] ) if (scaled_distance", "by an origin and coordinates are shifted to this origin", "to numba None cannot be used as a default value).", "pixel values. Pixel coordinates are returned as integers such that", "region of coordinates defined by an extent [xmin, xmax, ymin,", "shown below: ------------------- | | |<- - - - ->x", "used to define border pixels. Parameters ---------- grid : Grid2D", "defined by this 2D mask array. The sub-grid is returned", "mask array. The sub grid is slimmed and has dimensions", "grid pixel coordinate values. Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed", "geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index,", "slimmed grid. \"\"\" grid_2d_native_y = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 0], mask_2d=mask_2d, sub_size=sub_size", "shape (y_pixels, x_pixels, 2). The pixel coordinate origin is at", "are defined from the top-left corner, where the first unmasked", "np.ndarray: \"\"\" From an input slimmed 2D grid, return an", "native unmasked pixels, for example: - If slim_to_native[0] = [0,0],", "The sub grid is slimmed and has dimensions (total_unmasked_pixels*sub_size**2, 2).", "sub-pixel corresponds to index 0. Sub-pixels that are part of", "radius ** 2: y_inside.append(grid_2d[i, 0]) x_inside.append(grid_2d[i, 1]) return np.asarray(y_inside, x_inside)", "autoarray import numba_util from autoarray.mask import mask_2d_util @numba_util.jit() def grid_2d_centre_from(grid_2d_slim:", "row, whose native index is [0,5], corresponds to slimmed pixel", "x_upscale_half + x * x_upscale_step + (x_upscale_step / 2.0) )", "the first unmasked sub-pixel corresponds to index 0. Sub-pixels that", "0.0), ) -> np.ndarray: \"\"\" Convert a slimmed grid of", "(y,x) origin of the grid, which the scaled grid is", "origin before computing their 1D grid pixel indexes. The input", "grid, return an upscaled slimmed 2D grid where (y,x) coordinates", "range(grid_pixels_2d_slim.shape[0]): grid_pixel_indexes_2d_slim[slim_index] = int( grid_pixels_2d_slim[slim_index, 0] * shape_native[1] + grid_pixels_2d_slim[slim_index,", "the region using the longest path between the two chosen", ") def grid_2d_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]],", "for x1 in range(sub_size): grid_slim[sub_index, 0] = -( y_scaled -", "grid, which the scaled grid is shifted to. Returns -------", "of 2D (y,x) scaled coordinates to a native grid of", "pixels at the edge of the grid's mask (see *mask._border_1d_indexes*).", "corresponds to index [0,0]. Sub-pixels that are part of the", "1]) ) move_factor = ( border_grid_radii[closest_pixel_index] / grid_radii[pixel_index] ) if", "a 1D grid. Parameters ---------- grid_2d_slim The 1D grid of", "2D mask array is divided into. origin The (y,x) origin", "= int( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0]) + centres_scaled[0] + 0.5", "the coordinates of a grid to its border if they", "grid_2d: np.ndarray ): y_inside = [] x_inside = [] for", "0]) + np.square(grid[pixel_index, 1] - border_grid[:, 1]) ) move_factor =", "sub grid of (y,x) scaled coordinates at the centre of", "is returned. If 0, the border based on the 2D", "to slimmed pixel index 0. The fifth pixel on the", "2.0) ) upscale_index += 1 return grid_2d_slim_upscaled def grid_2d_of_points_within_radius( radius:", "converted to pixel value coordinates. shape_native The (y,x) shape of", "grid_scaled_2d_slim=grid_scaled_2d_slim, shape_native=shape_native, pixel_scales=pixel_scales, origin=origin, ) grid_pixel_indexes_2d_slim = np.zeros(grid_pixels_2d_slim.shape[0]) for slim_index", "mask array. The sub-grid is returned on an array of", "-> Tuple[float, float]: \"\"\" Returns the centre of a grid", "grid_scaled_2d_slim_radial_projected_from( extent: np.ndarray, centre: Tuple[float, float], pixel_scales: Union[float, Tuple[float, float]],", "shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_scaled_2d_slim = np.zeros((grid_pixels_2d_slim.shape[0], 2))", "contained within. The input and output grids are both native", "as all pixels at the edge of the grid's mask", "the grid, which the scaled grid is shifted to. Returns", "of 2D (y,x) pixel-value coordinates with dimensions (total_pixels, 2). Examples", "as np from typing import Tuple, Union, Optional from autoarray.structures.arrays.two_d", "of points from a 2D region of coordinates defined by", "in pixel values which is converted to scaled coordinates. shape_native", "2D (y,x) pixel indexes with dimensions (y_pixels, x_pixels, 2). Examples", "the values of all unmasked pixels to a slimmed grid", "If slim_to_native[4] = [1,1], the fifth value of the 1D", "= np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixels_2d_slim", "= grid_2d_slim_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\" total_sub_pixels =", "which the new grid coordinates are computed. pixel_scales The pixel", "* int((scaled_distance / pixel_scale)) + 1 grid_scaled_2d_slim_radii = np.zeros((shape_slim, 2))", "- y * y_upscale_step - (y_upscale_step / 2.0) ) grid_2d_slim_upscaled[upscale_index,", "grid of shape (total_y_pixels*sub_size, total_x_pixels*sub_size). This routine computes the (y,x)", "y_grid = grid_slim[slim_index, 0] x_grid = grid_slim[slim_index, 1] for y", "to this origin before computing their 1D grid pixel coordinate", "which is converted to scaled coordinates. shape_native The (y,x) shape", "edge of the extent in along the positive x-axis. \"\"\"", "= np.zeros((grid_scaled_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin )", "= mask_2d_util.total_sub_pixels_2d_from(mask_2d, sub_size) grid_slim = np.zeros(shape=(total_sub_pixels, 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from(", "pixel scale of the uniform grid that laid over the", "index 0. Sub-pixels that are part of the same mask", "x, 1] / pixel_scales[1]) + centres_scaled[1] + 0.5 ) return", "== distance_to_positive_y) or ( scaled_distance == distance_to_negative_y ): pixel_scale =", "np.zeros(2) border_origin[0] = np.mean(border_grid[:, 0]) border_origin[1] = np.mean(border_grid[:, 1]) border_grid_radii", ") sub_index += 1 return grid_slim def grid_2d_via_mask_from( mask_2d: np.ndarray,", "slimmed grid of 2d (y,x) pixel coordinate values. Pixel coordinates", "2D grid is used (due to numba None cannot be", "distance of every grid coordinate from the origin. 3: For", "has slimmed pixel index 10 if a row has 10", "slimmed pixel index 4. The first pixel on the second", "2: y_inside.append(grid_2d[i, 0]) x_inside.append(grid_2d[i, 1]) return np.asarray(y_inside, x_inside) def compute_polygon_area(points):", "returned as floats such that they include the decimal offset", "grid. Grid2D are defined from the top-left corner, where the", "the grid, which the scaled grid is shifted. Returns -------", "the slimmed grid. \"\"\" grid_2d_native_y = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 0], mask_2d=mask_2d,", "border edge if outside it. border_grid : Grid2D The grid", "of the grid, which the scaled grid is shifted. Returns", "distance_to_centre = 0.0 for slim_index in slim_indexes: y = grid_2d_slim[slim_index,", "- border_grid[:, 1]) ) move_factor = ( border_grid_radii[closest_pixel_index] / grid_radii[pixel_index]", "------- ndarray A native grid of 2D (y,x) pixel indexes", "coordinate on the gird. The scaled coordinate grid is defined", "2d (y,x) pixel coordinate values. Pixel coordinates are returned as", "np.square(np.subtract(border_grid[:, 1], border_origin[1])), ) ) border_min_radii = np.min(border_grid_radii) grid_radii =", "mask_2d=mask_2d, sub_size=sub_size ) return np.stack((grid_2d_native_y, grid_2d_native_x), axis=-1) @numba_util.jit() def grid_2d_slim_upscaled_from(", "included in the slimmed grid. Grid2D are defined from the", "in range(sub_size): grid_slim[sub_index, 0] = -( y_scaled - y_sub_half +", "the grid's y and x coordinates to determine the origin", "centre. This grid stores the radial coordinates as (y,x) values", "are the pixel from the top-left of the 2D grid", "*mask._border_1d_indexes*). This is performed as follows: 1: Use the mean", "as a default value). Returns ------- ndarray A radial set", "pixels sub-array. Returns ------- ndarray A 1D grid of values", "border (y,x) coordinates. \"\"\" grid_relocated = np.zeros(grid.shape) grid_relocated[:, :] =", "sub_index = 0 y_sub_half = pixel_scales[0] / 2 y_sub_step =", "shape_native The (y,x) shape of the 2D array the sub-grid", "in the slimmed grid. Grid2D are defined from the top-left", "array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 0], mask_2d=mask, sub_size=sub_size ) grid_1d_slim_x = array_2d_util.array_2d_slim_from(", "1] - centres_scaled[1] - 0.5 ) * pixel_scales[1] return grid_scaled_2d_slim", "of shape [total_y_pixels, total_x_pixels, 2], map the slimmed grid's coordinates", "np.min(grid_2d_slim[:, 1])) / 2.0 return centre_y, centre_x @numba_util.jit() def grid_2d_slim_via_mask_from(", "1D array maps to the pixels [1,1,:] of the native", "np.zeros(grid_pixels_2d_slim.shape[0]) for slim_index in range(grid_pixels_2d_slim.shape[0]): grid_pixel_indexes_2d_slim[slim_index] = int( grid_pixels_2d_slim[slim_index, 0]", "def grid_scaled_2d_slim_from( grid_pixels_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float,", "radial set of points sampling the longest distance from the", "are to be relocated to the border edge if outside", ") grid_1d_slim_x = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 1], mask_2d=mask, sub_size=sub_size )", "mask_2d=mask, sub_size=sub_size ) return np.stack((grid_1d_slim_y, grid_1d_slim_x), axis=-1) def grid_2d_native_from( grid_2d_slim:", "coordinates with dimensions (total_pixels, 2). Examples -------- grid_scaled_2d_slim = np.array([[1.0,", "included in the mapping. sub_size The size (sub_size x sub_size)", "same) as opposed to a 1D data structure so that", "are unmasked and therefore included as part of the calculated", "(due to numba None cannot be used as a default", "2d scaled coordinates with dimensions (total_pixels, 2). Examples -------- grid_pixels_2d_slim", "grid_2d_slim: np.ndarray, slim_indexes: np.ndarray, coordinate: Tuple[float, float] ) -> int:", "Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed grid of 2D (y,x)", "mask_2d: np.ndarray, sub_size: int ) -> np.ndarray: \"\"\" For a", "the native 2D grid where masked values are set to", "output grids are both native resolution and therefore have shape", "grid where (y,x) coordinates are added at an upscaled resolution", "0.0), ) -> np.ndarray: \"\"\" For a sub-grid, every unmasked", "shape (total_unmasked_pixels*sub_size**2, 2). y coordinates are stored in the 0", "are both slimmed and have shapes (total_pixels, 2) and (total_pixels,).", "a slimmed grid of 2D (y,x) pixel values. Pixel coordinates", "total_x_pixels*sub_size). Examples -------- mask = np.array([[True, False, True], [False, False,", "grid is shifted. Returns ------- ndarray A grid of slimmed", "np.array([[True, False, True], [False, False, False] [True, False, True]]) grid_2d_slim", "grid. \"\"\" grid_2d_native_y = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 0], mask_2d=mask_2d, sub_size=sub_size )", "grid_2d_native: np.ndarray, mask: np.ndarray, sub_size: int ) -> np.ndarray: \"\"\"", "the number of pixels between the centre and the edge", "indexes. Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed grid of 2D", "extent[1] - centre[1] distance_to_positive_y = extent[3] - centre[0] distance_to_negative_x =", "'slim_to_native' where each index gives the 2D pixel indexes of", "= ( border_grid_radii[closest_pixel_index] / grid_radii[pixel_index] ) if move_factor < 1.0:", "at the top left corner of the native grid and", "radial coordinates by the input `angle` clockwise. A schematric is", "[False, False, False] [True, False, True]]) grid_slim = grid_2d_slim_via_mask_from(mask=mask, pixel_scales=(0.5,", ") move_factor = ( border_grid_radii[closest_pixel_index] / grid_radii[pixel_index] ) if move_factor", "grid of shape [total_y_pixels, total_x_pixels, 2], map the slimmed grid's", "are stored in the 0 index of the second dimension,", "grid. - If slim_to_native[4] = [1,1], the fifth value of", "therefore shape (total_pixels, 2). The pixel coordinate origin is at", "= 0.0 and the x values iterate from the centre", "Rotate these radial coordinates by the input `angle` clockwise. A", "sub-grid of coordinates is computed for. pixel_scales The (y,x) scaled", "laid over the irregular grid of (y,x) coordinates. \"\"\" grid_2d_slim_upscaled", "[0,1], has slimmed pixel index 10 if a row has", "coordinates defined by an extent [xmin, xmax, ymin, ymax] and", "is shown below: ------------------- | | |<- - - -", "1] / pixel_scales[1]) + centres_scaled[1] + 0.5 ) return grid_pixels_2d_slim", "grid of 2D (y,x) scaled coordinates to a slimmed grid", "slim_indexes: np.ndarray, coordinate: Tuple[float, float] ) -> int: distance_to_centre =", "| ------------------- Using the centre x above, this function finds", "0.0), ) -> np.ndarray: \"\"\" Convert a native grid of", "grid's coordinates back to the native 2D grid where masked", "of 2d (y,x) pixel coordinate values. Pixel coordinates are returned", "= np.sqrt( np.add( np.square(np.subtract(grid[:, 0], border_origin[0])), np.square(np.subtract(grid[:, 1], border_origin[1])), )", "origin after computing their values from the 1D grid pixel", "np.ndarray, coordinate: Tuple[float, float] ) -> int: distance_to_centre = 0.0", "in the mapping. sub_size The size (sub_size x sub_size) of", "= grid_slim[slim_index, 0] x_grid = grid_slim[slim_index, 1] for y in", "native dimensions with shape (total_y_pixels*sub_size, total_x_pixels*sub_size). y coordinates are stored", "= (x - coordinate[1]) ** 2 + (y - coordinate[0])", "indexes. The input and output grids are both of shape", "mask_2d_util @numba_util.jit() def grid_2d_centre_from(grid_2d_slim: np.ndarray) -> Tuple[float, float]: \"\"\" Returns", "second row, whose native index is [0,1], has slimmed pixel", "array. The sub grid array has dimensions (total_unmasked_pixels*sub_size**2, 2). Examples", "distance_to_positive_x = extent[1] - centre[1] distance_to_positive_y = extent[3] - centre[0]", "4: Determine if it is outside the border, by comparing", "direction chosen (e.g. if the positive x-axis was the longest,", "= np.sqrt( np.add( np.square(np.subtract(border_grid[:, 0], border_origin[0])), np.square(np.subtract(border_grid[:, 1], border_origin[1])), )", "unmasked values from a native 2D grid of shape [total_y_pixels,", "unmasked pixels sub-array. Returns ------- ndarray A NumPy array of", "centres_scaled[1] + 0.5 ) return grid_pixels_2d @numba_util.jit() def relocated_grid_via_jit_from(grid, border_grid):", "top-left corner relative to the input scaled coordinate. The input", "grid, which the scaled grid is shifted Returns ------- ndarray", "+ 0.5 ) grid_pixels_2d_slim[slim_index, 1] = int( (grid_scaled_2d_slim[slim_index, 1] /", "on the top row, whose native index is [0,5], corresponds", "slimmed 2D grid which are mapped to the native 2D", "functions which require that a 2D grid structure is input.", "shape (total_pixels, 2). Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed grid", "centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for y in", "|<- - - - ->x | x = centre |", "grid_2d_slim_upscaled[upscale_index, 0] = ( y_grid + y_upscale_half - y *", "shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim = np.zeros((grid_scaled_2d_slim.shape[0], 2))", "1D grid. Parameters ---------- grid_2d_native : ndarray The native grid", "these radial coordinates by the input `angle` clockwise. A schematric", "The first pixel on the second row, whose native index", "the longest 1D distance of the 4 paths from the", "= np.zeros(shape=(total_sub_pixels, 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=mask_2d.shape, pixel_scales=pixel_scales, origin=origin )", "region using the longest path between the two chosen above.", "dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- mask = np.array([[True, False, True],", "False, False] [True, False, True]]) grid_slim = grid_2d_slim_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5),", "2], map the values of all unmasked pixels to a", "shifted. Returns ------- ndarray A grid of slimmed pixel indexes", "for slim_index in slim_indexes: y = grid_2d_slim[slim_index, 0] x =", "to the pixels [1,1,:] of the native 2D grid. Parameters", "from the 2D grid with dimensions (total_unmasked_pixels). \"\"\" grid_1d_slim_y =", ":] = grid[:, :] border_origin = np.zeros(2) border_origin[0] = np.mean(border_grid[:,", "index. Grids are defined from the top-left corner, where the", "corner, where the first sub-pixel corresponds to index [0,0]. Sub-pixels", "mask_2d=mask_2d, sub_size=sub_size ) grid_2d_native_x = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 1], mask_2d=mask_2d, sub_size=sub_size", "central coordinates of the grid. \"\"\" centre_y = (np.max(grid_2d_slim[:, 0])", "not included in the slimmed grid. Grid2D are defined from", "they map directly to the pixel they are contained within.", "at the top left corner of the grid, such that", "[True, False, True]]) grid_slim = grid_2d_slim_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0,", "np.square(np.subtract(grid[:, 0], border_origin[0])), np.square(np.subtract(grid[:, 1], border_origin[1])), ) ) for pixel_index", "of shape (total_y_pixels*sub_size, total_x_pixels*sub_size). This routine computes the (y,x) scaled", "2D (y,x) pixel-value coordinates with dimensions (total_pixels, 2). Examples --------", "region (e.g. following the positive / negative y and x", "Union[float, Tuple[float, float]], ) -> np.ndarray: \"\"\" From an input", "upscale_index = 0 y_upscale_half = pixel_scales[0] / 2 y_upscale_step =", "of 2D (y,x) scaled coordinates to a slimmed grid of", "grid. 2: Compute the radial distance of every grid coordinate", "= centre[1] - extent[0] distance_to_negative_y = centre[0] - extent[2] scaled_distance", "[0,1], [1,0], [1,1]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_pixels_2d_slim=grid_pixels_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0,", "steps of the pixel-scale. 5) Rotate these radial coordinates by", "border_grid[:, 0]) + np.square(grid[pixel_index, 1] - border_grid[:, 1]) ) move_factor", "radii radii += pixel_scale / sub_size return grid_scaled_2d_slim_radii @numba_util.jit() def", "outside the border, by comparing its radial distance from the", "[4.0, 4.0]]) grid_pixel_centres_2d = grid_pixel_centres_2d_from(grid_scaled_2d=grid_scaled_2d, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0))", "2.0) ) grid_slim[sub_index, 1] = ( x_scaled - x_sub_half +", "native grid and goes right-wards and downwards, such that for", "grid_pixel_indexes_2d_slim[slim_index] = int( grid_pixels_2d_slim[slim_index, 0] * shape_native[1] + grid_pixels_2d_slim[slim_index, 1]", "pixel [0,0] corresponds to the highest (most positive) y scaled", "conversion factor of the original 2D array. origin : (float,", ") ) border_min_radii = np.min(border_grid_radii) grid_radii = np.sqrt( np.add( np.square(np.subtract(grid[:,", "A grid of slimmed pixel indexes with dimensions (total_pixels,). Examples", "that are part of the same mask array pixel are", "input scaled coordinate. The input and output grids are both", ") @numba_util.jit() def grid_scaled_2d_slim_radial_projected_from( extent: np.ndarray, centre: Tuple[float, float], pixel_scales:", "defined by an origin and coordinates are shifted to this", "is used to define border pixels. Parameters ---------- grid :", "2). Examples -------- grid_scaled_2d_slim = np.array([[1.0, 1.0], [2.0, 2.0], [3.0,", "Returns ------- ndarray A 1D grid of values mapped from", "1D grid pixel indexes. The input and output grids are", "the 2D grid going rights and then downwards. The input", "scaled_distance = max( [ distance_to_positive_x, distance_to_positive_y, distance_to_negative_x, distance_to_negative_y, ] )", "mask of shape [total_y_pixels, total_x_pixels, 2], map the values of", "map the slimmed grid's coordinates back to the native 2D", "it. border_grid : Grid2D The grid of border (y,x) coordinates.", "mask array. The sub-grid is returned in its slimmed dimensions", "values which are mapped to the slimmed grid. mask_2d A", "that each pixel of the 2D mask array is divided", "2D (y,x) coordinates in scaled units which is converted to", "1D grid of values which are mapped to a 2D", "\"\"\" Convert a slimmed grid of 2d (y,x) scaled coordinates", "use the ratio of radial distances to move the coordinate", "slimmed grid's coordinates back to the native 2D grid where", "included as part of the calculated sub-grid. pixel_scales The (y,x)", "native grid of 2D (y,x) pixel values. Pixel coordinates are", "If its radial distance is larger, use the ratio of", "1]) border_grid_radii = np.sqrt( np.add( np.square(np.subtract(border_grid[:, 0], border_origin[0])), np.square(np.subtract(border_grid[:, 1],", "pixel-scale corresponding to the direction chosen (e.g. if the positive", "int ) -> np.ndarray: \"\"\" For a native 2D grid", "path between the two chosen above. 4) Create a (y,x)", "shifted to this origin before computing their 1D grid pixel", "0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d = np.zeros((grid_scaled_2d.shape[0], grid_scaled_2d.shape[1], 2)) centres_scaled", "grid of (y,x) values which are mapped to the slimmed", "0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim = grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim=grid_scaled_2d_slim, shape_native=shape_native, pixel_scales=pixel_scales,", "pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim = np.zeros((grid_scaled_2d_slim.shape[0], 2)) centres_scaled", "scaled grid is shifted. Returns ------- ndarray A slimmed grid", "the top-left corner, where the first unmasked sub-pixel corresponds to", "grid_relocated[:, :] = grid[:, :] border_origin = np.zeros(2) border_origin[0] =", "array is divided into. origin The (y,x) origin of the", "to the native 2D grid. mask_2d A 2D array of", "Returns ------- ndarray A slimmed grid of 2D (y,x) pixel", "grid of border (y,x) coordinates. \"\"\" grid_relocated = np.zeros(grid.shape) grid_relocated[:,", "resolution at which the new grid coordinates are computed. pixel_scales", "int((scaled_distance / pixel_scale)) + 1 grid_scaled_2d_slim_radii = np.zeros((shape_slim, 2)) grid_scaled_2d_slim_radii[:,", "the native 2D grid. - If slim_to_native[4] = [1,1], the", "pixel_scales[1]) + centres_scaled[1] + 0.5 ) return grid_pixels_2d @numba_util.jit() def", "are converted to pixel value coordinates. shape_native The (y,x) shape", "slimmed 2D grid of shape [total_unmasked_pixels, 2], that was computed", "/ 2.0 return centre_y, centre_x @numba_util.jit() def grid_2d_slim_via_mask_from( mask_2d: np.ndarray,", "so forth. Parameters ---------- shape_native The (y,x) shape of the", "A slimmed sub grid of (y,x) scaled coordinates at the", "= distance_to_centre_new furthest_grid_2d_slim_index = slim_index return furthest_grid_2d_slim_index def grid_2d_slim_from( grid_2d_native:", "False, True]]) grid_2d = grid_2d_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0))", "from autoarray.geometry import geometry_util from autoarray import numba_util from autoarray.mask", "(np.max(grid_2d_slim[:, 1]) + np.min(grid_2d_slim[:, 1])) / 2.0 return centre_y, centre_x", "radial points where all points are at the centre's y", "shape of the original 2D array the scaled coordinates were", "2)) grid_scaled_2d_slim_radii[:, 0] += centre[0] radii = centre[1] for slim_index", "array 'slim_to_native' where each index gives the 2D pixel indexes", "pixel of the 2D mask array is divided into. shape_slim", "Compute the radial distance of every grid coordinate from the", "i in range(len(grid_2d[:, 0])): if (grid_2d[i, 0] - centre[0]) **", "The returned `grid_radii` represents a radial set of points that", "to the edge of the extent window. The returned `grid_radii`", "grid_2d_slim_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\" total_sub_pixels = mask_2d_util.total_sub_pixels_2d_from(mask_2d,", "with format [xmin, xmax, ymin, ymax] centre : (float, flloat)", "autoarray.geometry import geometry_util from autoarray import numba_util from autoarray.mask import", "float] ) -> int: distance_to_centre = 0.0 for slim_index in", "y_scaled - y_sub_half + y1 * y_sub_step + (y_sub_step /", "This routine computes the (y,x) scaled coordinates a the centre", "from the top-left of the 2D grid going rights and", "grid_pixels_2d = np.zeros((grid_scaled_2d.shape[0], grid_scaled_2d.shape[1], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales,", "(y,x) centre to the edge of the region (e.g. following", "mean unmasked and are included in the mapping. sub_size The", "grid of values mapped from the 2D grid with dimensions", "y * y_upscale_step - (y_upscale_step / 2.0) ) grid_2d_slim_upscaled[upscale_index, 1]", "index 4. The first pixel on the second row, whose", "- centre[0]) ** 2 + ( grid_2d[i, 1] - centre[1]", "The scaled grid is defined by an origin and coordinates", "unmasked sub-pixel corresponds to index 0. Sub-pixels that are part", "2D mask array. The sub grid is slimmed and has", "shape_native=mask_2d.shape, pixel_scales=pixel_scales, origin=origin ) sub_index = 0 y_sub_half = pixel_scales[0]", "[True, False, True]]) grid_2d_slim = grid_2d_slim_via_shape_native_from(shape_native=(3,3), pixel_scales=(0.5, 0.5), sub_size=2, origin=(0.0,", "2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixel_indexes_2d_slim = grid_pixel_indexes_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5,", "grid_2d_slim = grid_2d_slim_via_shape_native_from(shape_native=(3,3), pixel_scales=(0.5, 0.5), sub_size=2, origin=(0.0, 0.0)) \"\"\" return", "ndarray A slimmed grid of 2D (y,x) pixel indexes with", "an grid of shape (3,3) where all pixels are unmasked:", "[0,1,:] of the native 2D grid. - If slim_to_native[4] =", "Returns ------- (float, float) The (y,x) central coordinates of the", "(if its inside the border, do nothing). The method can", "1D grid pixel indexes. Parameters ---------- grid_scaled_2d: np.ndarray The native", "= pixel_scales[0] else: pixel_scale = pixel_scales[1] if shape_slim == 0:", "defined from the top-left corner, where the first unmasked sub-pixel", "centre and the edge of the region using the longest", "from each pixel's top-left corner relative to the input scaled", "(total_pixels**2*sub_size**2, 2). y coordinates are stored in the 0 index", "int, pixel_scales: Union[float, Tuple[float, float]], ) -> np.ndarray: \"\"\" From", "its radial distance is larger, use the ratio of radial", "of pixel indexes. Pixel coordinates are returned as integers such", "border_origin = np.zeros(2) border_origin[0] = np.mean(border_grid[:, 0]) border_origin[1] = np.mean(border_grid[:,", "(y,x) centre. This functions operates as follows: 1) Given the", "grid coordinates are computed. pixel_scales The pixel scale of the", "in range(sub_size): for x1 in range(sub_size): grid_slim[sub_index, 0] = -(", "(most positive) y scaled coordinate and lowest (most negative) x", "0.0)) \"\"\" return grid_2d_slim_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, )", "to the direction chosen (e.g. if the positive x-axis was", "for x in range(upscale_factor): grid_2d_slim_upscaled[upscale_index, 0] = ( y_grid +", "2). Examples -------- grid_scaled_2d = np.array([[1.0, 1.0], [2.0, 2.0], [3.0,", "origin: Tuple[float, float] = (0.0, 0.0), ) -> np.ndarray: \"\"\"", "0.0)) \"\"\" return grid_2d_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, )", "[xmin, xmax, ymin, ymax] and with a (y,x) centre. This", "def compute_polygon_area(points): x = points[:, 1] y = points[:, 0]", "1] = ( x_scaled - x_sub_half + x1 * x_sub_step", "array is divided into. shape_slim Manually choose the shape of", "at which the new grid coordinates are computed. pixel_scales The", "origin. 3: For every coordinate, find its nearest pixel in", "0])): if (grid_2d[i, 0] - centre[0]) ** 2 + (", "sub grid is slimmed and has dimensions (total_unmasked_pixels*sub_size**2, 2). Examples", "ymax] centre : (float, flloat) The (y,x) central coordinate which", "grid_2d_native_from( grid_2d_slim: np.ndarray, mask_2d: np.ndarray, sub_size: int ) -> np.ndarray:", "a slimmed grid of pixel indexes. Pixel coordinates are returned", "2D array. origin : (float, flloat) The (y,x) origin of", "a 1D data structure so that it can be used", "grid. mask_2d A 2D array of bools, where `False` values", "pixel [0,0] of the 2D grid will correspond to index", "native 2D grid where masked values are set to zero.", "Tuple[float, float]], origin: Tuple[float, float] = (0.0, 0.0), ) ->", "of the 2D grid going rights and then downwards. The", "= extent[1] - centre[1] distance_to_positive_y = extent[3] - centre[0] distance_to_negative_x", "border_origin[0])), np.square(np.subtract(border_grid[:, 1], border_origin[1])), ) ) border_min_radii = np.min(border_grid_radii) grid_radii", "with dimensions (y_pixels, x_pixels, 2). Examples -------- grid_scaled_2d = np.array([[1.0,", "the border edge if outside it. border_grid : Grid2D The", "pixel indexes. Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed grid of", "Parameters ---------- grid : Grid2D The grid (uniform or irregular)", "the first value of the 1D array maps to the", "sampling the longest distance from the centre to the edge", "the centre in increasing steps of the pixel-scale. 5) Rotate", "= [0,1], the second value of the 1D array maps", "= ( y_grid + y_upscale_half - y * y_upscale_step -", "and not included in the slimmed grid. Grid2D are defined", "the origin. 3: For every coordinate, find its nearest pixel", "mask array pixel are indexed next to one another, such", "of bools, where `False` values are unmasked and therefore included", "are outside the border, where the border is defined as", "for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = ( (-grid_scaled_2d_slim[slim_index, 0]", "x_inside.append(grid_2d[i, 1]) return np.asarray(y_inside, x_inside) def compute_polygon_area(points): x = points[:,", "0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim = np.zeros((grid_scaled_2d_slim.shape[0], 2)) centres_scaled =", "(y,x) coordinates in scaled units which is converted to pixel", "- If slim_to_native[1] = [0,1], the second value of the", "np.sqrt( np.add( np.square(np.subtract(grid[:, 0], border_origin[0])), np.square(np.subtract(grid[:, 1], border_origin[1])), ) )", "both slimmed and have shapes (total_pixels, 2) and (total_pixels,). For", "y_scaled = (y - centres_scaled[0]) * pixel_scales[0] x_scaled = (x", "(float, float) The (y,x) central coordinates of the grid. \"\"\"", "define border pixels. Parameters ---------- grid : Grid2D The grid", "indexed next to one another, such that the second sub-pixel", "radial path to the edge of the extent window. The", "\"\"\" Returns the centre of a grid from a 1D", "from the centre to the edge of the extent in", "= pixel_scales[0] / upscale_factor x_upscale_half = pixel_scales[1] / 2 x_upscale_step", "the 2D mask array. The sub grid is slimmed and", "1 return grid_2d_slim_upscaled def grid_2d_of_points_within_radius( radius: float, centre: Tuple[float, float],", "(y - centres_scaled[0]) * pixel_scales[0] x_scaled = (x - centres_scaled[1])", "in the 1 index. Grids are defined from the top-left", "pixel on the top row, whose native index is [0,5],", "return grid_relocated @numba_util.jit() def furthest_grid_2d_slim_index_from( grid_2d_slim: np.ndarray, slim_indexes: np.ndarray, coordinate:", "= grid_2d_slim_via_shape_native_from(shape_native=(3,3), pixel_scales=(0.5, 0.5), sub_size=2, origin=(0.0, 0.0)) \"\"\" return grid_2d_slim_via_mask_from(", "= geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for slim_index in range(grid_scaled_2d_slim.shape[0]):", "1] = ( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1]) + centres_scaled[1] +", "x_sub_step = pixel_scales[1] / (sub_size) for y in range(mask_2d.shape[0]): for", "to pixel units conversion factor of the original 2D array.", "values of the native 2D mapped from the slimmed grid.", "pixel_scales[1] if shape_slim == 0: shape_slim = sub_size * int((scaled_distance", "(total_y_pixels, total_x_pixels) is divided into a finer uniform grid of", "2]. The pixel coordinate origin is at the top left", "0.5), sub_size=2, origin=(0.0, 0.0)) \"\"\" return grid_2d_slim_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales,", "which are converted to pixel value coordinates. shape_native The (y,x)", "(total_unmasked_pixels). \"\"\" grid_1d_slim_y = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 0], mask_2d=mask, sub_size=sub_size", "the ratio of radial distances to move the coordinate to", "that laid over the irregular grid of (y,x) coordinates. \"\"\"", ") if (scaled_distance == distance_to_positive_y) or ( scaled_distance == distance_to_negative_y", "uses a 1D array 'slim_to_native' where each index gives the", "True], [False, False, False] [True, False, True]]) grid_2d_slim = grid_2d_slim_via_shape_native_from(shape_native=(3,3),", "coordinates to a native grid of 2D (y,x) pixel values.", "def furthest_grid_2d_slim_index_from( grid_2d_slim: np.ndarray, slim_indexes: np.ndarray, coordinate: Tuple[float, float] )", "corner, where the first unmasked sub-pixel corresponds to index 0.", "then downwards. The input and output grids are both slimmed", "grid_scaled_2d: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], origin:", "1] - border_grid[:, 1]) ) move_factor = ( border_grid_radii[closest_pixel_index] /", "array maps to the pixels [1,1,:] of the native 2D", "are both slimmed and therefore shape (total_pixels, 2). The pixel", "= extent[3] - centre[0] distance_to_negative_x = centre[1] - extent[0] distance_to_negative_y", "the centre of every pixel unmasked pixel on the 2D", "to index 0 of the 1D grid. - pixel [0,1]", "so forth. Parameters ---------- mask_2d A 2D array of bools,", "sub_size The size (sub_size x sub_size) of each unmasked pixels", "0.5 ) * pixel_scales[1] return grid_scaled_2d_slim @numba_util.jit() def grid_pixel_centres_2d_from( grid_scaled_2d:", "factor of the original 2D array. origin : (float, flloat)", "of the grid. 2: Compute the radial distance of every", "as follows: 1) Given the region defined by the extent", "slim_index in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = ( (-grid_scaled_2d_slim[slim_index, 0] /", ") return grid_pixels_2d @numba_util.jit() def relocated_grid_via_jit_from(grid, border_grid): \"\"\" Relocate the", "y = grid_2d_slim[slim_index, 0] x = grid_2d_slim[slim_index, 1] distance_to_centre_new =", "slimmed grid of 2D (y,x) scaled coordinates to a slimmed", "grid_2d_slim_upscaled = np.zeros( shape=(grid_slim.shape[0] * upscale_factor ** 2, 2) )", "(0.0, 0.0), ) -> np.ndarray: \"\"\" For a sub-grid, every", "- pixel [0,0] of the 2D grid will correspond to", "scaled coordinates to a slimmed grid of 2D (y,x) pixel", "computes the (y,x) scaled coordinates at the centre of every", "(y,x) scaled coordinates to a slimmed grid of 2D (y,x)", "slim_index in range(grid_pixels_2d_slim.shape[0]): grid_pixel_indexes_2d_slim[slim_index] = int( grid_pixels_2d_slim[slim_index, 0] * shape_native[1]", "2, and so forth. Parameters ---------- mask_2d A 2D array", "1] = int( (grid_scaled_2d[y, x, 1] / pixel_scales[1]) + centres_scaled[1]", "centre[1] ) ** 2 > radius ** 2: y_inside.append(grid_2d[i, 0])", "around. Returns ------- ndarray A sub grid of (y,x) scaled", "y1 in range(sub_size): for x1 in range(sub_size): grid_slim[sub_index, 0] =", "= (np.max(grid_2d_slim[:, 0]) + np.min(grid_2d_slim[:, 0])) / 2.0 centre_x =", "the same mask array pixel are indexed next to one", "1 grid_scaled_2d_slim_radii = np.zeros((shape_slim, 2)) grid_scaled_2d_slim_radii[:, 0] += centre[0] radii", "computing their 1D grid pixel indexes. Parameters ---------- grid_scaled_2d_slim: np.ndarray", "pixel coordinate origin is at the top left corner of", "units which is converted to pixel indexes. shape_native The (y,x)", "2 y_sub_step = pixel_scales[0] / (sub_size) x_sub_half = pixel_scales[1] /", "is computed for. pixel_scales The (y,x) scaled units to pixel", "(0.0, 0.0), ) -> np.ndarray: \"\"\" Convert a native grid", "given values (0.0, 0.0). Grids are defined from the top-left", "- - - ->x | x = centre | |", "output grids are both slimmed and have shapes (total_pixels, 2)", "between the two chosen above. 4) Create a (y,x) grid", "scaled coordinates with dimensions (total_pixels, 2). Examples -------- grid_pixels_2d_slim =", "[2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixel_indexes_2d_slim = grid_pixel_indexes_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2),", "= grid_2d_slim[slim_index, 0] x = grid_2d_slim[slim_index, 1] distance_to_centre_new = (x", "grid_2d = grid_2d_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\" grid_2d_slim", "(float, flloat) The (y,x) origin of the grid, which the", "of the 1D array maps to the pixels [0,0,:] of", "* pixel_scales[1] for y1 in range(sub_size): for x1 in range(sub_size):", "is shifted to. Returns ------- ndarray A slimmed grid of", "grid of 2D (y,x) pixel coordinates to a slimmed grid", "pixel_scales[1] / 2 x_upscale_step = pixel_scales[1] / upscale_factor for slim_index", "pixel indexes. Parameters ---------- grid_scaled_2d: np.ndarray The native grid of", "or ( scaled_distance == distance_to_negative_y ): pixel_scale = pixel_scales[0] else:", "True]]) grid_slim = grid_2d_slim_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\"", "slimmed 2D grid, return an upscaled slimmed 2D grid where", "value). Returns ------- ndarray A radial set of points sampling", "0] = ( -(grid_pixels_2d_slim[slim_index, 0] - centres_scaled[0] - 0.5) *", "centres_scaled[0] + 0.5 ) grid_pixels_2d_slim[slim_index, 1] = ( (grid_scaled_2d_slim[slim_index, 1]", "2], that was computed by extracting the unmasked values from", "0] / pixel_scales[0]) + centres_scaled[0] + 0.5 ) grid_pixels_2d_slim[slim_index, 1]", "pixel units conversion factor of the original 2D array. origin", "= grid_scaled_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim =", "\"\"\" Convert a slimmed grid of 2D (y,x) scaled coordinates", "+ border_origin[:] ) return grid_relocated @numba_util.jit() def furthest_grid_2d_slim_index_from( grid_2d_slim: np.ndarray,", "grid_radii[pixel_index] > border_min_radii: closest_pixel_index = np.argmin( np.square(grid[pixel_index, 0] - border_grid[:,", "scaled grid is shifted to. Returns ------- ndarray A slimmed", "coordinates are therefore removed and not included in the slimmed", "floats such that they include the decimal offset from each", "(x - centres_scaled[1]) * pixel_scales[1] for y1 in range(sub_size): for", "A slimmed grid of 2D (y,x) pixel indexes with dimensions", "(total_pixels, 2). Examples -------- grid_pixels_2d_slim = np.array([[0,0], [0,1], [1,0], [1,1])", "y_upscale_half = pixel_scales[0] / 2 y_upscale_step = pixel_scales[0] / upscale_factor", "2D (y,x) scaled coordinates to a slimmed grid of 2D", "= pixel_scales[0] / 2 y_sub_step = pixel_scales[0] / (sub_size) x_sub_half", "( border_grid_radii[closest_pixel_index] / grid_radii[pixel_index] ) if move_factor < 1.0: grid_relocated[pixel_index,", "slimmed grid of 2d (y,x) scaled coordinates to a slimmed", "array pixel are indexed next to one another, such that", "the grid's native unmasked pixels, for example: - If slim_to_native[0]", "furthest_grid_2d_slim_index def grid_2d_slim_from( grid_2d_native: np.ndarray, mask: np.ndarray, sub_size: int )", "y value = 0.0 and the x values iterate from", "x coordinates in the 1 index. Grid2D are defined from", "centre x above, this function finds the longest radial path", "to its paired border pixel's radial distance. 5: If its", "grid is slimmed and has dimensions (total_unmasked_pixels*sub_size**2, 2). Examples --------", "return grid_scaled_2d_slim @numba_util.jit() def grid_pixel_centres_2d_from( grid_scaled_2d: np.ndarray, shape_native: Tuple[int, int],", "negative) x scaled coordinate on the gird. The scaled coordinate", "such that the pixel [0,0] corresponds to the highest (most", "= np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixel_indexes_2d_slim", "Returns ------- ndarray A NumPy array of shape [total_y_pixels, total_x_pixels,", "0] += centre[0] radii = centre[1] for slim_index in range(shape_slim):", "a slimmed grid of 2D (y,x) scaled values. The input", "x, 0] / pixel_scales[0]) + centres_scaled[0] + 0.5 ) grid_pixels_2d[y,", "2D mask array. The sub-grid is returned in its slimmed", "ratio of radial distances to move the coordinate to the", "= pixel_scales[1] if shape_slim == 0: shape_slim = sub_size *", "The (y,x) shape of the original 2D array the scaled", "the top-left, whose native index is [0,0], corresponds to slimmed", "2D (y,x) pixel values. Pixel coordinates are returned as integers", "int( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1]) + centres_scaled[1] + 0.5 )", "x1 in range(sub_size): grid_slim[sub_index, 0] = -( y_scaled - y_sub_half", "size of the sub-grid that each pixel of the 2D", "geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_scaled_2d_slim[slim_index,", "+ np.square(grid[pixel_index, 1] - border_grid[:, 1]) ) move_factor = (", "centre. This functions operates as follows: 1) Given the region", "Pixel coordinates are returned as integers such that they map", "correspond to index 0 of the 1D grid. - pixel", "2). Examples -------- grid_pixels_2d_slim = np.array([[0,0], [0,1], [1,0], [1,1]) grid_pixels_2d_slim", "distances to move the coordinate to the border (if its", "of the native 2D grid. - If slim_to_native[1] = [0,1],", "(y,x) scaled values. The input and output grids are both", "= centre | | <-> = longest radial path from", "grid of values which are mapped to a 2D array.", "top row, whose native index is [0,5], corresponds to slimmed", "pixels sub-array. Returns ------- ndarray A NumPy array of shape", "Tuple[float, float]], sub_size: int, origin: Tuple[float, float] = (0.0, 0.0),", "int], pixel_scales: Union[float, Tuple[float, float]], origin: Tuple[float, float] = (0.0,", "The sub-grid is returned in its slimmed dimensions with shape", "0.5 ) return grid_pixels_2d @numba_util.jit() def relocated_grid_via_jit_from(grid, border_grid): \"\"\" Relocate", "from the slimmed grid. \"\"\" grid_2d_native_y = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 0],", "as integers such that they map directly to the pixel", "sub-grid. pixel_scales The (y,x) scaled units to pixel units conversion", "-> int: distance_to_centre = 0.0 for slim_index in slim_indexes: y", "to a 1D data structure so that it can be", "slimmed grid. mask_2d A 2D array of bools, where `False`", "corner of the grid, such that the pixel [0,0] corresponds", "------- ndarray A grid of slimmed pixel indexes with dimensions", "+ y1 * y_sub_step + (y_sub_step / 2.0) ) grid_slim[sub_index,", "0 y_sub_half = pixel_scales[0] / 2 y_sub_step = pixel_scales[0] /", "in range(grid_scaled_2d_slim.shape[0]): grid_scaled_2d_slim[slim_index, 0] = ( -(grid_pixels_2d_slim[slim_index, 0] - centres_scaled[0]", "2D grid going rights and then downwards. The input and", "Parameters ---------- shape_native The (y,x) shape of the 2D array", "np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixel_indexes_2d_slim =", "divided into. origin The (y,x) origin of the 2D array,", "grid_2d_slim_upscaled def grid_2d_of_points_within_radius( radius: float, centre: Tuple[float, float], grid_2d: np.ndarray", "pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) @numba_util.jit() def grid_scaled_2d_slim_radial_projected_from( extent: np.ndarray, centre:", "False, False] [True, False, True]]) grid_2d = grid_2d_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5),", "2D (y,x) scaled coordinates to a native grid of 2D", "Examples -------- grid_scaled_2d = np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0],", "pixel on the 2D mask array. The sub grid is", "to move the coordinate to the border (if its inside", "to the edge of the extent in along the positive", "np.ndarray: \"\"\" Convert a slimmed grid of 2D (y,x) scaled", "2: Compute the radial distance of every grid coordinate from", "shifted Returns ------- ndarray A slimmed grid of 2D (y,x)", "first pixel has index 1, its next sub-pixel has index", "has dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- grid_2d = grid_2d_via_shape_native_from(shape_native=(3, 3),", "np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixel_centres_2d =", "array of bools, where `False` values are unmasked and therefore", "grid and goes right-wards and downwards, such that for an", "bools, where `False` values are unmasked and therefore included as", "= (0.0, 0.0), ) -> np.ndarray: \"\"\" For a sub-grid,", "grid_slim[sub_index, 1] = ( x_scaled - x_sub_half + x1 *", "False] [True, False, True]]) grid_2d = grid_2d_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1,", "border, do nothing). The method can be used on uniform", "x * x_upscale_step + (x_upscale_step / 2.0) ) upscale_index +=", "sub_size=2, origin=(0.0, 0.0)) \"\"\" return grid_2d_slim_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size,", "---------- grid_2d_slim The (y,x) values of the slimmed 2D grid", "grids the border of the 'image-plane' mask is used to", "@numba_util.jit() def grid_2d_centre_from(grid_2d_slim: np.ndarray) -> Tuple[float, float]: \"\"\" Returns the", "scaled coordinate and lowest (most negative) x scaled coordinate on", "ndarray A slimmed sub grid of (y,x) scaled coordinates at", "left corner of the native grid and goes right-wards and", "origin=origin, ) @numba_util.jit() def grid_scaled_2d_slim_radial_projected_from( extent: np.ndarray, centre: Tuple[float, float],", "from autoarray import numba_util from autoarray.mask import mask_2d_util @numba_util.jit() def", "The input and output grids are both native resolution and", "(y,x) coordinates. \"\"\" grid_2d_slim_upscaled = np.zeros( shape=(grid_slim.shape[0] * upscale_factor **", "(x_upscale_step / 2.0) ) upscale_index += 1 return grid_2d_slim_upscaled def", "in scaled units which is converted to slimmed pixel indexes.", "= np.zeros(grid_pixels_2d_slim.shape[0]) for slim_index in range(grid_pixels_2d_slim.shape[0]): grid_pixel_indexes_2d_slim[slim_index] = int( grid_pixels_2d_slim[slim_index,", "were computed on. pixel_scales The (y,x) scaled units to pixel", "------- ndarray A 1D grid of values mapped from the", "the original 2D array. origin : (float, flloat) The (y,x)", "be relocated to the border edge if outside it. border_grid", "[xmin, xmax, ymin, ymax] centre : (float, flloat) The (y,x)", "are both of shape (total_pixels, 2). Parameters ---------- grid_scaled_2d_slim: np.ndarray", "for an grid of shape (3,3) where all pixels are", "-------- grid_pixels_2d_slim = np.array([[0,0], [0,1], [1,0], [1,1]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_pixels_2d_slim=grid_pixels_2d_slim,", "np.array([[0,0], [0,1], [1,0], [1,1]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_pixels_2d_slim=grid_pixels_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5),", "where each index gives the 2D pixel indexes of the", "range(grid_scaled_2d.shape[0]): for x in range(grid_scaled_2d.shape[1]): grid_pixels_2d[y, x, 0] = int(", "the longest, the pixel_scale in the x dimension is used).", "The (y,x) origin of the grid, which the scaled grid", "sub-grid, every unmasked pixel of its 2D mask with shape", "was the longest, the pixel_scale in the x dimension is", "or irregular) whose pixels are to be relocated to the", "slimmed grid of 2D (y,x) coordinates in scaled units which", "move_factor * (grid[pixel_index, :] - border_origin[:]) + border_origin[:] ) return", "(y,x) scaled units to pixel units conversion factor of the", "for y in range(upscale_factor): for x in range(upscale_factor): grid_2d_slim_upscaled[upscale_index, 0]", "Returns ------- ndarray A slimmed grid of 2D (y,x) pixel-value", "sub_size The size of the sub-grid that each pixel of", "a slimmed grid of 2D (y,x) scaled coordinates to a", ") return grid_pixel_indexes_2d_slim @numba_util.jit() def grid_scaled_2d_slim_from( grid_pixels_2d_slim: np.ndarray, shape_native: Tuple[int,", "native grid of 2D (y,x) coordinates in scaled units which", "/ 2.0 centre_x = (np.max(grid_2d_slim[:, 1]) + np.min(grid_2d_slim[:, 1])) /", "move_factor < 1.0: grid_relocated[pixel_index, :] = ( move_factor * (grid[pixel_index,", "following the positive / negative y and x axes). 2)", "is converted to pixel indexes. shape_native The (y,x) shape of", "1] - centre[1] ) ** 2 > radius ** 2:", "mask_2d=mask_2d, pixel_scales=pixel_scales, sub_size=sub_size, origin=origin ) return grid_2d_native_from( grid_2d_slim=grid_2d_slim, mask_2d=mask_2d, sub_size=sub_size", "\"\"\" grid_relocated = np.zeros(grid.shape) grid_relocated[:, :] = grid[:, :] border_origin", "grids are both slimmed and therefore shape (total_pixels, 2). The", "the gird. The scaled coordinate grid is defined by the", "longest path between the two chosen above. 4) Create a", "* pixel_scales[1] return grid_scaled_2d_slim @numba_util.jit() def grid_pixel_centres_2d_from( grid_scaled_2d: np.ndarray, shape_native:", "at the edge of the grid's mask (see *mask._border_1d_indexes*). This", "grid. - If slim_to_native[1] = [0,1], the second value of", "its slimmed dimensions with shape (total_pixels**2*sub_size**2, 2). y coordinates are", "that the pixel [0,0] corresponds to the highest (most positive)", "routine computes the (y,x) scaled coordinates a the centre of", "as part of the calculated sub-grid. pixel_scales The (y,x) scaled", "2D (y,x) pixel indexes with dimensions (total_pixels, 2). Examples --------", "index is [0,5], corresponds to slimmed pixel index 4. The", ") grid_pixels_2d[y, x, 1] = int( (grid_scaled_2d[y, x, 1] /", "grid, which the scaled grid is shifted. Returns ------- ndarray", "negative y and x axes). 2) Use the pixel-scale corresponding", "from the origin. 3: For every coordinate, find its nearest", "grid. Parameters ---------- grid_2d_native : ndarray The native grid of", "0], mask_2d=mask_2d, sub_size=sub_size ) grid_2d_native_x = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 1], mask_2d=mask_2d,", "The input and output grids are both of shape (total_pixels,", "2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixel_centres_2d = grid_pixel_centres_2d_from(grid_scaled_2d=grid_scaled_2d, shape=(2,2), pixel_scales=(0.5,", "def grid_scaled_2d_slim_radial_projected_from( extent: np.ndarray, centre: Tuple[float, float], pixel_scales: Union[float, Tuple[float,", "another, such that the second sub-pixel in the first pixel", "pixel's radial distance. 5: If its radial distance is larger,", "1.0: grid_relocated[pixel_index, :] = ( move_factor * (grid[pixel_index, :] -", "before computing their 1D grid pixel indexes. Parameters ---------- grid_scaled_2d:", "\"\"\" grid_2d_slim_upscaled = np.zeros( shape=(grid_slim.shape[0] * upscale_factor ** 2, 2)", "Parameters ---------- grid_2d_slim The (y,x) values of the slimmed 2D", "grid that laid over the irregular grid of (y,x) coordinates.", "computing their 1D grid pixel indexes. The input and output", "origin=origin ) sub_index = 0 y_sub_half = pixel_scales[0] / 2", "\"\"\" Determine a projected radial grid of points from a", "centre to the edge of the region (e.g. following the", "path from centre to extent edge | | ------------------- Using", "grid_pixels_2d_slim @numba_util.jit() def grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales:", "and x axes). 2) Use the pixel-scale corresponding to the", "therefore have shape (y_pixels, x_pixels, 2). The pixel coordinate origin", "to. Returns ------- ndarray A slimmed grid of 2D (y,x)", "1])) / 2.0 return centre_y, centre_x @numba_util.jit() def grid_2d_slim_via_mask_from( mask_2d:", "to index [0,0]. Sub-pixels that are part of the same", "coordinates are computed. pixel_scales The pixel scale of the uniform", "grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], origin:", "origin before computing their 1D grid pixel coordinate values. Parameters", "are set to zero. This uses a 1D array 'slim_to_native'", "values mapped from the 2D grid with dimensions (total_unmasked_pixels). \"\"\"", "origin The (y,x) origin of the 2D array, which the", "= array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 1], mask_2d=mask, sub_size=sub_size ) return np.stack((grid_1d_slim_y,", "for x in range(mask_2d.shape[1]): if not mask_2d[y, x]: y_scaled =", "their 1D grid pixel indexes. Parameters ---------- grid_scaled_2d_slim: np.ndarray The", "mask_2d A 2D array of bools, where `False` values mean", "scaled coordinates at the centre of every sub-pixel defined by", "array_2d_slim=grid_2d_slim[:, 0], mask_2d=mask_2d, sub_size=sub_size ) grid_2d_native_x = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 1],", "origin=(0.0, 0.0)) \"\"\" grid_pixels_2d = np.zeros((grid_scaled_2d.shape[0], grid_scaled_2d.shape[1], 2)) centres_scaled =", "native 2D grid. Parameters ---------- grid_2d_slim The (y,x) values of", "of shape [total_unmasked_pixels, 2], that was computed by extracting the", "True]]) grid_2d_slim = grid_2d_slim_via_shape_native_from(shape_native=(3,3), pixel_scales=(0.5, 0.5), sub_size=2, origin=(0.0, 0.0)) \"\"\"", "\"\"\" grid_pixels_2d_slim = grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim=grid_scaled_2d_slim, shape_native=shape_native, pixel_scales=pixel_scales, origin=origin, ) grid_pixel_indexes_2d_slim", "[4.0, 4.0]]) grid_pixel_indexes_2d_slim = grid_pixel_indexes_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0))", "x-axis was the longest, the pixel_scale in the x dimension", "pixel_scales[0] ) grid_scaled_2d_slim[slim_index, 1] = ( grid_pixels_2d_slim[slim_index, 1] - centres_scaled[1]", "converted to scaled coordinates. shape_native The (y,x) shape of the", "furthest_grid_2d_slim_index = slim_index return furthest_grid_2d_slim_index def grid_2d_slim_from( grid_2d_native: np.ndarray, mask:", "[xmin, xmax, ymin, ymax], the algorithm finds the longest 1D", "pixel_scales: Union[float, Tuple[float, float]], sub_size: int, shape_slim: Optional[int] = 0,", "1] = radii radii += pixel_scale / sub_size return grid_scaled_2d_slim_radii", "grid. \"\"\" centre_y = (np.max(grid_2d_slim[:, 0]) + np.min(grid_2d_slim[:, 0])) /", "4) Create a (y,x) grid of radial points where all", "as floats such that they include the decimal offset from", "1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixel_indexes_2d_slim = grid_pixel_indexes_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim,", "scaled units which are converted to pixel value coordinates. shape_native", "the native 2D grid. Parameters ---------- grid_2d_slim The (y,x) values", "- pixel [1,0] of the 2D grid will correspond to", "float], pixel_scales: Union[float, Tuple[float, float]], sub_size: int, shape_slim: Optional[int] =", "of values mapped from the 2D grid with dimensions (total_unmasked_pixels).", "pixel has index 1, its next sub-pixel has index 2,", "grid_2d_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float, Tuple[float, float]], sub_size: int, origin:", "2 x_upscale_step = pixel_scales[1] / upscale_factor for slim_index in range(grid_slim.shape[0]):", "range(upscale_factor): for x in range(upscale_factor): grid_2d_slim_upscaled[upscale_index, 0] = ( y_grid", "dimension, x coordinates in the 1 index. Grid2D are defined", "(np.max(grid_2d_slim[:, 0]) + np.min(grid_2d_slim[:, 0])) / 2.0 centre_x = (np.max(grid_2d_slim[:,", "np.ndarray: \"\"\" Convert a slimmed grid of 2d (y,x) scaled", "pixel_scales=(0.5, 0.5), sub_size=2, origin=(0.0, 0.0)) \"\"\" return grid_2d_slim_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native),", "if it is outside the border, by comparing its radial", "+ x * x_upscale_step + (x_upscale_step / 2.0) ) upscale_index", "of the grid the radii grid is computed using, with", "coordinate values. Pixel coordinates are returned as floats such that", "------- ndarray A slimmed grid of 2D (y,x) pixel-value coordinates", "to the pixel they are contained within. The input and", "is at the top left corner of the grid, such", "grid_pixel_centres_2d_from(grid_scaled_2d=grid_scaled_2d, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d = np.zeros((grid_scaled_2d.shape[0],", "2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for y", "Tuple[float, float] ) -> int: distance_to_centre = 0.0 for slim_index", "a 2D grid structure is input. Parameters ---------- extent The", ") for pixel_index in range(grid.shape[0]): if grid_radii[pixel_index] > border_min_radii: closest_pixel_index", "[total_unmasked_pixels, 2]. The pixel coordinate origin is at the top", "such that they are the pixel from the top-left of", "points[:, 1] y = points[:, 0] return 0.5 * np.abs(np.dot(x,", "2). Examples -------- mask = np.array([[True, False, True], [False, False,", "the gird. The scaled grid is defined by an origin", "values are set to zero. This uses a 1D array", "irregular grid of (y,x) coordinates. \"\"\" grid_2d_slim_upscaled = np.zeros( shape=(grid_slim.shape[0]", "the 2D grid will correspond to index 0 of the", "pixel they are contained within. The input and output grids", "[2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2),", "in the 1 index. Masked coordinates are therefore removed and", "range(grid_slim.shape[0]): y_grid = grid_slim[slim_index, 0] x_grid = grid_slim[slim_index, 1] for", "origin=origin ) for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = (", "2, and so forth. Parameters ---------- shape_native The (y,x) shape", "np.ndarray: \"\"\" Convert a native grid of 2D (y,x) scaled", "(sub_size) for y in range(mask_2d.shape[0]): for x in range(mask_2d.shape[1]): if", "the gird. The scaled coordinate origin is defined by the", "grid_scaled_2d_slim = np.zeros((grid_pixels_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin", "to define border pixels. Parameters ---------- grid : Grid2D The", "of the 2D array, which the sub-grid is shifted around.", "-> np.ndarray: \"\"\" For a slimmed 2D grid of shape", "Parameters ---------- grid_2d_slim The 1D grid of values which are", "mapped to a 2D array. Returns ------- (float, float) The", "the first pixel has index 1, its next sub-pixel has", "pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim = grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim=grid_scaled_2d_slim, shape_native=shape_native,", "a 1D array 'slim_to_native' where each index gives the 2D", "sub-array. Returns ------- ndarray A 1D grid of values mapped", "right-wards and downwards, such that for an grid of shape", "int], pixel_scales: Union[float, Tuple[float, float]], sub_size: int, origin: Tuple[float, float]", "both native resolution and therefore have shape (y_pixels, x_pixels, 2).", "np.stack((grid_1d_slim_y, grid_1d_slim_x), axis=-1) def grid_2d_native_from( grid_2d_slim: np.ndarray, mask_2d: np.ndarray, sub_size:", "Tuple[float, float]], sub_size: int, shape_slim: Optional[int] = 0, ) ->", "the border, by comparing its radial distance from the origin", "first value of the 1D array maps to the pixels", "pixel_scales[0] x_scaled = (x - centres_scaled[1]) * pixel_scales[1] for y1", "and has dimensions (total_unmasked_pixels*sub_size**2, 2). Examples -------- mask = np.array([[True,", "Union, Optional from autoarray.structures.arrays.two_d import array_2d_util from autoarray.geometry import geometry_util", "grid_pixels_2d_slim @numba_util.jit() def grid_pixel_indexes_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales:", "grid[:, :] border_origin = np.zeros(2) border_origin[0] = np.mean(border_grid[:, 0]) border_origin[1]", "ndarray A radial set of points sampling the longest distance", "upscaled resolution at which the new grid coordinates are computed.", "+ grid_pixels_2d_slim[slim_index, 1] ) return grid_pixel_indexes_2d_slim @numba_util.jit() def grid_scaled_2d_slim_from( grid_pixels_2d_slim:", "* x_sub_step + (x_sub_step / 2.0) ) sub_index += 1", "edge of the region using the longest path between the", "sub_index += 1 return grid_slim def grid_2d_via_mask_from( mask_2d: np.ndarray, pixel_scales:", "in its slimmed dimensions with shape (total_pixels**2*sub_size**2, 2). y coordinates", "shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0]", "they are outside the border, where the border is defined", "The (y,x) central coordinate which the radial grid is traced", "all pixels are unmasked: - pixel [0,0] of the 2D", "+= 1 return grid_slim def grid_2d_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float,", "coordinates in scaled units which are converted to pixel value", "sub_size=sub_size ) grid_2d_native_x = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 1], mask_2d=mask_2d, sub_size=sub_size )", "sub_size * int((scaled_distance / pixel_scale)) + 1 grid_scaled_2d_slim_radii = np.zeros((shape_slim,", "[1,1]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_pixels_2d_slim=grid_pixels_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\"", "and lowest (most negative) x scaled coordinate on the gird.", "at the top-left, whose native index is [0,0], corresponds to", "np.zeros(grid.shape) grid_relocated[:, :] = grid[:, :] border_origin = np.zeros(2) border_origin[0]", "grid is shifted Returns ------- ndarray A native grid of", "range(len(grid_2d[:, 0])): if (grid_2d[i, 0] - centre[0]) ** 2 +", "return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int],", "at the centre of every pixel unmasked pixel on the", "3.0], [4.0, 4.0]]) grid_pixel_indexes_2d_slim = grid_pixel_indexes_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0,", "np.zeros((grid_scaled_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for", "(y,x) central coordinate which the radial grid is traced outwards", "from the centre in increasing steps of the pixel-scale. 5)", "x_grid - x_upscale_half + x * x_upscale_step + (x_upscale_step /", "= np.array([[True, False, True], [False, False, False] [True, False, True]])", "= grid_2d_slim_via_mask_from( mask_2d=mask_2d, pixel_scales=pixel_scales, sub_size=sub_size, origin=origin ) return grid_2d_native_from( grid_2d_slim=grid_2d_slim,", ":] border_origin = np.zeros(2) border_origin[0] = np.mean(border_grid[:, 0]) border_origin[1] =", "= 0.0 for slim_index in slim_indexes: y = grid_2d_slim[slim_index, 0]", "grid_2d_slim_upscaled[upscale_index, 1] = ( x_grid - x_upscale_half + x *", "mask with shape (total_y_pixels, total_x_pixels) is divided into a finer", "mask (see *mask._border_1d_indexes*). This is performed as follows: 1: Use", "This functions operates as follows: 1) Given the region defined", "finds the longest radial path to the edge of the", "-> np.ndarray: \"\"\" Convert a native grid of 2D (y,x)", "x_sub_step + (x_sub_step / 2.0) ) sub_index += 1 return", "y scaled coordinate and lowest (most negative) x scaled coordinate", "---------- grid_scaled_2d_slim: np.ndarray The slimmed grid of 2D (y,x) coordinates", "the mean value of the grid's y and x coordinates", "corresponding to the (y,x) values of the native 2D mapped", "1D array maps to the pixels [0,1,:] of the native", "4 paths from the (y,x) centre to the edge of", "is larger, use the ratio of radial distances to move", "Convert a slimmed grid of 2d (y,x) scaled coordinates to", "The slimmed grid of (y,x) coordinates in pixel values which", "The scaled coordinate origin is defined by the class attribute", "+ centres_scaled[1] + 0.5 ) return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_centres_2d_slim_from(", "pixel indexes. Pixel coordinates are returned as integers such that", "its inside the border, do nothing). The method can be", "Returns ------- ndarray A sub grid of (y,x) scaled coordinates", "= [0,0], the first value of the 1D array maps", "returned. If 0, the border based on the 2D grid", "array of shape (total_unmasked_pixels*sub_size**2, 2). y coordinates are stored in", "an array of shape (total_unmasked_pixels*sub_size**2, 2). y coordinates are stored", "Using the centre x above, this function finds the longest", "output grids are both of shape (total_pixels, 2). Parameters ----------", "/ sub_size return grid_scaled_2d_slim_radii @numba_util.jit() def grid_pixels_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native:", "the second value of the 1D array maps to the", "y in range(upscale_factor): for x in range(upscale_factor): grid_2d_slim_upscaled[upscale_index, 0] =", "function finds the longest radial path to the edge of", "1] = ( x_grid - x_upscale_half + x * x_upscale_step", "grid of 2d scaled coordinates with dimensions (total_pixels, 2). Examples", "(total_pixels, 2). Examples -------- grid_scaled_2d_slim = np.array([[1.0, 1.0], [2.0, 2.0],", "every pixel unmasked pixel on the 2D mask array. The", "border (if its inside the border, do nothing). The method", "0] = ( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0]) + centres_scaled[0] +", "- If slim_to_native[4] = [1,1], the fifth value of the", "shape_native[1] + grid_pixels_2d_slim[slim_index, 1] ) return grid_pixel_indexes_2d_slim @numba_util.jit() def grid_scaled_2d_slim_from(", "radial coordinates as (y,x) values (where all y values are", "= np.zeros((grid_scaled_2d.shape[0], grid_scaled_2d.shape[1], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin", "with a (y,x) centre. This functions operates as follows: 1)", "mask_2d[y, x]: y_scaled = (y - centres_scaled[0]) * pixel_scales[0] x_scaled", "The (y,x) shape of the 2D array the sub-grid of", "to pixel units conversion factor of the 2D mask array.", "is used). 3) Determine the number of pixels between the", "Parameters ---------- grid_2d_native : ndarray The native grid of (y,x)", "into. origin The (y,x) origin of the 2D array, which", "The native grid of 2D (y,x) coordinates in scaled units", "0], mask_2d=mask, sub_size=sub_size ) grid_1d_slim_x = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 1],", "the scaled grid is shifted. Returns ------- ndarray A grid", "None cannot be used as a default value). Returns -------", "the extent in along the positive x-axis. \"\"\" distance_to_positive_x =", "A schematric is shown below: ------------------- | | |<- -", "the native 2D grid. mask_2d A 2D array of bools,", "coordinate on the gird. The scaled grid is defined by", "grid_pixel_indexes_2d_slim = grid_pixel_indexes_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim", "coordinates to determine the origin of the grid. 2: Compute", "to the border (if its inside the border, do nothing).", "scaled units which is converted to pixel indexes. shape_native The", "grid of 2D (y,x) pixel indexes with dimensions (total_pixels, 2).", ") return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int,", "the border. 4: Determine if it is outside the border,", "pixel index 10 if a row has 10 pixels. The", "of the native 2D grid. - If slim_to_native[4] = [1,1],", "[0,0]. Sub-pixels that are part of the same mask array", "pixel values which is converted to scaled coordinates. shape_native The", "= grid_pixel_centres_2d_from(grid_scaled_2d=grid_scaled_2d, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d =", ":] - border_origin[:]) + border_origin[:] ) return grid_relocated @numba_util.jit() def", "directly to the pixel they are contained within. The input", "its radial distance from the origin to its paired border", "for slim_index in range(grid_pixels_2d_slim.shape[0]): grid_pixel_indexes_2d_slim[slim_index] = int( grid_pixels_2d_slim[slim_index, 0] *", "0.0 for slim_index in slim_indexes: y = grid_2d_slim[slim_index, 0] x", "array has dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- mask = np.array([[True,", "origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim = np.zeros((grid_scaled_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from(", "slimmed grid of 2D (y,x) pixel values. Pixel coordinates are", "positive x-axis. \"\"\" distance_to_positive_x = extent[1] - centre[1] distance_to_positive_y =", "Examples -------- mask = np.array([[True, False, True], [False, False, False]", "pixels. The scaled coordinate grid is defined by the class", "grid coordinate from the origin. 3: For every coordinate, find", "scaled_distance == distance_to_negative_y ): pixel_scale = pixel_scales[0] else: pixel_scale =", "attribute origin, and coordinates are shifted to this origin after", "of shape (3,3) where all pixels are unmasked: - pixel", "For a slimmed 2D grid of shape [total_unmasked_pixels, 2], that", "= longest radial path from centre to extent edge |", "index 1, its next sub-pixel has index 2, and so", "pixel of the 2D mask array is divided into. origin", "grid. Parameters ---------- grid_2d_slim The (y,x) values of the slimmed", "coordinates of a grid to its border if they are", "grid_slim[sub_index, 0] = -( y_scaled - y_sub_half + y1 *", "which are mapped to the native 2D grid. mask_2d A", "slim_to_native[0] = [0,0], the first value of the 1D array", "axis=-1) @numba_util.jit() def grid_2d_slim_upscaled_from( grid_slim: np.ndarray, upscale_factor: int, pixel_scales: Union[float,", "and the x values iterate from the centre in increasing", ") return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_indexes_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int,", "border of the 'image-plane' mask is used to define border", "y_sub_half = pixel_scales[0] / 2 y_sub_step = pixel_scales[0] / (sub_size)", "grid_2d_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) @numba_util.jit() def grid_scaled_2d_slim_radial_projected_from(", "grid. - pixel [0,1] of the 2D grid will correspond", "the extent window. The returned `grid_radii` represents a radial set", "0 y_upscale_half = pixel_scales[0] / 2 y_upscale_step = pixel_scales[0] /", "0.5), origin=(0.0, 0.0)) \"\"\" grid_scaled_2d_slim = np.zeros((grid_pixels_2d_slim.shape[0], 2)) centres_scaled =", "a radial set of points that in 1D sample the", "opposed to a 1D data structure so that it can", ") return grid_relocated @numba_util.jit() def furthest_grid_2d_slim_index_from( grid_2d_slim: np.ndarray, slim_indexes: np.ndarray,", "the first sub-pixel corresponds to index [0,0]. Sub-pixels that are", "of shape [total_y_pixels, total_x_pixels, 2] corresponding to the (y,x) values", "(y,x) coordinates in scaled units which are converted to pixel", "on the gird. The scaled coordinate grid is defined by", "grid_pixel_indexes_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim = grid_pixel_centres_2d_slim_from(", "where the first sub-pixel corresponds to index [0,0]. Sub-pixels that", "value = 0.0 and the x values iterate from the", "unmasked pixels to a slimmed grid of shape [total_unmasked_pixels, 2].", "= ( x_scaled - x_sub_half + x1 * x_sub_step +", "coordinate to the border (if its inside the border, do", "to a slimmed grid of 2d (y,x) pixel coordinate values.", "2D grid and mask of shape [total_y_pixels, total_x_pixels, 2], map", "Union[float, Tuple[float, float]], sub_size: int, origin: Tuple[float, float] = (0.0,", "with shape (total_y_pixels, total_x_pixels) is divided into a finer uniform", "/ pixel_scales[0]) + centres_scaled[0] + 0.5 ) grid_pixels_2d[y, x, 1]", "values are the same) as opposed to a 1D data", "array has dimensions (total_unmasked_pixels*sub_size**2, 2). Examples -------- mask = np.array([[True,", "grid_pixels_2d @numba_util.jit() def relocated_grid_via_jit_from(grid, border_grid): \"\"\" Relocate the coordinates of", "= 0 y_upscale_half = pixel_scales[0] / 2 y_upscale_step = pixel_scales[0]", "pixel units conversion factor of the 2D mask array. sub_size", "= grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim=grid_scaled_2d_slim, shape_native=shape_native, pixel_scales=pixel_scales, origin=origin, ) grid_pixel_indexes_2d_slim = np.zeros(grid_pixels_2d_slim.shape[0])", "slimmed and has dimensions (total_unmasked_pixels*sub_size**2, 2). Examples -------- mask =", "coordinates at the centre of every pixel unmasked pixel on", "which the scaled grid is shifted Returns ------- ndarray A", "two chosen above. 4) Create a (y,x) grid of radial", "else: pixel_scale = pixel_scales[1] if shape_slim == 0: shape_slim =", "origin=(0.0, 0.0)) \"\"\" return grid_2d_slim_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin,", "grid outwards from its centre. This grid stores the radial", "indexes with dimensions (total_pixels, 2). Examples -------- grid_scaled_2d_slim = np.array([[1.0,", "0] x_grid = grid_slim[slim_index, 1] for y in range(upscale_factor): for", "2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for slim_index", "| <-> = longest radial path from centre to extent", "and therefore shape (total_pixels, 2). The pixel coordinate origin is", "upscaled resolution to each grid coordinate, analogous to a sub-grid.", "(e.g. if the positive x-axis was the longest, the pixel_scale", "to the pixels [0,0,:] of the native 2D grid. -", "scaled grid is defined by an origin and coordinates are", "= pixel_scales[1] / 2 x_upscale_step = pixel_scales[1] / upscale_factor for", "np.zeros((shape_slim, 2)) grid_scaled_2d_slim_radii[:, 0] += centre[0] radii = centre[1] for", "2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5,", "pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d = np.zeros((grid_scaled_2d.shape[0], grid_scaled_2d.shape[1], 2))", "the longest path between the two chosen above. 4) Create", "border_origin[1])), ) ) border_min_radii = np.min(border_grid_radii) grid_radii = np.sqrt( np.add(", "sub-grid is shifted around. Returns ------- ndarray A sub grid", "Parameters ---------- extent The extent of the grid the radii", "A slimmed grid of 2D (y,x) pixel-value coordinates with dimensions", "2) Use the pixel-scale corresponding to the direction chosen (e.g.", "Returns ------- ndarray A grid of slimmed pixel indexes with", "x1 * x_sub_step + (x_sub_step / 2.0) ) sub_index +=", "grid is traced outwards from. pixel_scales The (y,x) scaled units", "ymax], the algorithm finds the longest 1D distance of the", "coordinates are returned as floats such that they include the", "border is defined as all pixels at the edge of", "from a 2D region of coordinates defined by an extent", "0: shape_slim = sub_size * int((scaled_distance / pixel_scale)) + 1", "grid_2d_native_from( grid_2d_slim=grid_2d_slim, mask_2d=mask_2d, sub_size=sub_size ) def grid_2d_slim_via_shape_native_from( shape_native: Tuple[int, int],", "the top left corner of the grid, such that the", "the 2D grid outwards from its centre. This grid stores", "@numba_util.jit() def furthest_grid_2d_slim_index_from( grid_2d_slim: np.ndarray, slim_indexes: np.ndarray, coordinate: Tuple[float, float]", "pixel_scales[0] else: pixel_scale = pixel_scales[1] if shape_slim == 0: shape_slim", "the uniform grid that laid over the irregular grid of", "x_sub_half + x1 * x_sub_step + (x_sub_step / 2.0) )", "+ ( grid_2d[i, 1] - centre[1] ) ** 2 >", "array. Returns ------- (float, float) The (y,x) central coordinates of", "------------------- | | |<- - - - ->x | x", "Tuple[float, float], grid_2d: np.ndarray ): y_inside = [] x_inside =", "2D array. Returns ------- (float, float) The (y,x) central coordinates", "[ distance_to_positive_x, distance_to_positive_y, distance_to_negative_x, distance_to_negative_y, ] ) if (scaled_distance ==", "the border based on the 2D grid is used (due", "of the grid, which the scaled grid is shifted Returns", ") for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = int( (-grid_scaled_2d_slim[slim_index,", "grid pixel indexes. Parameters ---------- grid_pixels_2d_slim: np.ndarray The slimmed grid", "value coordinates. shape_native The (y,x) shape of the original 2D", "= (0.0, 0.0), ) -> np.ndarray: \"\"\" Convert a native", "sub_size=1, origin=(0.0, 0.0)) \"\"\" total_sub_pixels = mask_2d_util.total_sub_pixels_2d_from(mask_2d, sub_size) grid_slim =", "that they map directly to the pixel they are contained", "coordinate and lowest (most negative) x scaled coordinate on the", "array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 1], mask_2d=mask, sub_size=sub_size ) return np.stack((grid_1d_slim_y, grid_1d_slim_x),", "** 2, 2) ) upscale_index = 0 y_upscale_half = pixel_scales[0]", "around. Returns ------- ndarray A slimmed sub grid of (y,x)", "2 + ( grid_2d[i, 1] - centre[1] ) ** 2", "shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d = np.zeros((grid_scaled_2d.shape[0], grid_scaled_2d.shape[1],", "the positive x-axis was the longest, the pixel_scale in the", "scaled units which is converted to slimmed pixel indexes. shape_native", "2D mask array is divided into. origin : (float, flloat)", "the pixel from the top-left of the 2D grid going", "2D grid will correspond to index 0 of the 1D", "geometry_util from autoarray import numba_util from autoarray.mask import mask_2d_util @numba_util.jit()", "on the 2D grid is used (due to numba None", "------- ndarray A slimmed grid of 2d scaled coordinates with", "of shape [total_unmasked_pixels, 2]. The pixel coordinate origin is at", "from autoarray.structures.arrays.two_d import array_2d_util from autoarray.geometry import geometry_util from autoarray", "a sub-grid, every unmasked pixel of its 2D mask with", "corresponds to slimmed pixel index 0. The fifth pixel on", "+ np.min(grid_2d_slim[:, 1])) / 2.0 return centre_y, centre_x @numba_util.jit() def", "range(mask_2d.shape[0]): for x in range(mask_2d.shape[1]): if not mask_2d[y, x]: y_scaled", "The sub-grid is returned on an array of shape (total_unmasked_pixels*sub_size**2,", "y coordinates are stored in the 0 index of the", "a 2D array. Returns ------- (float, float) The (y,x) central", "of 2D (y,x) pixel indexes with dimensions (total_pixels, 2). Examples", "shape_slim == 0: shape_slim = sub_size * int((scaled_distance / pixel_scale))", "computed. pixel_scales The pixel scale of the uniform grid that", "@numba_util.jit() def grid_2d_slim_upscaled_from( grid_slim: np.ndarray, upscale_factor: int, pixel_scales: Union[float, Tuple[float,", "therefore removed and not included in the slimmed grid. Grid2D", "The input and output grids are both slimmed and have", "set to zero. This uses a 1D array 'slim_to_native' where", "second sub-pixel in the first pixel has index 1, its", "np.asarray(y_inside, x_inside) def compute_polygon_area(points): x = points[:, 1] y =", "of 2D (y,x) pixel indexes with dimensions (y_pixels, x_pixels, 2).", "array. sub_size The size of the sub-grid that each pixel", "If slim_to_native[0] = [0,0], the first value of the 1D", "on uniform or irregular grids, however for irregular grids the", "return grid_slim def grid_2d_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float, Tuple[float, float]],", "from. pixel_scales The (y,x) scaled units to pixel units conversion", "1] y = points[:, 0] return 0.5 * np.abs(np.dot(x, np.roll(y,", "mask array. The sub grid array has dimensions (total_unmasked_pixels*sub_size**2, 2).", "== distance_to_negative_y ): pixel_scale = pixel_scales[0] else: pixel_scale = pixel_scales[1]", "on the gird. The scaled coordinate origin is defined by", "pixel_scale = pixel_scales[0] else: pixel_scale = pixel_scales[1] if shape_slim ==", "[False, False, False] [True, False, True]]) grid_2d_slim = grid_2d_slim_via_shape_native_from(shape_native=(3,3), pixel_scales=(0.5,", "at the centre's y value = 0.0 and the x", "2D mask array. The sub grid array has dimensions (total_y_pixels*sub_size,", "range(grid.shape[0]): if grid_radii[pixel_index] > border_min_radii: closest_pixel_index = np.argmin( np.square(grid[pixel_index, 0]", "of the 1D projected grid that is returned. If 0,", "index is [0,1], has slimmed pixel index 10 if a", "sub_size=sub_size ) return np.stack((grid_2d_native_y, grid_2d_native_x), axis=-1) @numba_util.jit() def grid_2d_slim_upscaled_from( grid_slim:", "is computed using, with format [xmin, xmax, ymin, ymax] centre", "\"\"\" grid_pixels_2d = np.zeros((grid_scaled_2d.shape[0], grid_scaled_2d.shape[1], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native,", "coordinate which the radial grid is traced outwards from. pixel_scales", "origin and coordinates are shifted to this origin before computing", "\"\"\" From an input slimmed 2D grid, return an upscaled", "irregular) whose pixels are to be relocated to the border", "the 2D mask array. sub_size The size of the sub-grid", "1], border_origin[1])), ) ) for pixel_index in range(grid.shape[0]): if grid_radii[pixel_index]", "native 2D grid. mask_2d A 2D array of bools, where", "of the 2D array the sub-grid of coordinates is computed", "centres_scaled[0] - 0.5) * pixel_scales[0] ) grid_scaled_2d_slim[slim_index, 1] = (", "distance_to_centre_new >= distance_to_centre: distance_to_centre = distance_to_centre_new furthest_grid_2d_slim_index = slim_index return", "is divided into a finer uniform grid of shape (total_y_pixels*sub_size,", "relative to the input scaled coordinate. The input and output", "total_x_pixels, 2] corresponding to the (y,x) values of the native", "= pixel_scales[0] / 2 y_upscale_step = pixel_scales[0] / upscale_factor x_upscale_half", "by the extent [xmin, xmax, ymin, ymax], the algorithm finds", "a slimmed grid of 2D (y,x) pixel coordinates to a", "* x_upscale_step + (x_upscale_step / 2.0) ) upscale_index += 1", "y = points[:, 0] return 0.5 * np.abs(np.dot(x, np.roll(y, 1))", "origin=(0.0, 0.0)) \"\"\" grid_2d_slim = grid_2d_slim_via_mask_from( mask_2d=mask_2d, pixel_scales=pixel_scales, sub_size=sub_size, origin=origin", "the 'image-plane' mask is used to define border pixels. Parameters", "float]], origin: Tuple[float, float] = (0.0, 0.0), ) -> np.ndarray:", "the x dimension is used). 3) Determine the number of", "and then downwards. The input and output grids are both", "native 2D grid. - If slim_to_native[1] = [0,1], the second", "native 2D grid of shape [total_y_pixels, total_x_pixels, 2], map the", "routine computes the (y,x) scaled coordinates at the centre of", "2 x_sub_step = pixel_scales[1] / (sub_size) for y in range(mask_2d.shape[0]):", "forth. Parameters ---------- shape_native The (y,x) shape of the 2D", "of coordinates is computed for. pixel_scales The (y,x) scaled units", "grid is overlaid. upscale_factor The upscaled resolution at which the", "grid_pixels_2d_slim[slim_index, 0] = int( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0]) + centres_scaled[0]", "This uses a 1D array 'slim_to_native' where each index gives", "value of the 1D array maps to the pixels [0,1,:]", "grid_pixels_2d_slim = grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim=grid_scaled_2d_slim, shape_native=shape_native, pixel_scales=pixel_scales, origin=origin, ) grid_pixel_indexes_2d_slim =", "Manually choose the shape of the 1D projected grid that", "going rights and then downwards. The input and output grids", "the grid's mask (see *mask._border_1d_indexes*). This is performed as follows:", "range(upscale_factor): grid_2d_slim_upscaled[upscale_index, 0] = ( y_grid + y_upscale_half - y", "distance_to_positive_y) or ( scaled_distance == distance_to_negative_y ): pixel_scale = pixel_scales[0]", "in range(mask_2d.shape[0]): for x in range(mask_2d.shape[1]): if not mask_2d[y, x]:", "by the class attribute origin, and coordinates are shifted to", "sub_size=2, origin=(0.0, 0.0)) \"\"\" return grid_2d_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size,", "the longest radial path to the edge of the extent", "sub-pixel defined by this 2D mask array. The sub-grid is", "shifted around. Returns ------- ndarray A sub grid of (y,x)", "the 1D projected grid that is returned. If 0, the", "the extent [xmin, xmax, ymin, ymax], the algorithm finds the", "np.add( np.square(np.subtract(grid[:, 0], border_origin[0])), np.square(np.subtract(grid[:, 1], border_origin[1])), ) ) for", "y_inside.append(grid_2d[i, 0]) x_inside.append(grid_2d[i, 1]) return np.asarray(y_inside, x_inside) def compute_polygon_area(points): x", "2D (y,x) coordinates in scaled units which are converted to", "): y_inside = [] x_inside = [] for i in", "2D grid of shape [total_unmasked_pixels, 2], that was computed by", "np.mean(border_grid[:, 1]) border_grid_radii = np.sqrt( np.add( np.square(np.subtract(border_grid[:, 0], border_origin[0])), np.square(np.subtract(border_grid[:,", "Relocate the coordinates of a grid to its border if", "do nothing). The method can be used on uniform or", "( x_scaled - x_sub_half + x1 * x_sub_step + (x_sub_step", "The upscaled resolution at which the new grid coordinates are", "= array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 0], mask_2d=mask_2d, sub_size=sub_size ) grid_2d_native_x = array_2d_util.array_2d_native_from(", ": (float, flloat) The (y,x) origin of the grid, which", "pixel value coordinates. shape_native The (y,x) shape of the original", "sub_size=1, origin=(0.0, 0.0)) \"\"\" grid_2d_slim = grid_2d_slim_via_mask_from( mask_2d=mask_2d, pixel_scales=pixel_scales, sub_size=sub_size,", "corresponds to slimmed pixel index 4. The first pixel on", "origin, and coordinates are shifted to this origin after computing", "numba_util from autoarray.mask import mask_2d_util @numba_util.jit() def grid_2d_centre_from(grid_2d_slim: np.ndarray) ->", "(y,x) pixel-value coordinates with dimensions (total_pixels, 2). Examples -------- grid_scaled_2d_slim", "slimmed grid of 2d scaled coordinates with dimensions (total_pixels, 2).", "of each unmasked pixels sub-array. Returns ------- ndarray A NumPy", "1]) + np.min(grid_2d_slim[:, 1])) / 2.0 return centre_y, centre_x @numba_util.jit()", "axes). 2) Use the pixel-scale corresponding to the direction chosen", "-> np.ndarray: \"\"\" Determine a projected radial grid of points", "grid of shape (3,3) where all pixels are unmasked: -", "The extent of the grid the radii grid is computed", "y_sub_step = pixel_scales[0] / (sub_size) x_sub_half = pixel_scales[1] / 2", "ndarray A slimmed grid of 2D (y,x) pixel-value coordinates with", "grid_relocated[pixel_index, :] = ( move_factor * (grid[pixel_index, :] - border_origin[:])", "upscaled slimmed 2D grid where (y,x) coordinates are added at", "( y_grid + y_upscale_half - y * y_upscale_step - (y_upscale_step", "units which is converted to slimmed pixel indexes. shape_native The", "shape [total_unmasked_pixels, 2]. The pixel coordinate origin is at the", "maps to the pixels [1,1,:] of the native 2D grid.", "include the decimal offset from each pixel's top-left corner relative", "of radial points where all points are at the centre's", "of (y,x) coordinates in pixel values which is converted to", "(total_y_pixels*sub_size, total_x_pixels*sub_size). This routine computes the (y,x) scaled coordinates at", "+ 0.5 ) return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_indexes_2d_slim_from( grid_scaled_2d_slim: np.ndarray,", "on the second row, whose native index is [0,1], has", "are returned as integers such that they are the pixel", "x_sub_half = pixel_scales[1] / 2 x_sub_step = pixel_scales[1] / (sub_size)", "whose native index is [0,1], has slimmed pixel index 10", "grid_scaled_2d: np.ndarray The native grid of 2D (y,x) coordinates in", "the same) as opposed to a 1D data structure so", "grid to its border if they are outside the border,", "int, shape_slim: Optional[int] = 0, ) -> np.ndarray: \"\"\" Determine", "to slimmed pixel index 4. The first pixel on the", "( move_factor * (grid[pixel_index, :] - border_origin[:]) + border_origin[:] )", "2D pixel indexes of the grid's native unmasked pixels, for", "= grid_scaled_2d_slim_from(grid_pixels_2d_slim=grid_pixels_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_scaled_2d_slim =", "a (y,x) centre. This functions operates as follows: 1) Given", "2). Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed grid of 2D", "y1 * y_sub_step + (y_sub_step / 2.0) ) grid_slim[sub_index, 1]", "which require that a 2D grid structure is input. Parameters", "pixel_scales: Union[float, Tuple[float, float]], sub_size: int, origin: Tuple[float, float] =", "to index 1 of the 1D grid. - pixel [1,0]", "scaled units to pixel units conversion factor of the original", "to a slimmed grid of 2D (y,x) pixel values. Pixel", "np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixels_2d_slim =", "np.square(np.subtract(grid[:, 1], border_origin[1])), ) ) for pixel_index in range(grid.shape[0]): if", "pixel are indexed next to one another, such that the", "\"\"\" grid_2d_native_y = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 0], mask_2d=mask_2d, sub_size=sub_size ) grid_2d_native_x", "window. The returned `grid_radii` represents a radial set of points", "the top left corner of the native grid and goes", "slim_indexes: y = grid_2d_slim[slim_index, 0] x = grid_2d_slim[slim_index, 1] distance_to_centre_new", "to the border edge if outside it. border_grid : Grid2D", "a slimmed 2D grid of shape [total_unmasked_pixels, 2], that was", "index [0,0]. Sub-pixels that are part of the same mask", "origin=origin ) for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_scaled_2d_slim[slim_index, 0] = (", "x coordinates in the 1 index. Grids are defined from", "centre to the edge of the extent in along the", "values of the slimmed 2D grid which are mapped to", "the centre of a grid from a 1D grid. Parameters", "total_sub_pixels = mask_2d_util.total_sub_pixels_2d_from(mask_2d, sub_size) grid_slim = np.zeros(shape=(total_sub_pixels, 2)) centres_scaled =", "the edge of the extent in along the positive x-axis.", "total_x_pixels, 2], map the slimmed grid's coordinates back to the", "index 2, and so forth. Parameters ---------- shape_native The (y,x)", "coordinates in the 1 index. Grids are defined from the", "/ 2 x_sub_step = pixel_scales[1] / (sub_size) for y in", "this 2D mask array. The sub-grid is returned in its", "as integers such that they are the pixel from the", "[1,0] of the 2D grid will correspond to index 4", "overlaid. upscale_factor The upscaled resolution at which the new grid", "+= 1 return grid_2d_slim_upscaled def grid_2d_of_points_within_radius( radius: float, centre: Tuple[float,", "def grid_2d_slim_from( grid_2d_native: np.ndarray, mask: np.ndarray, sub_size: int ) ->", "pixel_scales[0]) + centres_scaled[0] + 0.5 ) grid_pixels_2d_slim[slim_index, 1] = (", "grid_pixels_2d_slim[slim_index, 0] * shape_native[1] + grid_pixels_2d_slim[slim_index, 1] ) return grid_pixel_indexes_2d_slim", "np.min(grid_2d_slim[:, 0])) / 2.0 centre_x = (np.max(grid_2d_slim[:, 1]) + np.min(grid_2d_slim[:,", "centres_scaled[0]) * pixel_scales[0] x_scaled = (x - centres_scaled[1]) * pixel_scales[1]", "pixel_scales[0]) + centres_scaled[0] + 0.5 ) grid_pixels_2d_slim[slim_index, 1] = int(", "y_grid + y_upscale_half - y * y_upscale_step - (y_upscale_step /", "grid_slim: np.ndarray, upscale_factor: int, pixel_scales: Union[float, Tuple[float, float]], ) ->", "shape (total_y_pixels, total_x_pixels) is divided into a finer uniform grid", "of the extent window. The returned `grid_radii` represents a radial", "therefore included as part of the calculated sub-grid. pixel_scales The", "below: ------------------- | | |<- - - - ->x |", "the 2D mask array is divided into. shape_slim Manually choose", "Returns ------- ndarray A radial set of points sampling the", "[0,1] of the 2D grid will correspond to index 1", "float]: \"\"\" Returns the centre of a grid from a", "(total_y_pixels*sub_size, total_x_pixels*sub_size). This routine computes the (y,x) scaled coordinates a", "of shape [total_y_pixels, total_x_pixels, 2], map the values of all", "grid with dimensions (total_unmasked_pixels). \"\"\" grid_1d_slim_y = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :,", "to the pixels [0,1,:] of the native 2D grid. -", "grid will correspond to index 1 of the 1D grid.", "mapped from the slimmed grid. \"\"\" grid_2d_native_y = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:,", "mask_2d=mask, sub_size=sub_size ) grid_1d_slim_x = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 1], mask_2d=mask,", "np.ndarray The slimmed grid of 2D (y,x) coordinates in scaled", "/ 2.0) ) sub_index += 1 return grid_slim def grid_2d_via_mask_from(", "grid (uniform or irregular) whose pixels are to be relocated", "second dimension, x coordinates in the 1 index. Grids are", "and with a (y,x) centre. This functions operates as follows:", "is [0,1], has slimmed pixel index 10 if a row", "of the 2D mask array is divided into. origin The", "grid_2d_slim[slim_index, 0] x = grid_2d_slim[slim_index, 1] distance_to_centre_new = (x -", "the 1D array maps to the pixels [0,0,:] of the", "- x_upscale_half + x * x_upscale_step + (x_upscale_step / 2.0)", "np.square(grid[pixel_index, 1] - border_grid[:, 1]) ) move_factor = ( border_grid_radii[closest_pixel_index]", "used). 3) Determine the number of pixels between the centre", "the highest (most positive) y scaled coordinate and lowest (most", "border_origin[0])), np.square(np.subtract(grid[:, 1], border_origin[1])), ) ) for pixel_index in range(grid.shape[0]):", "border based on the 2D grid is used (due to", "(y,x) origin of the 2D array, which the sub-grid is", "sub-grid is returned on an array of shape (total_unmasked_pixels*sub_size**2, 2).", "distance_to_negative_y = centre[0] - extent[2] scaled_distance = max( [ distance_to_positive_x,", "slimmed and have shapes (total_pixels, 2) and (total_pixels,). For example:", "pixels. Parameters ---------- grid : Grid2D The grid (uniform or", "to the edge of the region (e.g. following the positive", "grid_scaled_2d = np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]])", "that they include the decimal offset from each pixel's top-left", "native resolution and therefore have shape (y_pixels, x_pixels, 2). The", "coordinates are added at an upscaled resolution to each grid", "both of shape (total_pixels, 2). Parameters ---------- grid_scaled_2d_slim: np.ndarray The", "for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_scaled_2d_slim[slim_index, 0] = ( -(grid_pixels_2d_slim[slim_index, 0]", "flloat) The (y,x) central coordinate which the radial grid is", "of (y,x) values which are mapped to the slimmed grid.", "grid_1d_slim_y = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 0], mask_2d=mask, sub_size=sub_size ) grid_1d_slim_x", "the (y,x) scaled coordinates at the centre of every sub-pixel", "-( y_scaled - y_sub_half + y1 * y_sub_step + (y_sub_step", "the 1 index. Grids are defined from the top-left corner,", "2 > radius ** 2: y_inside.append(grid_2d[i, 0]) x_inside.append(grid_2d[i, 1]) return", "Parameters ---------- grid_scaled_2d: np.ndarray The native grid of 2D (y,x)", "values of all unmasked pixels to a slimmed grid of", "pixels between the centre and the edge of the region", "grid of 2D (y,x) scaled coordinates to a native grid", "grids, however for irregular grids the border of the 'image-plane'", "/ 2 x_upscale_step = pixel_scales[1] / upscale_factor for slim_index in", "move the coordinate to the border (if its inside the", "/ upscale_factor for slim_index in range(grid_slim.shape[0]): y_grid = grid_slim[slim_index, 0]", "scaled grid is shifted Returns ------- ndarray A slimmed grid", "pixels are given values (0.0, 0.0). Grids are defined from", "of the native 2D mapped from the slimmed grid. \"\"\"", "- x_sub_half + x1 * x_sub_step + (x_sub_step / 2.0)", "its native dimensions with shape (total_y_pixels*sub_size, total_x_pixels*sub_size). y coordinates are", "mask_2d_util.total_sub_pixels_2d_from(mask_2d, sub_size) grid_slim = np.zeros(shape=(total_sub_pixels, 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=mask_2d.shape,", "of slimmed pixel indexes with dimensions (total_pixels,). Examples -------- grid_scaled_2d_slim", "integers such that they map directly to the pixel they", "the pixel they are contained within. The input and output", "+ centres_scaled[0] + 0.5 ) grid_pixels_2d[y, x, 1] = int(", "nearest pixel in the border. 4: Determine if it is", "the radial grid is traced outwards from. pixel_scales The (y,x)", "of (y,x) coordinates over which a square uniform grid is", "are computed. pixel_scales The pixel scale of the uniform grid", "slimmed grid of 2D (y,x) scaled values. The input and", "coordinates are shifted to this origin before computing their 1D", "downwards, such that for an grid of shape (3,3) where", "centre : (float, flloat) The (y,x) central coordinate which the", "grid_2d_of_points_within_radius( radius: float, centre: Tuple[float, float], grid_2d: np.ndarray ): y_inside", "of the sub-grid that each pixel of the 2D mask", "(-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0]) + centres_scaled[0] + 0.5 ) grid_pixels_2d_slim[slim_index,", "'image-plane' mask is used to define border pixels. Parameters ----------", "(y,x) values which are mapped to the slimmed grid. mask_2d", "and are included in the mapping. sub_size The size (sub_size", "values from a native 2D grid of shape [total_y_pixels, total_x_pixels,", "which a square uniform grid is overlaid. upscale_factor The upscaled", "x_inside = [] for i in range(len(grid_2d[:, 0])): if (grid_2d[i,", "= np.zeros((shape_slim, 2)) grid_scaled_2d_slim_radii[:, 0] += centre[0] radii = centre[1]", "Convert a slimmed grid of 2D (y,x) pixel coordinates to", "coordinates a the centre of every sub-pixel defined by this", "(total_pixels,). For example: The pixel at the top-left, whose native", "dimensions (total_pixels, 2). Examples -------- grid_pixels_2d_slim = np.array([[0,0], [0,1], [1,0],", "each pixel of the 2D mask array is divided into.", "pixel_scale)) + 1 grid_scaled_2d_slim_radii = np.zeros((shape_slim, 2)) grid_scaled_2d_slim_radii[:, 0] +=", "1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim,", "by comparing its radial distance from the origin to its", "@numba_util.jit() def grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float,", "coordinate on the gird. The scaled coordinate origin is defined", "in scaled units which are converted to pixel value coordinates.", "return grid_pixels_2d @numba_util.jit() def relocated_grid_via_jit_from(grid, border_grid): \"\"\" Relocate the coordinates", "defined by the extent [xmin, xmax, ymin, ymax], the algorithm", "2D grid. - If slim_to_native[1] = [0,1], the second value", "pixel indexes. Parameters ---------- grid_pixels_2d_slim: np.ndarray The slimmed grid of", "grid_2d = grid_2d_via_shape_native_from(shape_native=(3, 3), pixel_scales=(1.0, 1.0), sub_size=2, origin=(0.0, 0.0)) \"\"\"", "/ pixel_scale)) + 1 grid_scaled_2d_slim_radii = np.zeros((shape_slim, 2)) grid_scaled_2d_slim_radii[:, 0]", "A 2D array of bools, where `False` values mean unmasked", "data structure so that it can be used in functions", "the 2D grid will correspond to index 4 of the", "be used on uniform or irregular grids, however for irregular", "of the grid's native unmasked pixels, for example: - If", "y_upscale_half - y * y_upscale_step - (y_upscale_step / 2.0) )", "(x_sub_step / 2.0) ) sub_index += 1 return grid_slim def", "top left corner of the native grid and goes right-wards", "2.0) ) grid_2d_slim_upscaled[upscale_index, 1] = ( x_grid - x_upscale_half +", "of every sub-pixel defined by this 2D mask array. The", "pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\" total_sub_pixels = mask_2d_util.total_sub_pixels_2d_from(mask_2d, sub_size)", "uniform or irregular grids, however for irregular grids the border", "(total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- mask = np.array([[True, False, True], [False,", "centre's y value = 0.0 and the x values iterate", "edge if outside it. border_grid : Grid2D The grid of", "of the 1D array maps to the pixels [0,1,:] of", "of the 'image-plane' mask is used to define border pixels.", "pixel-scale. 5) Rotate these radial coordinates by the input `angle`", "pixel_scale in the x dimension is used). 3) Determine the", "shape (total_y_pixels*sub_size, total_x_pixels*sub_size). This routine computes the (y,x) scaled coordinates", "if the positive x-axis was the longest, the pixel_scale in", "1 index. Masked pixels are given values (0.0, 0.0). Grids", "np.ndarray: \"\"\" For a slimmed 2D grid of shape [total_unmasked_pixels,", "2.0) ) sub_index += 1 return grid_slim def grid_2d_via_mask_from( mask_2d:", "original 2D array the scaled coordinates were computed on. pixel_scales", "it is outside the border, by comparing its radial distance", "The sub grid array has dimensions (total_unmasked_pixels*sub_size**2, 2). Examples --------", "grids are both of shape (total_pixels, 2). Parameters ---------- grid_scaled_2d_slim:", "a row has 10 pixels. The scaled coordinate grid is", "sub-grid that each pixel of the 2D mask array is", ") return np.stack((grid_2d_native_y, grid_2d_native_x), axis=-1) @numba_util.jit() def grid_2d_slim_upscaled_from( grid_slim: np.ndarray,", "Tuple, Union, Optional from autoarray.structures.arrays.two_d import array_2d_util from autoarray.geometry import", "x_scaled - x_sub_half + x1 * x_sub_step + (x_sub_step /", "scaled coordinates to a slimmed grid of 2d (y,x) pixel", ") return np.stack((grid_1d_slim_y, grid_1d_slim_x), axis=-1) def grid_2d_native_from( grid_2d_slim: np.ndarray, mask_2d:", "grid is used (due to numba None cannot be used", "Union[float, Tuple[float, float]], origin: Tuple[float, float] = (0.0, 0.0), )", "grid is defined by an origin and coordinates are shifted", "= np.min(border_grid_radii) grid_radii = np.sqrt( np.add( np.square(np.subtract(grid[:, 0], border_origin[0])), np.square(np.subtract(grid[:,", "autoarray.mask import mask_2d_util @numba_util.jit() def grid_2d_centre_from(grid_2d_slim: np.ndarray) -> Tuple[float, float]:", "corner of the native grid and goes right-wards and downwards,", "the shape of the 1D projected grid that is returned.", "paired border pixel's radial distance. 5: If its radial distance", "the longest distance from the centre to the edge of", "border_origin[:] ) return grid_relocated @numba_util.jit() def furthest_grid_2d_slim_index_from( grid_2d_slim: np.ndarray, slim_indexes:", "sub grid array has dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- grid_2d", "From an input slimmed 2D grid, return an upscaled slimmed", "0] = ( y_grid + y_upscale_half - y * y_upscale_step", "offset from each pixel's top-left corner relative to the input", "/ 2.0) ) grid_slim[sub_index, 1] = ( x_scaled - x_sub_half", "fifth pixel on the top row, whose native index is", "this origin before computing their 1D grid pixel indexes. The", "(3,3) where all pixels are unmasked: - pixel [0,0] of", "grid_pixels_2d_slim: np.ndarray The slimmed grid of (y,x) coordinates in pixel", "second dimension, x coordinates in the 1 index. Masked coordinates", "scaled coordinates a the centre of every sub-pixel defined by", "pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_scaled_2d_slim = np.zeros((grid_pixels_2d_slim.shape[0], 2)) centres_scaled", "part of the calculated sub-grid. pixel_scales The (y,x) scaled units", "| | |<- - - - ->x | x =", "slimmed grid of pixel indexes. Pixel coordinates are returned as", "1D distance of the 4 paths from the (y,x) centre", "0, ) -> np.ndarray: \"\"\" Determine a projected radial grid", "of the grid, which the scaled grid is shifted to.", "the pixels [0,1,:] of the native 2D grid. - If", "removed and not included in the slimmed grid. Grid2D are", "from the top-left corner, where the first sub-pixel corresponds to", "ymin, ymax] centre : (float, flloat) The (y,x) central coordinate", "3: For every coordinate, find its nearest pixel in the", "unmasked pixel on the 2D mask array. The sub grid", "2D grid outwards from its centre. This grid stores the", "and coordinates are shifted to this origin before computing their", "and goes right-wards and downwards, such that for an grid", "outside the border, where the border is defined as all", "outwards from its centre. This grid stores the radial coordinates", "(grid_scaled_2d[y, x, 1] / pixel_scales[1]) + centres_scaled[1] + 0.5 )", "mask is used to define border pixels. Parameters ---------- grid", "slim_index in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = int( (-grid_scaled_2d_slim[slim_index, 0] /", "the sub-grid is shifted around. Returns ------- ndarray A sub", "] ) if (scaled_distance == distance_to_positive_y) or ( scaled_distance ==", "y and x coordinates to determine the origin of the", "1 index. Grid2D are defined from the top-left corner, where", "slimmed grid of 2D (y,x) pixel indexes with dimensions (total_pixels,", "set of points that in 1D sample the 2D grid", "index 1 of the 1D grid. - pixel [1,0] of", "and the edge of the region using the longest path", "lowest (most negative) x scaled coordinate on the gird. The", "the native 2D grid. - If slim_to_native[1] = [0,1], the", "The grid (uniform or irregular) whose pixels are to be", "@numba_util.jit() def grid_scaled_2d_slim_radial_projected_from( extent: np.ndarray, centre: Tuple[float, float], pixel_scales: Union[float,", "edge of the region (e.g. following the positive / negative", "the pixels [0,0,:] of the native 2D grid. - If", "= ( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1]) + centres_scaled[1] + 0.5", "-(grid_pixels_2d_slim[slim_index, 0] - centres_scaled[0] - 0.5) * pixel_scales[0] ) grid_scaled_2d_slim[slim_index,", "numpy as np from typing import Tuple, Union, Optional from", "ndarray A grid of slimmed pixel indexes with dimensions (total_pixels,).", "scaled values. The input and output grids are both slimmed", "that a 2D grid structure is input. Parameters ---------- extent", "mask array. sub_size The size of the sub-grid that each", "mask array. The sub-grid is returned in its native dimensions", "A radial set of points sampling the longest distance from", "grid_scaled_2d_slim_from(grid_pixels_2d_slim=grid_pixels_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_scaled_2d_slim = np.zeros((grid_pixels_2d_slim.shape[0],", "maps to the pixels [0,1,:] of the native 2D grid.", "pixel_scales[0] / 2 y_upscale_step = pixel_scales[0] / upscale_factor x_upscale_half =", "one another, such that the second sub-pixel in the first", "ymin, ymax], the algorithm finds the longest 1D distance of", "\"\"\" Convert a native grid of 2D (y,x) scaled coordinates", "total_x_pixels*sub_size). y coordinates are stored in the 0 index of", "[] for i in range(len(grid_2d[:, 0])): if (grid_2d[i, 0] -", "** 2: y_inside.append(grid_2d[i, 0]) x_inside.append(grid_2d[i, 1]) return np.asarray(y_inside, x_inside) def", "index 2, and so forth. Parameters ---------- mask_2d A 2D", "grid of slimmed pixel indexes with dimensions (total_pixels,). Examples --------", "array. The sub-grid is returned on an array of shape", "Grid2D The grid of border (y,x) coordinates. \"\"\" grid_relocated =", "xmax, ymin, ymax] centre : (float, flloat) The (y,x) central", "def grid_pixel_indexes_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float,", "in along the positive x-axis. \"\"\" distance_to_positive_x = extent[1] -", "pixel_scales[0]) + centres_scaled[0] + 0.5 ) grid_pixels_2d[y, x, 1] =", "1 index. Grids are defined from the top-left corner, where", "centre[1] - extent[0] distance_to_negative_y = centre[0] - extent[2] scaled_distance =", "origin before computing their 1D grid pixel indexes. Parameters ----------", "pixel's top-left corner relative to the input scaled coordinate. The", "on the 2D mask array. The sub grid array has", "mapping. sub_size The size (sub_size x sub_size) of each unmasked", "Tuple[float, float], pixel_scales: Union[float, Tuple[float, float]], sub_size: int, shape_slim: Optional[int]", "origin=origin ) return grid_2d_native_from( grid_2d_slim=grid_2d_slim, mask_2d=mask_2d, sub_size=sub_size ) def grid_2d_slim_via_shape_native_from(", "indexes of the grid's native unmasked pixels, for example: -", "* upscale_factor ** 2, 2) ) upscale_index = 0 y_upscale_half", "array. origin : (float, flloat) The (y,x) origin of the", "0.5 ) return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_indexes_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native:", "float) The (y,x) central coordinates of the grid. \"\"\" centre_y", "pixel_scales[1] / 2 x_sub_step = pixel_scales[1] / (sub_size) for y", "range(grid_scaled_2d_slim.shape[0]): grid_scaled_2d_slim[slim_index, 0] = ( -(grid_pixels_2d_slim[slim_index, 0] - centres_scaled[0] -", "comparing its radial distance from the origin to its paired", "for y in range(mask_2d.shape[0]): for x in range(mask_2d.shape[1]): if not", "corresponding to the direction chosen (e.g. if the positive x-axis", "the positive / negative y and x axes). 2) Use", "and x coordinates to determine the origin of the grid.", "of the uniform grid that laid over the irregular grid", "in range(grid_scaled_2d.shape[0]): for x in range(grid_scaled_2d.shape[1]): grid_pixels_2d[y, x, 0] =", "where the first unmasked sub-pixel corresponds to index 0. Sub-pixels", "x_pixels, 2). The pixel coordinate origin is at the top", "in range(grid_scaled_2d.shape[1]): grid_pixels_2d[y, x, 0] = int( (-grid_scaled_2d[y, x, 0]", "(y,x) scaled coordinates to a slimmed grid of 2d (y,x)", "they are the pixel from the top-left of the 2D", "centre to extent edge | | ------------------- Using the centre", "For every coordinate, find its nearest pixel in the border.", "by this 2D mask array. The sub-grid is returned in", "indexes. Parameters ---------- grid_pixels_2d_slim: np.ndarray The slimmed grid of (y,x)", "is returned on an array of shape (total_unmasked_pixels*sub_size**2, 2). y", "relocated_grid_via_jit_from(grid, border_grid): \"\"\" Relocate the coordinates of a grid to", "returned in its slimmed dimensions with shape (total_pixels**2*sub_size**2, 2). y", "| |<- - - - ->x | x = centre", "divided into. shape_slim Manually choose the shape of the 1D", ") grid_pixel_indexes_2d_slim = np.zeros(grid_pixels_2d_slim.shape[0]) for slim_index in range(grid_pixels_2d_slim.shape[0]): grid_pixel_indexes_2d_slim[slim_index] =", "the original 2D array the scaled coordinates were computed on.", "a projected radial grid of points from a 2D region", "grid_scaled_2d_slim_radii[:, 0] += centre[0] radii = centre[1] for slim_index in", "0], border_origin[0])), np.square(np.subtract(grid[:, 1], border_origin[1])), ) ) for pixel_index in", "forth. Parameters ---------- mask_2d A 2D array of bools, where", "array of shape [total_y_pixels, total_x_pixels, 2] corresponding to the (y,x)", "the sub-grid of coordinates is computed for. pixel_scales The (y,x)", "are returned as floats such that they include the decimal", "origin=(0.0, 0.0)) \"\"\" return grid_2d_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin,", "radial distance of every grid coordinate from the origin. 3:", "x scaled coordinate on the gird. The scaled coordinate origin", "the slimmed grid. Grid2D are defined from the top-left corner,", "/ pixel_scales[1]) + centres_scaled[1] + 0.5 ) return grid_pixels_2d @numba_util.jit()", "schematric is shown below: ------------------- | | |<- - -", "y_sub_step + (y_sub_step / 2.0) ) grid_slim[sub_index, 1] = (", "coordinates. shape_native The (y,x) shape of the original 2D array", "Returns ------- ndarray A native grid of 2D (y,x) pixel", "---------- shape_native The (y,x) shape of the 2D array the", "the slimmed grid's coordinates back to the native 2D grid", "the coordinate to the border (if its inside the border,", "is [0,0], corresponds to slimmed pixel index 0. The fifth", "in range(upscale_factor): grid_2d_slim_upscaled[upscale_index, 0] = ( y_grid + y_upscale_half -", "Parameters ---------- grid_pixels_2d_slim: np.ndarray The slimmed grid of (y,x) coordinates", "= ( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0]) + centres_scaled[0] + 0.5", "grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim", "(sub_size) x_sub_half = pixel_scales[1] / 2 x_sub_step = pixel_scales[1] /", "the 1 index. Masked pixels are given values (0.0, 0.0).", "(total_pixels, 2). The pixel coordinate origin is at the top", "- centres_scaled[1]) * pixel_scales[1] for y1 in range(sub_size): for x1", "find its nearest pixel in the border. 4: Determine if", "The pixel at the top-left, whose native index is [0,0],", "1D grid pixel coordinate values. Parameters ---------- grid_scaled_2d_slim: np.ndarray The", "of the original 2D array. origin : (float, flloat) The", "(y - coordinate[0]) ** 2 if distance_to_centre_new >= distance_to_centre: distance_to_centre", "grid. Parameters ---------- grid_2d_slim The 1D grid of values which", "pixel_scales=pixel_scales, origin=origin ) for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] =", ") -> np.ndarray: \"\"\" Convert a native grid of 2D", "+ centres_scaled[0] + 0.5 ) grid_pixels_2d_slim[slim_index, 1] = ( (grid_scaled_2d_slim[slim_index,", "1D data structure so that it can be used in", "of the grid. \"\"\" centre_y = (np.max(grid_2d_slim[:, 0]) + np.min(grid_2d_slim[:,", "radial distance is larger, use the ratio of radial distances", "geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for y in range(grid_scaled_2d.shape[0]): for", "x scaled coordinate on the gird. The scaled grid is", "3.0], [4.0, 4.0]]) grid_pixel_centres_2d = grid_pixel_centres_2d_from(grid_scaled_2d=grid_scaled_2d, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0,", "pixel_scales The pixel scale of the uniform grid that laid", "the top-left corner, where the first sub-pixel corresponds to index", "< 1.0: grid_relocated[pixel_index, :] = ( move_factor * (grid[pixel_index, :]", "def grid_2d_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], sub_size:", "are included in the mapping. sub_size The size (sub_size x", "pixels [1,1,:] of the native 2D grid. Parameters ---------- grid_2d_slim", "grid structure is input. Parameters ---------- extent The extent of", "shape of the 1D projected grid that is returned. If", "slimmed grid of (y,x) coordinates in pixel values which is", "np.square(np.subtract(border_grid[:, 0], border_origin[0])), np.square(np.subtract(border_grid[:, 1], border_origin[1])), ) ) border_min_radii =", "array. The sub grid is slimmed and has dimensions (total_unmasked_pixels*sub_size**2,", "flloat) The (y,x) origin of the grid, which the scaled", "[0,0], the first value of the 1D array maps to", "0]) x_inside.append(grid_2d[i, 1]) return np.asarray(y_inside, x_inside) def compute_polygon_area(points): x =", "the second dimension, x coordinates in the 1 index. Grids", "2D (y,x) scaled values. The input and output grids are", "2D (y,x) scaled coordinates to a slimmed grid of pixel", "computing their values from the 1D grid pixel indexes. Parameters", "of 2d scaled coordinates with dimensions (total_pixels, 2). Examples --------", "grid of (y,x) coordinates. \"\"\" grid_2d_slim_upscaled = np.zeros( shape=(grid_slim.shape[0] *", "in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = int( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0])", "whose native index is [0,5], corresponds to slimmed pixel index", "structure is input. Parameters ---------- extent The extent of the", "with dimensions (total_pixels, 2). Examples -------- grid_pixels_2d_slim = np.array([[0,0], [0,1],", "index. Masked coordinates are therefore removed and not included in", "def grid_2d_slim_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], sub_size:", "into a finer uniform grid of shape (total_y_pixels*sub_size, total_x_pixels*sub_size). This", "= grid_2d_via_shape_native_from(shape_native=(3, 3), pixel_scales=(1.0, 1.0), sub_size=2, origin=(0.0, 0.0)) \"\"\" return", "of the 1D grid. Parameters ---------- grid_2d_native : ndarray The", "NumPy array of shape [total_y_pixels, total_x_pixels, 2] corresponding to the", "geometry_util.central_scaled_coordinate_2d_from( shape_native=mask_2d.shape, pixel_scales=pixel_scales, origin=origin ) sub_index = 0 y_sub_half =", "[True, False, True]]) grid_2d = grid_2d_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0,", "radii grid is computed using, with format [xmin, xmax, ymin,", "next to one another, such that the second sub-pixel in", "origin of the grid, which the scaled grid is shifted", "np.argmin( np.square(grid[pixel_index, 0] - border_grid[:, 0]) + np.square(grid[pixel_index, 1] -", "and output grids are both slimmed and therefore shape (total_pixels,", "grid stores the radial coordinates as (y,x) values (where all", "border_grid_radii = np.sqrt( np.add( np.square(np.subtract(border_grid[:, 0], border_origin[0])), np.square(np.subtract(border_grid[:, 1], border_origin[1])),", "extent[0] distance_to_negative_y = centre[0] - extent[2] scaled_distance = max( [", "border_grid_radii[closest_pixel_index] / grid_radii[pixel_index] ) if move_factor < 1.0: grid_relocated[pixel_index, :]", "to pixel value coordinates. shape_native The (y,x) shape of the", "each grid coordinate, analogous to a sub-grid. Parameters ---------- grid_slim", "= np.array([[0,0], [0,1], [1,0], [1,1]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_pixels_2d_slim=grid_pixels_2d_slim, shape=(2,2), pixel_scales=(0.5,", "units conversion factor of the 2D mask array. sub_size The", ") grid_scaled_2d_slim[slim_index, 1] = ( grid_pixels_2d_slim[slim_index, 1] - centres_scaled[1] -", "grid_scaled_2d_slim: np.ndarray The slimmed grid of 2D (y,x) coordinates in", "computed on. pixel_scales The (y,x) scaled units to pixel units", "resolution and therefore have shape (y_pixels, x_pixels, 2). The pixel", "used as a default value). Returns ------- ndarray A radial", "grid_scaled_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim = np.zeros((grid_scaled_2d_slim.shape[0],", "Returns ------- ndarray A slimmed grid of 2d scaled coordinates", "with dimensions (total_unmasked_pixels). \"\"\" grid_1d_slim_y = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 0],", "pixel [1,0] of the 2D grid will correspond to index", "grid_pixels_2d[y, x, 0] = int( (-grid_scaled_2d[y, x, 0] / pixel_scales[0])", "sub-grid is returned in its slimmed dimensions with shape (total_pixels**2*sub_size**2,", "before computing their 1D grid pixel coordinate values. Parameters ----------", "will correspond to index 4 of the 1D grid. Parameters", "border_min_radii: closest_pixel_index = np.argmin( np.square(grid[pixel_index, 0] - border_grid[:, 0]) +", "grid of shape [total_unmasked_pixels, 2], that was computed by extracting", "all unmasked pixels to a slimmed grid of shape [total_unmasked_pixels,", "to pixel indexes. shape_native The (y,x) shape of the original", "ndarray A NumPy array of shape [total_y_pixels, total_x_pixels, 2] corresponding", "grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim=grid_scaled_2d_slim, shape_native=shape_native, pixel_scales=pixel_scales, origin=origin, ) grid_pixel_indexes_2d_slim = np.zeros(grid_pixels_2d_slim.shape[0]) for", "= [] x_inside = [] for i in range(len(grid_2d[:, 0])):", "the centre to the edge of the extent in along", "of 2D (y,x) pixel coordinates to a slimmed grid of", "True], [False, False, False] [True, False, True]]) grid_slim = grid_2d_slim_via_mask_from(mask=mask,", "is divided into. shape_slim Manually choose the shape of the", "decimal offset from each pixel's top-left corner relative to the", "extent: np.ndarray, centre: Tuple[float, float], pixel_scales: Union[float, Tuple[float, float]], sub_size:", "y values are the same) as opposed to a 1D", "input. Parameters ---------- extent The extent of the grid the", "coordinate origin is at the top left corner of the", "this origin after computing their values from the 1D grid", "coordinate: Tuple[float, float] ) -> int: distance_to_centre = 0.0 for", "edge | | ------------------- Using the centre x above, this", "2D array the scaled coordinates were computed on. pixel_scales The", "x-axis. \"\"\" distance_to_positive_x = extent[1] - centre[1] distance_to_positive_y = extent[3]", "False, True]]) grid_slim = grid_2d_slim_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0))", "import numba_util from autoarray.mask import mask_2d_util @numba_util.jit() def grid_2d_centre_from(grid_2d_slim: np.ndarray)", "the pixel_scale in the x dimension is used). 3) Determine", "The grid of border (y,x) coordinates. \"\"\" grid_relocated = np.zeros(grid.shape)", "shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) def grid_2d_via_shape_native_from( shape_native: Tuple[int, int],", "pixel_scales[0] / upscale_factor x_upscale_half = pixel_scales[1] / 2 x_upscale_step =", "in the 1 index. Grid2D are defined from the top-left", "where all pixels are unmasked: - pixel [0,0] of the", "of the 2D grid will correspond to index 0 of", "ndarray The native grid of (y,x) values which are mapped", "coordinates to a slimmed grid of pixel indexes. Pixel coordinates", "array, which the sub-grid is shifted around. Returns ------- ndarray", "border_origin[1])), ) ) for pixel_index in range(grid.shape[0]): if grid_radii[pixel_index] >", "4. The first pixel on the second row, whose native", "second dimension, x coordinates in the 1 index. Masked pixels", "zero. This uses a 1D array 'slim_to_native' where each index", "grid_2d_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], sub_size: int,", "of the 2D mask array is divided into. origin :", "= ( move_factor * (grid[pixel_index, :] - border_origin[:]) + border_origin[:]", "extent in along the positive x-axis. \"\"\" distance_to_positive_x = extent[1]", "sub_size=sub_size ) grid_1d_slim_x = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 1], mask_2d=mask, sub_size=sub_size", "coordinate origin is defined by the class attribute origin, and", "+ 0.5 ) grid_pixels_2d_slim[slim_index, 1] = ( (grid_scaled_2d_slim[slim_index, 1] /", "grids are both slimmed and have shapes (total_pixels, 2) and", "grid_pixel_centres_2d = grid_pixel_centres_2d_from(grid_scaled_2d=grid_scaled_2d, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d", "The sub grid array has dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples --------", "scaled coordinates to a native grid of 2D (y,x) pixel", "extent edge | | ------------------- Using the centre x above,", "For a native 2D grid and mask of shape [total_y_pixels,", "pixels are unmasked: - pixel [0,0] of the 2D grid", "shifted. Returns ------- ndarray A slimmed grid of 2d scaled", "the unmasked values from a native 2D grid of shape", "coordinate[1]) ** 2 + (y - coordinate[0]) ** 2 if", "coordinates back to the native 2D grid where masked values", "shape [total_unmasked_pixels, 2], that was computed by extracting the unmasked", "( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0]) + centres_scaled[0] + 0.5 )", "the second row, whose native index is [0,1], has slimmed", "2D grid which are mapped to the native 2D grid.", "= centre[0] - extent[2] scaled_distance = max( [ distance_to_positive_x, distance_to_positive_y,", "determine the origin of the grid. 2: Compute the radial", "---------- grid_pixels_2d_slim: np.ndarray The slimmed grid of (y,x) coordinates in", "= pixel_scales[1] / (sub_size) for y in range(mask_2d.shape[0]): for x", "0] - centre[0]) ** 2 + ( grid_2d[i, 1] -", "and therefore have shape (y_pixels, x_pixels, 2). The pixel coordinate", "in range(grid_pixels_2d_slim.shape[0]): grid_pixel_indexes_2d_slim[slim_index] = int( grid_pixels_2d_slim[slim_index, 0] * shape_native[1] +", ") -> int: distance_to_centre = 0.0 for slim_index in slim_indexes:", "return centre_y, centre_x @numba_util.jit() def grid_2d_slim_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float,", "np.sqrt( np.add( np.square(np.subtract(border_grid[:, 0], border_origin[0])), np.square(np.subtract(border_grid[:, 1], border_origin[1])), ) )", "- 0.5 ) * pixel_scales[1] return grid_scaled_2d_slim @numba_util.jit() def grid_pixel_centres_2d_from(", "grid_pixel_indexes_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]],", "are given values (0.0, 0.0). Grids are defined from the", "np.ndarray, pixel_scales: Union[float, Tuple[float, float]], sub_size: int, origin: Tuple[float, float]", "values from the 1D grid pixel indexes. Parameters ---------- grid_pixels_2d_slim:", "maps to the pixels [0,0,:] of the native 2D grid.", "that they are the pixel from the top-left of the", "the pixel [0,0] corresponds to the highest (most positive) y", "x]: y_scaled = (y - centres_scaled[0]) * pixel_scales[0] x_scaled =", "are at the centre's y value = 0.0 and the", "distance from the origin to its paired border pixel's radial", "scaled coordinate on the gird. The scaled coordinate origin is", "sub-array. Returns ------- ndarray A NumPy array of shape [total_y_pixels,", "False] [True, False, True]]) grid_slim = grid_2d_slim_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1,", "from a 1D grid. Parameters ---------- grid_2d_slim The 1D grid", "np.array([[True, False, True], [False, False, False] [True, False, True]]) grid_2d", "an origin and coordinates are shifted to this origin before", ") -> np.ndarray: \"\"\" For a native 2D grid and", "radii = centre[1] for slim_index in range(shape_slim): grid_scaled_2d_slim_radii[slim_index, 1] =", "(0.0, 0.0). Grids are defined from the top-left corner, where", "1, its next sub-pixel has index 2, and so forth.", "Optional[int] = 0, ) -> np.ndarray: \"\"\" Determine a projected", "return furthest_grid_2d_slim_index def grid_2d_slim_from( grid_2d_native: np.ndarray, mask: np.ndarray, sub_size: int", "value of the 1D array maps to the pixels [0,0,:]", "range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = int( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0]) +", "that it can be used in functions which require that", "1] distance_to_centre_new = (x - coordinate[1]) ** 2 + (y", "grid is shifted. Returns ------- ndarray A slimmed grid of", "coordinates in the 1 index. Grid2D are defined from the", "int ) -> np.ndarray: \"\"\" For a slimmed 2D grid", "origin : (float, flloat) The (y,x) origin of the 2D", "array the scaled coordinates were computed on. pixel_scales The (y,x)", "gird. The scaled coordinate grid is defined by the class", "shape_slim Manually choose the shape of the 1D projected grid", "dimensions (total_unmasked_pixels). \"\"\" grid_1d_slim_y = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 0], mask_2d=mask,", "in the 0 index of the second dimension, x coordinates", "Grid2D are defined from the top-left corner, where the first", "grid array has dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- mask =", "the input scaled coordinate. The input and output grids are", "-> np.ndarray: \"\"\" For a native 2D grid and mask", ") -> np.ndarray: \"\"\" Convert a slimmed grid of 2d", "The (y,x) values of the slimmed 2D grid which are", "over the irregular grid of (y,x) coordinates. \"\"\" grid_2d_slim_upscaled =", "0.5 ) grid_pixels_2d_slim[slim_index, 1] = int( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1])", "grid_scaled_2d_slim_radii @numba_util.jit() def grid_pixels_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales:", "The fifth pixel on the top row, whose native index", "\"\"\" grid_2d_slim = grid_2d_slim_via_mask_from( mask_2d=mask_2d, pixel_scales=pixel_scales, sub_size=sub_size, origin=origin ) return", "flloat) The (y,x) origin of the 2D array, which the", "array. The sub-grid is returned in its native dimensions with", "points are at the centre's y value = 0.0 and", "grid_2d_slim: np.ndarray, mask_2d: np.ndarray, sub_size: int ) -> np.ndarray: \"\"\"", "grid_2d_slim_via_shape_native_from(shape_native=(3,3), pixel_scales=(0.5, 0.5), sub_size=2, origin=(0.0, 0.0)) \"\"\" return grid_2d_slim_via_mask_from( mask_2d=np.full(fill_value=False,", "from a native 2D grid of shape [total_y_pixels, total_x_pixels, 2],", "0] - border_grid[:, 0]) + np.square(grid[pixel_index, 1] - border_grid[:, 1])", "-> np.ndarray: \"\"\" Convert a slimmed grid of 2D (y,x)", "2D grid with dimensions (total_unmasked_pixels). \"\"\" grid_1d_slim_y = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:,", "this origin before computing their 1D grid pixel coordinate values.", "slimmed pixel index 0. The fifth pixel on the top", "border pixels. Parameters ---------- grid : Grid2D The grid (uniform", "grid_relocated @numba_util.jit() def furthest_grid_2d_slim_index_from( grid_2d_slim: np.ndarray, slim_indexes: np.ndarray, coordinate: Tuple[float,", "scaled coordinate grid is defined by the class attribute origin,", "border if they are outside the border, where the border", "projected grid that is returned. If 0, the border based", "whose native index is [0,0], corresponds to slimmed pixel index", "distance_to_negative_y, ] ) if (scaled_distance == distance_to_positive_y) or ( scaled_distance", "between the centre and the edge of the region using", "= grid[:, :] border_origin = np.zeros(2) border_origin[0] = np.mean(border_grid[:, 0])", "\"\"\" distance_to_positive_x = extent[1] - centre[1] distance_to_positive_y = extent[3] -", "grid array has dimensions (total_unmasked_pixels*sub_size**2, 2). Examples -------- mask =", "to a native grid of 2D (y,x) pixel values. Pixel", "x dimension is used). 3) Determine the number of pixels", "of the extent in along the positive x-axis. \"\"\" distance_to_positive_x", "map the values of all unmasked pixels to a slimmed", "outwards from. pixel_scales The (y,x) scaled units to pixel units", "(y,x) coordinates. \"\"\" grid_relocated = np.zeros(grid.shape) grid_relocated[:, :] = grid[:,", "in functions which require that a 2D grid structure is", "part of the same mask array pixel are indexed next", "square uniform grid is overlaid. upscale_factor The upscaled resolution at", "highest (most positive) y scaled coordinate and lowest (most negative)", "grid_scaled_2d_slim_radii[slim_index, 1] = radii radii += pixel_scale / sub_size return", "(y,x) pixel indexes with dimensions (y_pixels, x_pixels, 2). Examples --------", "pixel_scales=pixel_scales, origin=origin ) for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_scaled_2d_slim[slim_index, 0] =", "grid array has dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- grid_2d =", "x in range(grid_scaled_2d.shape[1]): grid_pixels_2d[y, x, 0] = int( (-grid_scaled_2d[y, x,", "native 2D grid and mask of shape [total_y_pixels, total_x_pixels, 2],", "0] return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x,", "0] = -( y_scaled - y_sub_half + y1 * y_sub_step", "origin is at the top left corner of the native", "units conversion factor of the original 2D array. origin :", "/ upscale_factor x_upscale_half = pixel_scales[1] / 2 x_upscale_step = pixel_scales[1]", "np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], origin: Tuple[float,", "(grid[pixel_index, :] - border_origin[:]) + border_origin[:] ) return grid_relocated @numba_util.jit()", "scaled coordinate on the gird. The scaled coordinate grid is", "grid_slim[slim_index, 1] for y in range(upscale_factor): for x in range(upscale_factor):", "- centres_scaled[0] - 0.5) * pixel_scales[0] ) grid_scaled_2d_slim[slim_index, 1] =", "def grid_2d_slim_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float, Tuple[float, float]], sub_size: int,", "radii += pixel_scale / sub_size return grid_scaled_2d_slim_radii @numba_util.jit() def grid_pixels_2d_slim_from(", "centre[0] distance_to_negative_x = centre[1] - extent[0] distance_to_negative_y = centre[0] -", "uniform grid that laid over the irregular grid of (y,x)", "x_upscale_half = pixel_scales[1] / 2 x_upscale_step = pixel_scales[1] / upscale_factor", "its 2D mask with shape (total_y_pixels, total_x_pixels) is divided into", "the scaled coordinates were computed on. pixel_scales The (y,x) scaled", "on. pixel_scales The (y,x) scaled units to pixel units conversion", "grid_2d_slim_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float, Tuple[float, float]], sub_size: int, origin:", "index of the second dimension, x coordinates in the 1", "grid the radii grid is computed using, with format [xmin,", "based on the 2D grid is used (due to numba", "returned as integers such that they are the pixel from", "np.add( np.square(np.subtract(border_grid[:, 0], border_origin[0])), np.square(np.subtract(border_grid[:, 1], border_origin[1])), ) ) border_min_radii", "grid_pixel_indexes_2d_slim = np.zeros(grid_pixels_2d_slim.shape[0]) for slim_index in range(grid_pixels_2d_slim.shape[0]): grid_pixel_indexes_2d_slim[slim_index] = int(", "0 of the 1D grid. - pixel [0,1] of the", "of the 2D grid will correspond to index 4 of", "of 2D (y,x) scaled values. The input and output grids", "= points[:, 0] return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) -", "0])) / 2.0 centre_x = (np.max(grid_2d_slim[:, 1]) + np.min(grid_2d_slim[:, 1]))", "is defined by the class attribute origin, and coordinates are", "= grid_2d_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\" grid_2d_slim =", "values iterate from the centre in increasing steps of the", "dimensions (total_unmasked_pixels*sub_size**2, 2). Examples -------- mask = np.array([[True, False, True],", "structure so that it can be used in functions which", "\"\"\" For a slimmed 2D grid of shape [total_unmasked_pixels, 2],", "every coordinate, find its nearest pixel in the border. 4:", "radial distance. 5: If its radial distance is larger, use", "map directly to the pixel they are contained within. The", "integers such that they are the pixel from the top-left", "np.ndarray, mask_2d: np.ndarray, sub_size: int ) -> np.ndarray: \"\"\" For", "from the origin to its paired border pixel's radial distance.", "sub-grid is shifted around. Returns ------- ndarray A slimmed sub", "every sub-pixel defined by this 2D mask array. The sub-grid", "the two chosen above. 4) Create a (y,x) grid of", "Given the region defined by the extent [xmin, xmax, ymin,", "larger, use the ratio of radial distances to move the", "on an array of shape (total_unmasked_pixels*sub_size**2, 2). y coordinates are", "sub-grid. Parameters ---------- grid_slim The slimmed grid of (y,x) coordinates", "2d (y,x) scaled coordinates to a slimmed grid of 2d", "has index 1, its next sub-pixel has index 2, and", "points[:, 0] return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y,", "A slimmed grid of 2d scaled coordinates with dimensions (total_pixels,", "Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], origin: Tuple[float, float] =", "0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\" grid_2d_slim = grid_2d_slim_via_mask_from( mask_2d=mask_2d, pixel_scales=pixel_scales,", "so that it can be used in functions which require", "grid_2d_slim_from( grid_2d_native: np.ndarray, mask: np.ndarray, sub_size: int ) -> np.ndarray:", "native index is [0,1], has slimmed pixel index 10 if", "a 2D region of coordinates defined by an extent [xmin,", "this function finds the longest radial path to the edge", "indexes. shape_native The (y,x) shape of the original 2D array", "* pixel_scales[0] ) grid_scaled_2d_slim[slim_index, 1] = ( grid_pixels_2d_slim[slim_index, 1] -", "of the pixel-scale. 5) Rotate these radial coordinates by the", "of (y,x) scaled coordinates at the centre of every pixel", ") grid_pixels_2d_slim[slim_index, 1] = int( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1]) +", "grid_2d_native_x = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 1], mask_2d=mask_2d, sub_size=sub_size ) return np.stack((grid_2d_native_y,", "1D grid of values mapped from the 2D grid with", "dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- grid_2d = grid_2d_via_shape_native_from(shape_native=(3, 3), pixel_scales=(1.0,", "1D sample the 2D grid outwards from its centre. This", ": (float, flloat) The (y,x) origin of the 2D array,", "grid_pixels_2d_slim = np.zeros((grid_scaled_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin", "The scaled coordinate grid is defined by the class attribute", "------- ndarray A slimmed grid of 2D (y,x) pixel indexes", "pixel coordinate values. Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed grid", "is overlaid. upscale_factor The upscaled resolution at which the new", "+ 0.5 ) grid_pixels_2d[y, x, 1] = int( (grid_scaled_2d[y, x,", "grid pixel indexes. Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed grid", "[total_y_pixels, total_x_pixels, 2] corresponding to the (y,x) values of the", "@numba_util.jit() def grid_pixels_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float,", "[3.0, 3.0], [4.0, 4.0]]) grid_pixel_centres_2d = grid_pixel_centres_2d_from(grid_scaled_2d=grid_scaled_2d, shape=(2,2), pixel_scales=(0.5, 0.5),", "return grid_2d_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) @numba_util.jit() def", "will correspond to index 1 of the 1D grid. -", "can be used on uniform or irregular grids, however for", "(y,x) pixel indexes with dimensions (total_pixels, 2). Examples -------- grid_scaled_2d_slim", "compute_polygon_area(points): x = points[:, 1] y = points[:, 0] return", "+ (x_upscale_step / 2.0) ) upscale_index += 1 return grid_2d_slim_upscaled", "pixel indexes with dimensions (total_pixels, 2). Examples -------- grid_scaled_2d_slim =", "1 return grid_slim def grid_2d_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float, Tuple[float,", "an extent [xmin, xmax, ymin, ymax] and with a (y,x)", "| | ------------------- Using the centre x above, this function", "all points are at the centre's y value = 0.0", "to slimmed pixel indexes. shape_native The (y,x) shape of the", "grid coordinate, analogous to a sub-grid. Parameters ---------- grid_slim The", "1]) return np.asarray(y_inside, x_inside) def compute_polygon_area(points): x = points[:, 1]", "\"\"\" total_sub_pixels = mask_2d_util.total_sub_pixels_2d_from(mask_2d, sub_size) grid_slim = np.zeros(shape=(total_sub_pixels, 2)) centres_scaled", "grid pixel indexes. The input and output grids are both", "( x_grid - x_upscale_half + x * x_upscale_step + (x_upscale_step", "Optional from autoarray.structures.arrays.two_d import array_2d_util from autoarray.geometry import geometry_util from", "pixel_scales[1] return grid_scaled_2d_slim @numba_util.jit() def grid_pixel_centres_2d_from( grid_scaled_2d: np.ndarray, shape_native: Tuple[int,", "(total_pixels, 2). Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed grid of", "np.ndarray, centre: Tuple[float, float], pixel_scales: Union[float, Tuple[float, float]], sub_size: int,", "For a sub-grid, every unmasked pixel of its 2D mask", "= slim_index return furthest_grid_2d_slim_index def grid_2d_slim_from( grid_2d_native: np.ndarray, mask: np.ndarray,", "native grid of 2D (y,x) scaled coordinates to a native", "np.ndarray, slim_indexes: np.ndarray, coordinate: Tuple[float, float] ) -> int: distance_to_centre", "[0,0] of the 2D grid will correspond to index 0", "grid_scaled_2d_slim[slim_index, 0] = ( -(grid_pixels_2d_slim[slim_index, 0] - centres_scaled[0] - 0.5)", "return np.asarray(y_inside, x_inside) def compute_polygon_area(points): x = points[:, 1] y", "= np.zeros(2) border_origin[0] = np.mean(border_grid[:, 0]) border_origin[1] = np.mean(border_grid[:, 1])", "x coordinates in the 1 index. Masked pixels are given", "is shifted Returns ------- ndarray A native grid of 2D", "is returned in its native dimensions with shape (total_y_pixels*sub_size, total_x_pixels*sub_size).", "mask array is divided into. shape_slim Manually choose the shape", "The (y,x) scaled units to pixel units conversion factor of", "total_x_pixels*sub_size). This routine computes the (y,x) scaled coordinates at the", "np.ndarray, mask: np.ndarray, sub_size: int ) -> np.ndarray: \"\"\" For", "def grid_2d_slim_upscaled_from( grid_slim: np.ndarray, upscale_factor: int, pixel_scales: Union[float, Tuple[float, float]],", "which are mapped to the slimmed grid. mask_2d A 2D", "the 1D array maps to the pixels [1,1,:] of the", "it can be used in functions which require that a", "if they are outside the border, where the border is", "grid_2d_slim The (y,x) values of the slimmed 2D grid which", "x = grid_2d_slim[slim_index, 1] distance_to_centre_new = (x - coordinate[1]) **", "scale of the uniform grid that laid over the irregular", "and so forth. Parameters ---------- mask_2d A 2D array of", "grid from a 1D grid. Parameters ---------- grid_2d_slim The 1D", "slim_to_native[4] = [1,1], the fifth value of the 1D array", "\"\"\" grid_pixels_2d_slim = np.zeros((grid_scaled_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales,", "native 2D mapped from the slimmed grid. \"\"\" grid_2d_native_y =", "the border is defined as all pixels at the edge", "of a grid to its border if they are outside", "goes right-wards and downwards, such that for an grid of", "shifted to this origin after computing their values from the", "centre: Tuple[float, float], grid_2d: np.ndarray ): y_inside = [] x_inside", "1], mask_2d=mask_2d, sub_size=sub_size ) return np.stack((grid_2d_native_y, grid_2d_native_x), axis=-1) @numba_util.jit() def", "slimmed pixel indexes with dimensions (total_pixels,). Examples -------- grid_scaled_2d_slim =", "+ centres_scaled[0] + 0.5 ) grid_pixels_2d_slim[slim_index, 1] = int( (grid_scaled_2d_slim[slim_index,", "the native 2D mapped from the slimmed grid. \"\"\" grid_2d_native_y", "The sub-grid is returned in its native dimensions with shape", "float, centre: Tuple[float, float], grid_2d: np.ndarray ): y_inside = []", "distance_to_negative_x, distance_to_negative_y, ] ) if (scaled_distance == distance_to_positive_y) or (", "(y,x) values of the slimmed 2D grid which are mapped", "they are contained within. The input and output grids are", "returned as integers such that they map directly to the", "rights and then downwards. The input and output grids are", "(grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1]) + centres_scaled[1] + 0.5 ) return", "(y,x) coordinates in pixel values which is converted to scaled", "`grid_radii` represents a radial set of points that in 1D", "to the input scaled coordinate. The input and output grids", "in range(grid.shape[0]): if grid_radii[pixel_index] > border_min_radii: closest_pixel_index = np.argmin( np.square(grid[pixel_index,", "of the region using the longest path between the two", "2], map the slimmed grid's coordinates back to the native", "index 0. The fifth pixel on the top row, whose", "gird. The scaled grid is defined by an origin and", "with shape (total_y_pixels*sub_size, total_x_pixels*sub_size). y coordinates are stored in the", "[4.0, 4.0]]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0))", "are returned as integers such that they map directly to", "computed for. pixel_scales The (y,x) scaled units to pixel units", "Parameters ---------- mask_2d A 2D array of bools, where `False`", "(y,x) pixel values. Pixel coordinates are returned as integers such", "of every grid coordinate from the origin. 3: For every", "-------- grid_scaled_2d = np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0,", "1: Use the mean value of the grid's y and", "pixel_scale = pixel_scales[1] if shape_slim == 0: shape_slim = sub_size", "if move_factor < 1.0: grid_relocated[pixel_index, :] = ( move_factor *", "points sampling the longest distance from the centre to the", "the second dimension, x coordinates in the 1 index. Masked", "values. Pixel coordinates are returned as floats such that they", "values. The input and output grids are both slimmed and", "scaled coordinates. shape_native The (y,x) shape of the original 2D", "float] = (0.0, 0.0), ) -> np.ndarray: \"\"\" For a", "---------- grid : Grid2D The grid (uniform or irregular) whose", "will correspond to index 0 of the 1D grid. -", "2D mask array. The sub-grid is returned in its native", "* y_sub_step + (y_sub_step / 2.0) ) grid_slim[sub_index, 1] =", "values. Pixel coordinates are returned as integers such that they", "grid will correspond to index 0 of the 1D grid.", "functions operates as follows: 1) Given the region defined by", "np.ndarray: \"\"\" Convert a slimmed grid of 2D (y,x) pixel", "within. The input and output grids are both slimmed and", "the mapping. sub_size The size (sub_size x sub_size) of each", "computes the (y,x) scaled coordinates a the centre of every", "numba None cannot be used as a default value). Returns", "a (y,x) grid of radial points where all points are", "to extent edge | | ------------------- Using the centre x", "the irregular grid of (y,x) coordinates. \"\"\" grid_2d_slim_upscaled = np.zeros(", "grid_relocated = np.zeros(grid.shape) grid_relocated[:, :] = grid[:, :] border_origin =", "the 2D mask array. The sub grid array has dimensions", "path to the edge of the extent window. The returned", "slim_index return furthest_grid_2d_slim_index def grid_2d_slim_from( grid_2d_native: np.ndarray, mask: np.ndarray, sub_size:", "pixel indexes with dimensions (y_pixels, x_pixels, 2). Examples -------- grid_scaled_2d", "return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_indexes_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int],", "origin=origin, ) def grid_2d_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float,", "shape of the 2D array the sub-grid of coordinates is", "longest radial path to the edge of the extent window.", "array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 1], mask_2d=mask_2d, sub_size=sub_size ) return np.stack((grid_2d_native_y, grid_2d_native_x), axis=-1)", "total_x_pixels*sub_size). Examples -------- grid_2d = grid_2d_via_shape_native_from(shape_native=(3, 3), pixel_scales=(1.0, 1.0), sub_size=2,", "1] ) return grid_pixel_indexes_2d_slim @numba_util.jit() def grid_scaled_2d_slim_from( grid_pixels_2d_slim: np.ndarray, shape_native:", "---------- extent The extent of the grid the radii grid", "Examples -------- grid_pixels_2d_slim = np.array([[0,0], [0,1], [1,0], [1,1]) grid_pixels_2d_slim =", "is used (due to numba None cannot be used as", "coordinates. \"\"\" grid_relocated = np.zeros(grid.shape) grid_relocated[:, :] = grid[:, :]", "native grid of (y,x) values which are mapped to the", "distance_to_positive_y = extent[3] - centre[0] distance_to_negative_x = centre[1] - extent[0]", "3.0], [4.0, 4.0]]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0,", "converted to pixel indexes. shape_native The (y,x) shape of the", "if shape_slim == 0: shape_slim = sub_size * int((scaled_distance /", "pixel indexes with dimensions (total_pixels,). Examples -------- grid_scaled_2d_slim = np.array([[1.0,", "pixel indexes of the grid's native unmasked pixels, for example:", "default value). Returns ------- ndarray A radial set of points", "is converted to scaled coordinates. shape_native The (y,x) shape of", "shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim = grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim=grid_scaled_2d_slim,", "[2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixel_centres_2d = grid_pixel_centres_2d_from(grid_scaled_2d=grid_scaled_2d, shape=(2,2),", "of the 1D grid. - pixel [1,0] of the 2D", "(y,x) shape of the 2D array the sub-grid of coordinates", "grid is shifted Returns ------- ndarray A slimmed grid of", "scaled coordinates to a slimmed grid of pixel indexes. Pixel", "added at an upscaled resolution to each grid coordinate, analogous", "x_inside) def compute_polygon_area(points): x = points[:, 1] y = points[:,", "[total_y_pixels, total_x_pixels, 2], map the values of all unmasked pixels", "coordinate. The input and output grids are both slimmed and", "[0,0,:] of the native 2D grid. - If slim_to_native[1] =", "origin=origin, ) grid_pixel_indexes_2d_slim = np.zeros(grid_pixels_2d_slim.shape[0]) for slim_index in range(grid_pixels_2d_slim.shape[0]): grid_pixel_indexes_2d_slim[slim_index]", "scaled grid is shifted Returns ------- ndarray A native grid", "on the gird. The scaled grid is defined by an", "before computing their 1D grid pixel indexes. Parameters ---------- grid_scaled_2d_slim:", "a grid from a 1D grid. Parameters ---------- grid_2d_slim The", "2D mask array. The sub grid array has dimensions (total_unmasked_pixels*sub_size**2,", "of the 1D array maps to the pixels [1,1,:] of", "in the first pixel has index 1, its next sub-pixel", "import numpy as np from typing import Tuple, Union, Optional", "its next sub-pixel has index 2, and so forth. Parameters", "which the scaled grid is shifted to. Returns ------- ndarray", "which the scaled grid is shifted. Returns ------- ndarray A", "gird. The scaled coordinate origin is defined by the class", "grid where masked values are set to zero. This uses", "1) Given the region defined by the extent [xmin, xmax,", "for pixel_index in range(grid.shape[0]): if grid_radii[pixel_index] > border_min_radii: closest_pixel_index =", "= [1,1], the fifth value of the 1D array maps", "x coordinates to determine the origin of the grid. 2:", "grid and mask of shape [total_y_pixels, total_x_pixels, 2], map the", "np.ndarray ): y_inside = [] x_inside = [] for i", "pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) def grid_2d_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales:", "grid_2d_slim_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], sub_size: int,", "gives the 2D pixel indexes of the grid's native unmasked", "and output grids are both slimmed and have shapes (total_pixels,", "@numba_util.jit() def grid_scaled_2d_slim_from( grid_pixels_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float,", "within. The input and output grids are both native resolution", "0 index of the second dimension, x coordinates in the", "performed as follows: 1: Use the mean value of the", "sub_size=sub_size ) def grid_2d_slim_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float,", "The pixel coordinate origin is at the top left corner", "units which are converted to pixel value coordinates. shape_native The", "of 2D (y,x) coordinates in scaled units which are converted", "projected radial grid of points from a 2D region of", ":, 0], mask_2d=mask, sub_size=sub_size ) grid_1d_slim_x = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :,", "the 1D grid. - pixel [0,1] of the 2D grid", "\"\"\" return grid_2d_slim_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) def", "np.zeros( shape=(grid_slim.shape[0] * upscale_factor ** 2, 2) ) upscale_index =", "has dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- mask = np.array([[True, False,", "grid_2d_slim_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) def grid_2d_via_shape_native_from( shape_native:", "centre of every pixel unmasked pixel on the 2D mask", "the calculated sub-grid. pixel_scales The (y,x) scaled units to pixel", "------- ndarray A radial set of points sampling the longest", "0], border_origin[0])), np.square(np.subtract(border_grid[:, 1], border_origin[1])), ) ) border_min_radii = np.min(border_grid_radii)", "unmasked: - pixel [0,0] of the 2D grid will correspond", "x_pixels, 2). Examples -------- grid_scaled_2d = np.array([[1.0, 1.0], [2.0, 2.0],", "distance_to_centre_new = (x - coordinate[1]) ** 2 + (y -", "4.0]]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\"", "upscale_factor x_upscale_half = pixel_scales[1] / 2 x_upscale_step = pixel_scales[1] /", "1D grid. Parameters ---------- grid_2d_slim The 1D grid of values", "grid_2d_slim The 1D grid of values which are mapped to", "native index is [0,5], corresponds to slimmed pixel index 4.", "is converted to slimmed pixel indexes. shape_native The (y,x) shape", "array. The sub grid array has dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples", "slimmed pixel indexes. shape_native The (y,x) shape of the original", "border_grid[:, 1]) ) move_factor = ( border_grid_radii[closest_pixel_index] / grid_radii[pixel_index] )", "however for irregular grids the border of the 'image-plane' mask", "irregular grids the border of the 'image-plane' mask is used", "native 2D grid. - If slim_to_native[4] = [1,1], the fifth", "of shape (total_unmasked_pixels*sub_size**2, 2). y coordinates are stored in the", "dimensions (y_pixels, x_pixels, 2). Examples -------- grid_scaled_2d = np.array([[1.0, 1.0],", "Returns ------- ndarray A slimmed sub grid of (y,x) scaled", "@numba_util.jit() def relocated_grid_via_jit_from(grid, border_grid): \"\"\" Relocate the coordinates of a", "range(sub_size): for x1 in range(sub_size): grid_slim[sub_index, 0] = -( y_scaled", "scaled grid is shifted. Returns ------- ndarray A grid of", "(uniform or irregular) whose pixels are to be relocated to", "1D array 'slim_to_native' where each index gives the 2D pixel", "coordinates in pixel values which is converted to scaled coordinates.", "1] = int( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1]) + centres_scaled[1] +", "the 1D array maps to the pixels [0,1,:] of the", "first sub-pixel corresponds to index [0,0]. Sub-pixels that are part", "Tuple[float, float] = (0.0, 0.0), ) -> np.ndarray: \"\"\" Convert", "origin=origin ) for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = int(", "coordinates are returned as integers such that they map directly", "@numba_util.jit() def grid_pixel_indexes_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float,", "pixels are to be relocated to the border edge if", "value of the 1D array maps to the pixels [1,1,:]", "A NumPy array of shape [total_y_pixels, total_x_pixels, 2] corresponding to", "( grid_2d[i, 1] - centre[1] ) ** 2 > radius", "The pixel scale of the uniform grid that laid over", "into. origin : (float, flloat) The (y,x) origin of the", "The 1D grid of values which are mapped to a", "grid_2d_native_y = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 0], mask_2d=mask_2d, sub_size=sub_size ) grid_2d_native_x =", "the 2D mask array is divided into. origin The (y,x)", "array maps to the pixels [0,1,:] of the native 2D", "0] * shape_native[1] + grid_pixels_2d_slim[slim_index, 1] ) return grid_pixel_indexes_2d_slim @numba_util.jit()", "in range(len(grid_2d[:, 0])): if (grid_2d[i, 0] - centre[0]) ** 2", "for y1 in range(sub_size): for x1 in range(sub_size): grid_slim[sub_index, 0]", "coordinates is computed for. pixel_scales The (y,x) scaled units to", "pixel_index in range(grid.shape[0]): if grid_radii[pixel_index] > border_min_radii: closest_pixel_index = np.argmin(", "border_min_radii = np.min(border_grid_radii) grid_radii = np.sqrt( np.add( np.square(np.subtract(grid[:, 0], border_origin[0])),", "sub-pixel has index 2, and so forth. Parameters ---------- shape_native", "mapped to the slimmed grid. mask_2d A 2D array of", "to this origin after computing their values from the 1D", "grid of (y,x) coordinates over which a square uniform grid", "values are unmasked and therefore included as part of the", "---------- grid_2d_native : ndarray The native grid of (y,x) values", "scaled coordinates at the centre of every pixel unmasked pixel", "2 if distance_to_centre_new >= distance_to_centre: distance_to_centre = distance_to_centre_new furthest_grid_2d_slim_index =", "grid_pixels_2d_slim[slim_index, 1] ) return grid_pixel_indexes_2d_slim @numba_util.jit() def grid_scaled_2d_slim_from( grid_pixels_2d_slim: np.ndarray,", "(y_upscale_step / 2.0) ) grid_2d_slim_upscaled[upscale_index, 1] = ( x_grid -", "the 2D pixel indexes of the grid's native unmasked pixels,", "calculated sub-grid. pixel_scales The (y,x) scaled units to pixel units", "of border (y,x) coordinates. \"\"\" grid_relocated = np.zeros(grid.shape) grid_relocated[:, :]", "the radial coordinates as (y,x) values (where all y values", "the sub-grid is shifted around. Returns ------- ndarray A slimmed", "to a slimmed grid of shape [total_unmasked_pixels, 2]. The pixel", "grid_2d_slim = grid_2d_slim_via_mask_from( mask_2d=mask_2d, pixel_scales=pixel_scales, sub_size=sub_size, origin=origin ) return grid_2d_native_from(", ">= distance_to_centre: distance_to_centre = distance_to_centre_new furthest_grid_2d_slim_index = slim_index return furthest_grid_2d_slim_index", "with dimensions (total_pixels, 2). Examples -------- grid_scaled_2d_slim = np.array([[1.0, 1.0],", "the centre's y value = 0.0 and the x values", "defined by an extent [xmin, xmax, ymin, ymax] and with", "0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\" total_sub_pixels = mask_2d_util.total_sub_pixels_2d_from(mask_2d, sub_size) grid_slim", "centre in increasing steps of the pixel-scale. 5) Rotate these", "| x = centre | | <-> = longest radial", "= sub_size * int((scaled_distance / pixel_scale)) + 1 grid_scaled_2d_slim_radii =", "the grid. \"\"\" centre_y = (np.max(grid_2d_slim[:, 0]) + np.min(grid_2d_slim[:, 0]))", "of every pixel unmasked pixel on the 2D mask array.", "grid_scaled_2d.shape[1], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for", "0.0)) \"\"\" grid_pixels_2d = np.zeros((grid_scaled_2d.shape[0], grid_scaled_2d.shape[1], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from(", "correspond to index 4 of the 1D grid. Parameters ----------", "centre_x @numba_util.jit() def grid_2d_slim_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float, Tuple[float, float]],", "each unmasked pixels sub-array. Returns ------- ndarray A NumPy array", ": Grid2D The grid of border (y,x) coordinates. \"\"\" grid_relocated", "0.0)) \"\"\" grid_2d_slim = grid_2d_slim_via_mask_from( mask_2d=mask_2d, pixel_scales=pixel_scales, sub_size=sub_size, origin=origin )", "the 2D array the sub-grid of coordinates is computed for.", "using the longest path between the two chosen above. 4)", "uniform grid of shape (total_y_pixels*sub_size, total_x_pixels*sub_size). This routine computes the", "slimmed grid of 2D (y,x) pixel-value coordinates with dimensions (total_pixels,", "pixel_scale / sub_size return grid_scaled_2d_slim_radii @numba_util.jit() def grid_pixels_2d_slim_from( grid_scaled_2d_slim: np.ndarray,", "the class attribute origin, and coordinates are shifted to this", "\"\"\" Convert a slimmed grid of 2D (y,x) pixel coordinates", "0.0)) \"\"\" total_sub_pixels = mask_2d_util.total_sub_pixels_2d_from(mask_2d, sub_size) grid_slim = np.zeros(shape=(total_sub_pixels, 2))", "a slimmed grid of shape [total_unmasked_pixels, 2]. The pixel coordinate", "1D grid. - pixel [1,0] of the 2D grid will", "True]]) grid_2d = grid_2d_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\"", "furthest_grid_2d_slim_index_from( grid_2d_slim: np.ndarray, slim_indexes: np.ndarray, coordinate: Tuple[float, float] ) ->", "for x in range(grid_scaled_2d.shape[1]): grid_pixels_2d[y, x, 0] = int( (-grid_scaled_2d[y,", "import geometry_util from autoarray import numba_util from autoarray.mask import mask_2d_util", "original 2D array. origin : (float, flloat) The (y,x) origin", "[] x_inside = [] for i in range(len(grid_2d[:, 0])): if", "centre[0] radii = centre[1] for slim_index in range(shape_slim): grid_scaled_2d_slim_radii[slim_index, 1]", "its centre. This grid stores the radial coordinates as (y,x)", "- centre[1] distance_to_positive_y = extent[3] - centre[0] distance_to_negative_x = centre[1]", "return an upscaled slimmed 2D grid where (y,x) coordinates are", "radial grid of points from a 2D region of coordinates", "the x values iterate from the centre in increasing steps", "number of pixels between the centre and the edge of", "the edge of the grid's mask (see *mask._border_1d_indexes*). This is", "of the 4 paths from the (y,x) centre to the", "coordinates to a slimmed grid of 2d (y,x) pixel coordinate", "------- (float, float) The (y,x) central coordinates of the grid.", "1] = ( grid_pixels_2d_slim[slim_index, 1] - centres_scaled[1] - 0.5 )", "This grid stores the radial coordinates as (y,x) values (where", "of the native grid and goes right-wards and downwards, such", "in the 1 index. Masked pixels are given values (0.0,", "2D grid. Parameters ---------- grid_2d_slim The (y,x) values of the", "from the (y,x) centre to the edge of the region", "The input and output grids are both slimmed and therefore", "sub_size=sub_size, origin=origin, ) def grid_2d_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales: Union[float,", "follows: 1: Use the mean value of the grid's y", "the 4 paths from the (y,x) centre to the edge", "- - ->x | x = centre | | <->", "** 2 if distance_to_centre_new >= distance_to_centre: distance_to_centre = distance_to_centre_new furthest_grid_2d_slim_index", "scaled coordinate origin is defined by the class attribute origin,", "---------- grid_slim The slimmed grid of (y,x) coordinates over which", "corner relative to the input scaled coordinate. The input and", "- centre[0] distance_to_negative_x = centre[1] - extent[0] distance_to_negative_y = centre[0]", "/ grid_radii[pixel_index] ) if move_factor < 1.0: grid_relocated[pixel_index, :] =", "has 10 pixels. The scaled coordinate grid is defined by", "A 1D grid of values mapped from the 2D grid", "Masked coordinates are therefore removed and not included in the", "The native grid of (y,x) values which are mapped to", ") for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = ( (-grid_scaled_2d_slim[slim_index,", "in slim_indexes: y = grid_2d_slim[slim_index, 0] x = grid_2d_slim[slim_index, 1]", "pixel_scales[0] / (sub_size) x_sub_half = pixel_scales[1] / 2 x_sub_step =", "axis=-1) def grid_2d_native_from( grid_2d_slim: np.ndarray, mask_2d: np.ndarray, sub_size: int )", "grid_pixels_2d_slim[slim_index, 1] - centres_scaled[1] - 0.5 ) * pixel_scales[1] return", "total_x_pixels*sub_size). This routine computes the (y,x) scaled coordinates a the", "np.stack((grid_2d_native_y, grid_2d_native_x), axis=-1) @numba_util.jit() def grid_2d_slim_upscaled_from( grid_slim: np.ndarray, upscale_factor: int,", "of the region (e.g. following the positive / negative y", "the centre x above, this function finds the longest radial", "grid of 2d (y,x) pixel coordinate values. Pixel coordinates are", "coordinates in the 1 index. Masked coordinates are therefore removed", "0.0 and the x values iterate from the centre in", "** 2 > radius ** 2: y_inside.append(grid_2d[i, 0]) x_inside.append(grid_2d[i, 1])", "- border_grid[:, 0]) + np.square(grid[pixel_index, 1] - border_grid[:, 1]) )", "are shifted to this origin before computing their 1D grid", "of its 2D mask with shape (total_y_pixels, total_x_pixels) is divided", "grid_1d_slim_x), axis=-1) def grid_2d_native_from( grid_2d_slim: np.ndarray, mask_2d: np.ndarray, sub_size: int", "such that they include the decimal offset from each pixel's", "is outside the border, by comparing its radial distance from", "def grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float,", "2D (y,x) pixel coordinates to a slimmed grid of 2D", "in range(upscale_factor): for x in range(upscale_factor): grid_2d_slim_upscaled[upscale_index, 0] = (", "example: The pixel at the top-left, whose native index is", "np.zeros((grid_scaled_2d.shape[0], grid_scaled_2d.shape[1], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin )", "an upscaled resolution to each grid coordinate, analogous to a", "grid_radii = np.sqrt( np.add( np.square(np.subtract(grid[:, 0], border_origin[0])), np.square(np.subtract(grid[:, 1], border_origin[1])),", "dimension, x coordinates in the 1 index. Masked pixels are", "dimension, x coordinates in the 1 index. Masked coordinates are", "in range(grid_slim.shape[0]): y_grid = grid_slim[slim_index, 0] x_grid = grid_slim[slim_index, 1]", "unmasked and therefore included as part of the calculated sub-grid.", "0.5 ) return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native:", "grid_pixels_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], origin:", "mask array is divided into. origin The (y,x) origin of", "coordinates of the grid. \"\"\" centre_y = (np.max(grid_2d_slim[:, 0]) +", "used (due to numba None cannot be used as a", "all y values are the same) as opposed to a", "return grid_pixel_indexes_2d_slim @numba_util.jit() def grid_scaled_2d_slim_from( grid_pixels_2d_slim: np.ndarray, shape_native: Tuple[int, int],", "sub_size) of each unmasked pixels sub-array. Returns ------- ndarray A", "grid_slim The slimmed grid of (y,x) coordinates over which a", "coordinates are stored in the 0 index of the second", "border_grid): \"\"\" Relocate the coordinates of a grid to its", "divided into a finer uniform grid of shape (total_y_pixels*sub_size, total_x_pixels*sub_size).", "centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for slim_index in", "distance_to_negative_x = centre[1] - extent[0] distance_to_negative_y = centre[0] - extent[2]", "x_upscale_step = pixel_scales[1] / upscale_factor for slim_index in range(grid_slim.shape[0]): y_grid", "radial set of points that in 1D sample the 2D", "grid_scaled_2d_slim_radii = np.zeros((shape_slim, 2)) grid_scaled_2d_slim_radii[:, 0] += centre[0] radii =", "format [xmin, xmax, ymin, ymax] centre : (float, flloat) The", "left corner of the grid, such that the pixel [0,0]", "The slimmed grid of (y,x) coordinates over which a square", "and coordinates are shifted to this origin after computing their", "as follows: 1: Use the mean value of the grid's", "The (y,x) central coordinates of the grid. \"\"\" centre_y =", "have shapes (total_pixels, 2) and (total_pixels,). For example: The pixel", "x_scaled = (x - centres_scaled[1]) * pixel_scales[1] for y1 in", "= int( (-grid_scaled_2d[y, x, 0] / pixel_scales[0]) + centres_scaled[0] +", "of the original 2D array the scaled coordinates were computed", "= np.zeros(grid.shape) grid_relocated[:, :] = grid[:, :] border_origin = np.zeros(2)", "+ (y - coordinate[0]) ** 2 if distance_to_centre_new >= distance_to_centre:", "every grid coordinate from the origin. 3: For every coordinate,", "from autoarray.mask import mask_2d_util @numba_util.jit() def grid_2d_centre_from(grid_2d_slim: np.ndarray) -> Tuple[float,", "0] = int( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0]) + centres_scaled[0] +", "the 2D mask array is divided into. origin : (float,", ") def grid_2d_slim_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]],", "fifth value of the 1D array maps to the pixels", "pixel_scales=pixel_scales, origin=origin ) sub_index = 0 y_sub_half = pixel_scales[0] /", "of the grid's mask (see *mask._border_1d_indexes*). This is performed as", "np.ndarray: \"\"\" For a native 2D grid and mask of", "index gives the 2D pixel indexes of the grid's native", "border_origin[1] = np.mean(border_grid[:, 1]) border_grid_radii = np.sqrt( np.add( np.square(np.subtract(border_grid[:, 0],", "float]], sub_size: int, shape_slim: Optional[int] = 0, ) -> np.ndarray:", "pixel_scales[1] / upscale_factor for slim_index in range(grid_slim.shape[0]): y_grid = grid_slim[slim_index,", "pixel-value coordinates with dimensions (total_pixels, 2). Examples -------- grid_scaled_2d_slim =", "coordinates. \"\"\" grid_2d_slim_upscaled = np.zeros( shape=(grid_slim.shape[0] * upscale_factor ** 2,", "<-> = longest radial path from centre to extent edge", "values (where all y values are the same) as opposed", "the scaled grid is shifted to. Returns ------- ndarray A", "grid_slim = np.zeros(shape=(total_sub_pixels, 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=mask_2d.shape, pixel_scales=pixel_scales, origin=origin", "slimmed dimensions with shape (total_pixels**2*sub_size**2, 2). y coordinates are stored", "centre[0] - extent[2] scaled_distance = max( [ distance_to_positive_x, distance_to_positive_y, distance_to_negative_x,", "False, True], [False, False, False] [True, False, True]]) grid_slim =", "mask_2d=mask_2d, sub_size=sub_size ) def grid_2d_slim_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales: Union[float,", "the algorithm finds the longest 1D distance of the 4", "pixel of its 2D mask with shape (total_y_pixels, total_x_pixels) is", "using, with format [xmin, xmax, ymin, ymax] centre : (float,", "2D grid will correspond to index 1 of the 1D", "array is divided into. origin : (float, flloat) The (y,x)", "pixel_scales[0] / 2 y_sub_step = pixel_scales[0] / (sub_size) x_sub_half =", "> radius ** 2: y_inside.append(grid_2d[i, 0]) x_inside.append(grid_2d[i, 1]) return np.asarray(y_inside,", "for slim_index in range(grid_slim.shape[0]): y_grid = grid_slim[slim_index, 0] x_grid =", "is defined as all pixels at the edge of the", "= pixel_scales[1] / 2 x_sub_step = pixel_scales[1] / (sub_size) for", "pixels [0,0,:] of the native 2D grid. - If slim_to_native[1]", "`False` values are unmasked and therefore included as part of", "index 10 if a row has 10 pixels. The scaled", "2D mask array. sub_size The size of the sub-grid that", "chosen above. 4) Create a (y,x) grid of radial points", "be used as a default value). Returns ------- ndarray A", "values mean unmasked and are included in the mapping. sub_size", "slimmed 2D grid where (y,x) coordinates are added at an", "shape=(grid_slim.shape[0] * upscale_factor ** 2, 2) ) upscale_index = 0", "the edge of the region (e.g. following the positive /", "= ( x_grid - x_upscale_half + x * x_upscale_step +", "centre[1] distance_to_positive_y = extent[3] - centre[0] distance_to_negative_x = centre[1] -", "grid_pixels_2d_slim[slim_index, 0] = ( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0]) + centres_scaled[0]", "( scaled_distance == distance_to_negative_y ): pixel_scale = pixel_scales[0] else: pixel_scale", "array_2d_slim=grid_2d_slim[:, 1], mask_2d=mask_2d, sub_size=sub_size ) return np.stack((grid_2d_native_y, grid_2d_native_x), axis=-1) @numba_util.jit()", "its nearest pixel in the border. 4: Determine if it", "coordinates at the centre of every sub-pixel defined by this", "is slimmed and has dimensions (total_unmasked_pixels*sub_size**2, 2). Examples -------- mask", "if a row has 10 pixels. The scaled coordinate grid", "ymin, ymax] and with a (y,x) centre. This functions operates", "1D grid. - pixel [0,1] of the 2D grid will", "longest 1D distance of the 4 paths from the (y,x)", "/ 2 y_sub_step = pixel_scales[0] / (sub_size) x_sub_half = pixel_scales[1]", "Use the mean value of the grid's y and x", "and therefore included as part of the calculated sub-grid. pixel_scales", "= pixel_scales[1] / upscale_factor for slim_index in range(grid_slim.shape[0]): y_grid =", "sub_size: int, shape_slim: Optional[int] = 0, ) -> np.ndarray: \"\"\"", "x values iterate from the centre in increasing steps of", "centre of a grid from a 1D grid. Parameters ----------", "pixel from the top-left of the 2D grid going rights", "x sub_size) of each unmasked pixels sub-array. Returns ------- ndarray", "uniform grid is overlaid. upscale_factor The upscaled resolution at which", "If 0, the border based on the 2D grid is", "returned on an array of shape (total_unmasked_pixels*sub_size**2, 2). y coordinates", "divided into. origin : (float, flloat) The (y,x) origin of", "= grid_2d_slim[slim_index, 1] distance_to_centre_new = (x - coordinate[1]) ** 2", "along the positive x-axis. \"\"\" distance_to_positive_x = extent[1] - centre[1]", "typing import Tuple, Union, Optional from autoarray.structures.arrays.two_d import array_2d_util from", "int( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0]) + centres_scaled[0] + 0.5 )", "[total_unmasked_pixels, 2], that was computed by extracting the unmasked values", "where masked values are set to zero. This uses a", "the origin of the grid. 2: Compute the radial distance", "positive) y scaled coordinate and lowest (most negative) x scaled", "coordinate[0]) ** 2 if distance_to_centre_new >= distance_to_centre: distance_to_centre = distance_to_centre_new", "(sub_size x sub_size) of each unmasked pixels sub-array. Returns -------", "are mapped to a 2D array. Returns ------- (float, float)", "follows: 1) Given the region defined by the extent [xmin,", "(y,x) values (where all y values are the same) as", "of shape (total_pixels, 2). Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed", "has dimensions (total_unmasked_pixels*sub_size**2, 2). Examples -------- mask = np.array([[True, False,", "at the centre of every sub-pixel defined by this 2D", "mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) @numba_util.jit() def grid_scaled_2d_slim_radial_projected_from( extent:", "the second sub-pixel in the first pixel has index 1,", "`angle` clockwise. A schematric is shown below: ------------------- | |", "finds the longest 1D distance of the 4 paths from", "(y_pixels, x_pixels, 2). Examples -------- grid_scaled_2d = np.array([[1.0, 1.0], [2.0,", "in scaled units which is converted to pixel indexes. shape_native", "sub_size) grid_slim = np.zeros(shape=(total_sub_pixels, 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=mask_2d.shape, pixel_scales=pixel_scales,", "grid_scaled_2d_slim_from( grid_pixels_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]],", "1D grid pixel indexes. Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed", "algorithm finds the longest 1D distance of the 4 paths", "grid_2d_slim[slim_index, 1] distance_to_centre_new = (x - coordinate[1]) ** 2 +", "2] corresponding to the (y,x) values of the native 2D", "in its native dimensions with shape (total_y_pixels*sub_size, total_x_pixels*sub_size). y coordinates", "that in 1D sample the 2D grid outwards from its", "return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))", "( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1]) + centres_scaled[1] + 0.5 )", "of values which are mapped to a 2D array. Returns", "x scaled coordinate on the gird. The scaled coordinate grid", "converted to slimmed pixel indexes. shape_native The (y,x) shape of", "slimmed grid of 2D (y,x) pixel coordinates to a slimmed", "masked values are set to zero. This uses a 1D", ") -> np.ndarray: \"\"\" From an input slimmed 2D grid,", "= np.argmin( np.square(grid[pixel_index, 0] - border_grid[:, 0]) + np.square(grid[pixel_index, 1]", "mask = np.array([[True, False, True], [False, False, False] [True, False,", "grid of 2D (y,x) coordinates in scaled units which are", "np.ndarray: \"\"\" For a sub-grid, every unmasked pixel of its", "such that the second sub-pixel in the first pixel has", "grid of radial points where all points are at the", "native index is [0,0], corresponds to slimmed pixel index 0.", "`False` values mean unmasked and are included in the mapping.", "np.ndarray: \"\"\" Determine a projected radial grid of points from", "border. 4: Determine if it is outside the border, by", "1] / pixel_scales[1]) + centres_scaled[1] + 0.5 ) return grid_pixels_2d", "a slimmed grid of 2d (y,x) scaled coordinates to a", "def grid_2d_centre_from(grid_2d_slim: np.ndarray) -> Tuple[float, float]: \"\"\" Returns the centre", "grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_pixels_2d_slim=grid_pixels_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_scaled_2d_slim", "top-left, whose native index is [0,0], corresponds to slimmed pixel", ") grid_2d_native_x = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 1], mask_2d=mask_2d, sub_size=sub_size ) return", "2) and (total_pixels,). For example: The pixel at the top-left,", "centre[1] for slim_index in range(shape_slim): grid_scaled_2d_slim_radii[slim_index, 1] = radii radii", "2 + (y - coordinate[0]) ** 2 if distance_to_centre_new >=", "pixels to a slimmed grid of shape [total_unmasked_pixels, 2]. The", "they include the decimal offset from each pixel's top-left corner", "[0,5], corresponds to slimmed pixel index 4. The first pixel", "= int( (grid_scaled_2d[y, x, 1] / pixel_scales[1]) + centres_scaled[1] +", "a sub-grid. Parameters ---------- grid_slim The slimmed grid of (y,x)", "int( (-grid_scaled_2d[y, x, 0] / pixel_scales[0]) + centres_scaled[0] + 0.5", "= (y - centres_scaled[0]) * pixel_scales[0] x_scaled = (x -", "which is converted to slimmed pixel indexes. shape_native The (y,x)", "\"\"\" For a sub-grid, every unmasked pixel of its 2D", "mapped from the 2D grid with dimensions (total_unmasked_pixels). \"\"\" grid_1d_slim_y", "- extent[2] scaled_distance = max( [ distance_to_positive_x, distance_to_positive_y, distance_to_negative_x, distance_to_negative_y,", "the grid, such that the pixel [0,0] corresponds to the", "values (0.0, 0.0). Grids are defined from the top-left corner,", "stored in the 0 index of the second dimension, x", "chosen (e.g. if the positive x-axis was the longest, the", "(y,x) coordinates in scaled units which is converted to slimmed", "/ pixel_scales[1]) + centres_scaled[1] + 0.5 ) return grid_pixels_2d_slim @numba_util.jit()", "to each grid coordinate, analogous to a sub-grid. Parameters ----------", "with shape (total_pixels**2*sub_size**2, 2). y coordinates are stored in the", "sub_size return grid_scaled_2d_slim_radii @numba_util.jit() def grid_pixels_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int,", "grid is defined by the class attribute origin, and coordinates", "for y in range(grid_scaled_2d.shape[0]): for x in range(grid_scaled_2d.shape[1]): grid_pixels_2d[y, x,", "units to pixel units conversion factor of the original 2D", "(see *mask._border_1d_indexes*). This is performed as follows: 1: Use the", "centres_scaled[1]) * pixel_scales[1] for y1 in range(sub_size): for x1 in", "coordinate grid is defined by the class attribute origin, and", "array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 0], mask_2d=mask_2d, sub_size=sub_size ) grid_2d_native_x = array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:,", ") for y in range(grid_scaled_2d.shape[0]): for x in range(grid_scaled_2d.shape[1]): grid_pixels_2d[y,", "operates as follows: 1) Given the region defined by the", "in range(shape_slim): grid_scaled_2d_slim_radii[slim_index, 1] = radii radii += pixel_scale /", "grid of 2d (y,x) scaled coordinates to a slimmed grid", "grid_pixels_2d_slim[slim_index, 1] = ( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1]) + centres_scaled[1]", "total_x_pixels) is divided into a finer uniform grid of shape", "grid of pixel indexes. Pixel coordinates are returned as integers", "* (grid[pixel_index, :] - border_origin[:]) + border_origin[:] ) return grid_relocated", "- If slim_to_native[0] = [0,0], the first value of the", "* y_upscale_step - (y_upscale_step / 2.0) ) grid_2d_slim_upscaled[upscale_index, 1] =", "to a sub-grid. Parameters ---------- grid_slim The slimmed grid of", "which are mapped to a 2D array. Returns ------- (float,", "is divided into. origin The (y,x) origin of the 2D", "a native 2D grid and mask of shape [total_y_pixels, total_x_pixels,", "The slimmed grid of 2D (y,x) coordinates in scaled units", "Tuple[float, float]: \"\"\" Returns the centre of a grid from", "return grid_scaled_2d_slim_radii @numba_util.jit() def grid_pixels_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int],", "1], border_origin[1])), ) ) border_min_radii = np.min(border_grid_radii) grid_radii = np.sqrt(", "border_origin[:]) + border_origin[:] ) return grid_relocated @numba_util.jit() def furthest_grid_2d_slim_index_from( grid_2d_slim:", "is performed as follows: 1: Use the mean value of", "= (np.max(grid_2d_slim[:, 1]) + np.min(grid_2d_slim[:, 1])) / 2.0 return centre_y,", "border, by comparing its radial distance from the origin to", "float] = (0.0, 0.0), ) -> np.ndarray: \"\"\" Convert a", "+ centres_scaled[1] + 0.5 ) return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_indexes_2d_slim_from(", "0] = int( (-grid_scaled_2d[y, x, 0] / pixel_scales[0]) + centres_scaled[0]", "mask array is divided into. origin : (float, flloat) The", "the (y,x) scaled coordinates a the centre of every sub-pixel", "extracting the unmasked values from a native 2D grid of", ": ndarray The native grid of (y,x) values which are", "of each unmasked pixels sub-array. Returns ------- ndarray A 1D", "extent window. The returned `grid_radii` represents a radial set of", "range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = ( (-grid_scaled_2d_slim[slim_index, 0] / pixel_scales[0]) +", "= (x - centres_scaled[1]) * pixel_scales[1] for y1 in range(sub_size):", "origin=(0.0, 0.0)) \"\"\" grid_scaled_2d_slim = np.zeros((grid_pixels_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from(", "relocated to the border edge if outside it. border_grid :", "to index 4 of the 1D grid. Parameters ---------- grid_2d_native", "resolution to each grid coordinate, analogous to a sub-grid. Parameters", "False] [True, False, True]]) grid_2d_slim = grid_2d_slim_via_shape_native_from(shape_native=(3,3), pixel_scales=(0.5, 0.5), sub_size=2,", "region defined by the extent [xmin, xmax, ymin, ymax], the", "radial path from centre to extent edge | | -------------------", "(grid_2d[i, 0] - centre[0]) ** 2 + ( grid_2d[i, 1]", "(y,x) coordinates over which a square uniform grid is overlaid.", "can be used in functions which require that a 2D", "of points sampling the longest distance from the centre to", "grid's mask (see *mask._border_1d_indexes*). This is performed as follows: 1:", "an input slimmed 2D grid, return an upscaled slimmed 2D", "0] / pixel_scales[0]) + centres_scaled[0] + 0.5 ) grid_pixels_2d[y, x,", "of 2d (y,x) scaled coordinates to a slimmed grid of", "scaled coordinate. The input and output grids are both slimmed", "float]], ) -> np.ndarray: \"\"\" From an input slimmed 2D", "their values from the 1D grid pixel indexes. Parameters ----------", "shape (3,3) where all pixels are unmasked: - pixel [0,0]", "its paired border pixel's radial distance. 5: If its radial", "shape_slim: Optional[int] = 0, ) -> np.ndarray: \"\"\" Determine a", "the border, where the border is defined as all pixels", "grid_pixels_2d_slim[slim_index, 1] = int( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1]) + centres_scaled[1]", "Grids are defined from the top-left corner, where the first", "pixel indexes. shape_native The (y,x) shape of the original 2D", "values. Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed grid of 2D", "(total_pixels,). Examples -------- grid_scaled_2d_slim = np.array([[1.0, 1.0], [2.0, 2.0], [3.0,", "input slimmed 2D grid, return an upscaled slimmed 2D grid", "2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=mask_2d.shape, pixel_scales=pixel_scales, origin=origin ) sub_index =", "slim_index in range(grid_slim.shape[0]): y_grid = grid_slim[slim_index, 0] x_grid = grid_slim[slim_index,", "(e.g. following the positive / negative y and x axes).", "coordinates in the 1 index. Masked pixels are given values", "the centre and the edge of the region using the", "pixel index 0. The fifth pixel on the top row,", "in range(mask_2d.shape[1]): if not mask_2d[y, x]: y_scaled = (y -", ") * pixel_scales[1] return grid_scaled_2d_slim @numba_util.jit() def grid_pixel_centres_2d_from( grid_scaled_2d: np.ndarray,", "distance. 5: If its radial distance is larger, use the", "[3.0, 3.0], [4.0, 4.0]]) grid_pixel_indexes_2d_slim = grid_pixel_indexes_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5),", "* shape_native[1] + grid_pixels_2d_slim[slim_index, 1] ) return grid_pixel_indexes_2d_slim @numba_util.jit() def", "to scaled coordinates. shape_native The (y,x) shape of the original", "1], mask_2d=mask, sub_size=sub_size ) return np.stack((grid_1d_slim_y, grid_1d_slim_x), axis=-1) def grid_2d_native_from(", "over which a square uniform grid is overlaid. upscale_factor The", "(y,x) pixel coordinate values. Pixel coordinates are returned as floats", "import array_2d_util from autoarray.geometry import geometry_util from autoarray import numba_util", "scaled coordinates were computed on. pixel_scales The (y,x) scaled units", "is at the top left corner of the native grid", "A sub grid of (y,x) scaled coordinates at the centre", "which the sub-grid is shifted around. Returns ------- ndarray A", "grid_2d_centre_from(grid_2d_slim: np.ndarray) -> Tuple[float, float]: \"\"\" Returns the centre of", "the second dimension, x coordinates in the 1 index. Grid2D", "correspond to index 1 of the 1D grid. - pixel", "grid. - pixel [1,0] of the 2D grid will correspond", "from its centre. This grid stores the radial coordinates as", "in the border. 4: Determine if it is outside the", "coordinates as (y,x) values (where all y values are the", "2D array of bools, where `False` values mean unmasked and", "slimmed grid of shape [total_unmasked_pixels, 2]. The pixel coordinate origin", "both slimmed and therefore shape (total_pixels, 2). The pixel coordinate", "centres_scaled[0] + 0.5 ) grid_pixels_2d_slim[slim_index, 1] = int( (grid_scaled_2d_slim[slim_index, 1]", "the slimmed grid. mask_2d A 2D array of bools, where", "conversion factor of the 2D mask array. sub_size The size", "coordinate, analogous to a sub-grid. Parameters ---------- grid_slim The slimmed", "2D mask array is divided into. shape_slim Manually choose the", "is input. Parameters ---------- extent The extent of the grid", "where `False` values mean unmasked and are included in the", "Pixel coordinates are returned as integers such that they are", "(y,x) central coordinates of the grid. \"\"\" centre_y = (np.max(grid_2d_slim[:,", "of 2D (y,x) pixel values. Pixel coordinates are returned as", "centre of every sub-pixel defined by this 2D mask array.", "(-grid_scaled_2d[y, x, 0] / pixel_scales[0]) + centres_scaled[0] + 0.5 )", "their 1D grid pixel coordinate values. Parameters ---------- grid_scaled_2d_slim: np.ndarray", "corresponds to the highest (most positive) y scaled coordinate and", "1] for y in range(upscale_factor): for x in range(upscale_factor): grid_2d_slim_upscaled[upscale_index,", "origin is at the top left corner of the grid,", "origin to its paired border pixel's radial distance. 5: If", "Examples -------- grid_scaled_2d_slim = np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0],", "0.5 ) grid_pixels_2d[y, x, 1] = int( (grid_scaled_2d[y, x, 1]", "slim_to_native[1] = [0,1], the second value of the 1D array", "---------- grid_2d_slim The 1D grid of values which are mapped", "def grid_2d_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float, Tuple[float, float]], sub_size: int,", "pixel in the border. 4: Determine if it is outside", "coordinate values. Parameters ---------- grid_scaled_2d_slim: np.ndarray The slimmed grid of", "2D grid where masked values are set to zero. This", "Examples -------- grid_2d = grid_2d_via_shape_native_from(shape_native=(3, 3), pixel_scales=(1.0, 1.0), sub_size=2, origin=(0.0,", "shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_scaled_2d_slim[slim_index, 0]", "slimmed pixel index 10 if a row has 10 pixels.", "- extent[0] distance_to_negative_y = centre[0] - extent[2] scaled_distance = max(", "+ x1 * x_sub_step + (x_sub_step / 2.0) ) sub_index", "stores the radial coordinates as (y,x) values (where all y", "grid : Grid2D The grid (uniform or irregular) whose pixels", ") grid_2d_slim_upscaled[upscale_index, 1] = ( x_grid - x_upscale_half + x", "to a 2D array. Returns ------- (float, float) The (y,x)", "every unmasked pixel of its 2D mask with shape (total_y_pixels,", "index is [0,0], corresponds to slimmed pixel index 0. The", "2D mapped from the slimmed grid. \"\"\" grid_2d_native_y = array_2d_util.array_2d_native_from(", "int( (grid_scaled_2d[y, x, 1] / pixel_scales[1]) + centres_scaled[1] + 0.5", "grid of 2D (y,x) pixel-value coordinates with dimensions (total_pixels, 2).", "np.ndarray, sub_size: int ) -> np.ndarray: \"\"\" For a slimmed", "which the radial grid is traced outwards from. pixel_scales The", "Convert a slimmed grid of 2D (y,x) scaled coordinates to", "dimension, x coordinates in the 1 index. Grids are defined", "positive x-axis was the longest, the pixel_scale in the x", "origin of the 2D array, which the sub-grid is shifted", "array the sub-grid of coordinates is computed for. pixel_scales The", "0.5 ) grid_pixels_2d_slim[slim_index, 1] = ( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1])", "return np.stack((grid_1d_slim_y, grid_1d_slim_x), axis=-1) def grid_2d_native_from( grid_2d_slim: np.ndarray, mask_2d: np.ndarray,", "are defined from the top-left corner, where the first sub-pixel", "the (y,x) centre to the edge of the region (e.g.", "central coordinate which the radial grid is traced outwards from.", "longest distance from the centre to the edge of the", "shifted around. Returns ------- ndarray A slimmed sub grid of", "slim_index in range(shape_slim): grid_scaled_2d_slim_radii[slim_index, 1] = radii radii += pixel_scale", "radial grid is traced outwards from. pixel_scales The (y,x) scaled", "a slimmed grid of 2d (y,x) pixel coordinate values. Pixel", "x = centre | | <-> = longest radial path", "pixel_scales The (y,x) scaled units to pixel units conversion factor", "shape_native The (y,x) shape of the original 2D array the", "-> np.ndarray: \"\"\" For a sub-grid, every unmasked pixel of", "origin is defined by the class attribute origin, and coordinates", "unmasked pixels, for example: - If slim_to_native[0] = [0,0], the", "3) Determine the number of pixels between the centre and", "\"\"\" grid_1d_slim_y = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 0], mask_2d=mask, sub_size=sub_size )", "are shifted to this origin after computing their values from", "each index gives the 2D pixel indexes of the grid's", "of the second dimension, x coordinates in the 1 index.", "radial distance from the origin to its paired border pixel's", "computed by extracting the unmasked values from a native 2D", "\"\"\" return grid_2d_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) @numba_util.jit()", "shape [total_y_pixels, total_x_pixels, 2], map the slimmed grid's coordinates back", "(float, flloat) The (y,x) central coordinate which the radial grid", "(y,x) scaled coordinates a the centre of every sub-pixel defined", "of the 1D grid. - pixel [0,1] of the 2D", "pixel_scales=(1.0, 1.0), sub_size=2, origin=(0.0, 0.0)) \"\"\" return grid_2d_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native),", "(y,x) scaled coordinates to a native grid of 2D (y,x)", "the positive x-axis. \"\"\" distance_to_positive_x = extent[1] - centre[1] distance_to_positive_y", "slimmed and therefore shape (total_pixels, 2). The pixel coordinate origin", ": (float, flloat) The (y,x) central coordinate which the radial", "Determine if it is outside the border, by comparing its", "are the same) as opposed to a 1D data structure", "after computing their values from the 1D grid pixel indexes.", "int: distance_to_centre = 0.0 for slim_index in slim_indexes: y =", "sub grid array has dimensions (total_unmasked_pixels*sub_size**2, 2). Examples -------- mask", "paths from the (y,x) centre to the edge of the", "of the grid, such that the pixel [0,0] corresponds to", "The method can be used on uniform or irregular grids,", "is shifted around. Returns ------- ndarray A slimmed sub grid", "the centre of every sub-pixel defined by this 2D mask", "The size (sub_size x sub_size) of each unmasked pixels sub-array.", "grid_pixel_centres_2d_from( grid_scaled_2d: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]],", "0]) + np.min(grid_2d_slim[:, 0])) / 2.0 centre_x = (np.max(grid_2d_slim[:, 1])", "the direction chosen (e.g. if the positive x-axis was the", "is divided into. origin : (float, flloat) The (y,x) origin", "- centre[1] ) ** 2 > radius ** 2: y_inside.append(grid_2d[i,", "array of bools, where `False` values mean unmasked and are", "bools, where `False` values mean unmasked and are included in", "import mask_2d_util @numba_util.jit() def grid_2d_centre_from(grid_2d_slim: np.ndarray) -> Tuple[float, float]: \"\"\"", "grid of 2D (y,x) pixel indexes with dimensions (y_pixels, x_pixels,", ") border_min_radii = np.min(border_grid_radii) grid_radii = np.sqrt( np.add( np.square(np.subtract(grid[:, 0],", "a square uniform grid is overlaid. upscale_factor The upscaled resolution", "= -( y_scaled - y_sub_half + y1 * y_sub_step +", "mask array. The sub grid array has dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size).", "row, whose native index is [0,1], has slimmed pixel index", "sub_size=sub_size ) return np.stack((grid_1d_slim_y, grid_1d_slim_x), axis=-1) def grid_2d_native_from( grid_2d_slim: np.ndarray,", "int, origin: Tuple[float, float] = (0.0, 0.0), ) -> np.ndarray:", "[1,1,:] of the native 2D grid. Parameters ---------- grid_2d_slim The", "(y,x) scaled coordinates at the centre of every pixel unmasked", "grid_pixels_2d[y, x, 1] = int( (grid_scaled_2d[y, x, 1] / pixel_scales[1])", "slimmed grid. Grid2D are defined from the top-left corner, where", "grid, such that the pixel [0,0] corresponds to the highest", "traced outwards from. pixel_scales The (y,x) scaled units to pixel", "[False, False, False] [True, False, True]]) grid_2d = grid_2d_via_mask_from(mask=mask, pixel_scales=(0.5,", "shape (total_pixels**2*sub_size**2, 2). y coordinates are stored in the 0", "grid which are mapped to the native 2D grid. mask_2d", "pixel_scales[1] for y1 in range(sub_size): for x1 in range(sub_size): grid_slim[sub_index,", "2D array the sub-grid of coordinates is computed for. pixel_scales", "as (y,x) values (where all y values are the same)", "(y,x) scaled coordinates at the centre of every sub-pixel defined", "= ( grid_pixels_2d_slim[slim_index, 1] - centres_scaled[1] - 0.5 ) *", "2D grid of shape [total_y_pixels, total_x_pixels, 2], map the slimmed", "array_2d_util from autoarray.geometry import geometry_util from autoarray import numba_util from", "(x - coordinate[1]) ** 2 + (y - coordinate[0]) **", "scaled coordinate on the gird. The scaled grid is defined", "a native grid of 2D (y,x) pixel values. Pixel coordinates", "y and x axes). 2) Use the pixel-scale corresponding to", "centre | | <-> = longest radial path from centre", "represents a radial set of points that in 1D sample", "grid is shifted to. Returns ------- ndarray A slimmed grid", "/ pixel_scales[0]) + centres_scaled[0] + 0.5 ) grid_pixels_2d_slim[slim_index, 1] =", "of 2D (y,x) coordinates in scaled units which is converted", "the grid. 2: Compute the radial distance of every grid", "= np.zeros((grid_pixels_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin )", "iterate from the centre in increasing steps of the pixel-scale.", "): pixel_scale = pixel_scales[0] else: pixel_scale = pixel_scales[1] if shape_slim", "centre[0]) ** 2 + ( grid_2d[i, 1] - centre[1] )", "------- ndarray A slimmed sub grid of (y,x) scaled coordinates", "mask_2d A 2D array of bools, where `False` values are", "extent[2] scaled_distance = max( [ distance_to_positive_x, distance_to_positive_y, distance_to_negative_x, distance_to_negative_y, ]", "dimension is used). 3) Determine the number of pixels between", "centres_scaled[1] + 0.5 ) return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim:", "the edge of the region using the longest path between", "distance of the 4 paths from the (y,x) centre to", "x in range(upscale_factor): grid_2d_slim_upscaled[upscale_index, 0] = ( y_grid + y_upscale_half", "This is performed as follows: 1: Use the mean value", "if distance_to_centre_new >= distance_to_centre: distance_to_centre = distance_to_centre_new furthest_grid_2d_slim_index = slim_index", "the fifth value of the 1D array maps to the", "shifted to. Returns ------- ndarray A slimmed grid of 2D", "* pixel_scales[0] x_scaled = (x - centres_scaled[1]) * pixel_scales[1] for", "def grid_pixel_centres_2d_from( grid_scaled_2d: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float,", "centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=mask_2d.shape, pixel_scales=pixel_scales, origin=origin ) sub_index = 0", "(y,x) scaled coordinates to a slimmed grid of pixel indexes.", "indexes. Parameters ---------- grid_scaled_2d: np.ndarray The native grid of 2D", "2D array of bools, where `False` values are unmasked and", "2D array, which the sub-grid is shifted around. Returns -------", "computing their 1D grid pixel indexes. Parameters ---------- grid_scaled_2d: np.ndarray", ":] = ( move_factor * (grid[pixel_index, :] - border_origin[:]) +", "longest, the pixel_scale in the x dimension is used). 3)", "a finer uniform grid of shape (total_y_pixels*sub_size, total_x_pixels*sub_size). This routine", "where all points are at the centre's y value =", "top-left corner, where the first unmasked sub-pixel corresponds to index", "+ (x_sub_step / 2.0) ) sub_index += 1 return grid_slim", "array has dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- grid_2d = grid_2d_via_shape_native_from(shape_native=(3,", "+ 0.5 ) return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim: np.ndarray,", "border_origin[0] = np.mean(border_grid[:, 0]) border_origin[1] = np.mean(border_grid[:, 1]) border_grid_radii =", "2D grid. mask_2d A 2D array of bools, where `False`", "------- ndarray A NumPy array of shape [total_y_pixels, total_x_pixels, 2]", "pixel index 4. The first pixel on the second row,", "(most negative) x scaled coordinate on the gird. The scaled", "origin of the grid. 2: Compute the radial distance of", "[1,1], the fifth value of the 1D array maps to", "4.0]]) grid_pixel_centres_2d = grid_pixel_centres_2d_from(grid_scaled_2d=grid_scaled_2d, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\"", ") upscale_index += 1 return grid_2d_slim_upscaled def grid_2d_of_points_within_radius( radius: float,", "analogous to a sub-grid. Parameters ---------- grid_slim The slimmed grid", "0.0)) \"\"\" grid_pixels_2d_slim = np.zeros((grid_scaled_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native,", "float], grid_2d: np.ndarray ): y_inside = [] x_inside = []", "such that for an grid of shape (3,3) where all", "slimmed grid of (y,x) coordinates over which a square uniform", "second dimension, x coordinates in the 1 index. Grid2D are", "np.ndarray, sub_size: int ) -> np.ndarray: \"\"\" For a native", "shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], sub_size: int, origin:", "the pixel-scale corresponding to the direction chosen (e.g. if the", "float]], sub_size: int, origin: Tuple[float, float] = (0.0, 0.0), )", "+ y_upscale_half - y * y_upscale_step - (y_upscale_step / 2.0)", "negative) x scaled coordinate on the gird. The scaled grid", "2D region of coordinates defined by an extent [xmin, xmax,", "if outside it. border_grid : Grid2D The grid of border", ") return grid_2d_native_from( grid_2d_slim=grid_2d_slim, mask_2d=mask_2d, sub_size=sub_size ) def grid_2d_slim_via_shape_native_from( shape_native:", "(y_sub_step / 2.0) ) grid_slim[sub_index, 1] = ( x_scaled -", "grid_2d[i, 1] - centre[1] ) ** 2 > radius **", "for irregular grids the border of the 'image-plane' mask is", "shape (total_y_pixels*sub_size, total_x_pixels*sub_size). y coordinates are stored in the 0", "+ 0.5 ) return grid_pixels_2d @numba_util.jit() def relocated_grid_via_jit_from(grid, border_grid): \"\"\"", "are unmasked: - pixel [0,0] of the 2D grid will", "to zero. This uses a 1D array 'slim_to_native' where each", ") grid_slim[sub_index, 1] = ( x_scaled - x_sub_half + x1", "attribute origin, and coordinates are shifted to this origin before", "the sub-grid that each pixel of the 2D mask array", "top-left corner, where the first sub-pixel corresponds to index [0,0].", "\"\"\" centre_y = (np.max(grid_2d_slim[:, 0]) + np.min(grid_2d_slim[:, 0])) / 2.0", "where the border is defined as all pixels at the", "mask: np.ndarray, sub_size: int ) -> np.ndarray: \"\"\" For a", "- y_sub_half + y1 * y_sub_step + (y_sub_step / 2.0)", "grid_2d_slim=grid_2d_slim, mask_2d=mask_2d, sub_size=sub_size ) def grid_2d_slim_via_shape_native_from( shape_native: Tuple[int, int], pixel_scales:", "mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) def grid_2d_via_shape_native_from( shape_native: Tuple[int,", "- centres_scaled[1] - 0.5 ) * pixel_scales[1] return grid_scaled_2d_slim @numba_util.jit()", "= geometry_util.central_scaled_coordinate_2d_from( shape_native=mask_2d.shape, pixel_scales=pixel_scales, origin=origin ) sub_index = 0 y_sub_half", "require that a 2D grid structure is input. Parameters ----------", "the 1D grid. Parameters ---------- grid_2d_native : ndarray The native", "1D array maps to the pixels [0,0,:] of the native", "If slim_to_native[1] = [0,1], the second value of the 1D", "the edge of the extent window. The returned `grid_radii` represents", "border pixel's radial distance. 5: If its radial distance is", "== 0: shape_slim = sub_size * int((scaled_distance / pixel_scale)) +", "= np.zeros( shape=(grid_slim.shape[0] * upscale_factor ** 2, 2) ) upscale_index", "sub-pixel has index 2, and so forth. Parameters ---------- mask_2d", "each pixel's top-left corner relative to the input scaled coordinate.", "coordinate, find its nearest pixel in the border. 4: Determine", "choose the shape of the 1D projected grid that is", "is [0,5], corresponds to slimmed pixel index 4. The first", "and output grids are both of shape (total_pixels, 2). Parameters", "that was computed by extracting the unmasked values from a", "of the native 2D grid. Parameters ---------- grid_2d_slim The (y,x)", "is shifted. Returns ------- ndarray A grid of slimmed pixel", "upscale_factor for slim_index in range(grid_slim.shape[0]): y_grid = grid_slim[slim_index, 0] x_grid", "the (y,x) values of the native 2D mapped from the", "grid_slim[slim_index, 0] x_grid = grid_slim[slim_index, 1] for y in range(upscale_factor):", "0.5) * pixel_scales[0] ) grid_scaled_2d_slim[slim_index, 1] = ( grid_pixels_2d_slim[slim_index, 1]", "contained within. The input and output grids are both slimmed", "method can be used on uniform or irregular grids, however", "pixel coordinates to a slimmed grid of 2D (y,x) scaled", "- 0.5) * pixel_scales[0] ) grid_scaled_2d_slim[slim_index, 1] = ( grid_pixels_2d_slim[slim_index,", "of the 2D mask array. sub_size The size of the", "of the calculated sub-grid. pixel_scales The (y,x) scaled units to", "origin=origin ) for y in range(grid_scaled_2d.shape[0]): for x in range(grid_scaled_2d.shape[1]):", "2.0 return centre_y, centre_x @numba_util.jit() def grid_2d_slim_via_mask_from( mask_2d: np.ndarray, pixel_scales:", "returned in its native dimensions with shape (total_y_pixels*sub_size, total_x_pixels*sub_size). y", "the region (e.g. following the positive / negative y and", "first unmasked sub-pixel corresponds to index 0. Sub-pixels that are", "y in range(mask_2d.shape[0]): for x in range(mask_2d.shape[1]): if not mask_2d[y,", "the 2D grid with dimensions (total_unmasked_pixels). \"\"\" grid_1d_slim_y = array_2d_util.array_2d_slim_from(", "and output grids are both native resolution and therefore have", "->x | x = centre | | <-> = longest", "sub-pixel in the first pixel has index 1, its next", "first pixel on the second row, whose native index is", "sub_size: int ) -> np.ndarray: \"\"\" For a slimmed 2D", "finer uniform grid of shape (total_y_pixels*sub_size, total_x_pixels*sub_size). This routine computes", "pixel indexes. The input and output grids are both of", "a default value). Returns ------- ndarray A radial set of", "(total_unmasked_pixels*sub_size**2, 2). y coordinates are stored in the 0 index", "the slimmed 2D grid which are mapped to the native", "(y,x) values of the native 2D mapped from the slimmed", "2D grid, return an upscaled slimmed 2D grid where (y,x)", "coordinates to a slimmed grid of 2D (y,x) pixel values.", "x_grid = grid_slim[slim_index, 1] for y in range(upscale_factor): for x", "unmasked pixel of its 2D mask with shape (total_y_pixels, total_x_pixels)", "pixels, for example: - If slim_to_native[0] = [0,0], the first", "xmax, ymin, ymax], the algorithm finds the longest 1D distance", "1.0), sub_size=2, origin=(0.0, 0.0)) \"\"\" return grid_2d_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales,", "x coordinates in the 1 index. Masked coordinates are therefore", "y_upscale_step - (y_upscale_step / 2.0) ) grid_2d_slim_upscaled[upscale_index, 1] = (", "array maps to the pixels [0,0,:] of the native 2D", "in increasing steps of the pixel-scale. 5) Rotate these radial", "of the same mask array pixel are indexed next to", "are indexed next to one another, such that the second", "False, False] [True, False, True]]) grid_2d_slim = grid_2d_slim_via_shape_native_from(shape_native=(3,3), pixel_scales=(0.5, 0.5),", "upscale_factor: int, pixel_scales: Union[float, Tuple[float, float]], ) -> np.ndarray: \"\"\"", "the top-left of the 2D grid going rights and then", "10 pixels. The scaled coordinate grid is defined by the", "same mask array pixel are indexed next to one another,", "of pixels between the centre and the edge of the", "pixel_scales: Union[float, Tuple[float, float]], origin: Tuple[float, float] = (0.0, 0.0),", "input and output grids are both slimmed and therefore shape", "sub_size: int ) -> np.ndarray: \"\"\" For a native 2D", "defined as all pixels at the edge of the grid's", "= array_2d_util.array_2d_native_from( array_2d_slim=grid_2d_slim[:, 1], mask_2d=mask_2d, sub_size=sub_size ) return np.stack((grid_2d_native_y, grid_2d_native_x),", "@numba_util.jit() def grid_2d_slim_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float, Tuple[float, float]], sub_size:", "distance_to_negative_y ): pixel_scale = pixel_scales[0] else: pixel_scale = pixel_scales[1] if", "centre_y, centre_x @numba_util.jit() def grid_2d_slim_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float, Tuple[float,", "to this origin before computing their 1D grid pixel indexes.", "the native grid and goes right-wards and downwards, such that", "This routine computes the (y,x) scaled coordinates at the centre", "sub-grid is returned in its native dimensions with shape (total_y_pixels*sub_size,", "2). The pixel coordinate origin is at the top left", "pixel_scales: Union[float, Tuple[float, float]], ) -> np.ndarray: \"\"\" From an", "distance_to_centre_new furthest_grid_2d_slim_index = slim_index return furthest_grid_2d_slim_index def grid_2d_slim_from( grid_2d_native: np.ndarray,", "output grids are both slimmed and therefore shape (total_pixels, 2).", "distance_to_centre: distance_to_centre = distance_to_centre_new furthest_grid_2d_slim_index = slim_index return furthest_grid_2d_slim_index def", "grid pixel indexes. Parameters ---------- grid_scaled_2d: np.ndarray The native grid", "1 index. Masked coordinates are therefore removed and not included", "grid_slim def grid_2d_via_mask_from( mask_2d: np.ndarray, pixel_scales: Union[float, Tuple[float, float]], sub_size:", "= [] for i in range(len(grid_2d[:, 0])): if (grid_2d[i, 0]", "on the 2D mask array. The sub grid is slimmed", "- centres_scaled[0]) * pixel_scales[0] x_scaled = (x - centres_scaled[1]) *", ") for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_scaled_2d_slim[slim_index, 0] = ( -(grid_pixels_2d_slim[slim_index,", "---------- grid_scaled_2d: np.ndarray The native grid of 2D (y,x) coordinates", "is shifted Returns ------- ndarray A slimmed grid of 2D", "defined by the class attribute origin, and coordinates are shifted", "------- ndarray A sub grid of (y,x) scaled coordinates at", "are mapped to the slimmed grid. mask_2d A 2D array", "that for an grid of shape (3,3) where all pixels", "( grid_pixels_2d_slim[slim_index, 1] - centres_scaled[1] - 0.5 ) * pixel_scales[1]", "for. pixel_scales The (y,x) scaled units to pixel units conversion", "by this 2D mask array. The sub-grid is returned on", "1D projected grid that is returned. If 0, the border", "used on uniform or irregular grids, however for irregular grids", "from centre to extent edge | | ------------------- Using the", "shape [total_y_pixels, total_x_pixels, 2] corresponding to the (y,x) values of", "centres_scaled[1] + 0.5 ) return grid_pixels_2d_slim @numba_util.jit() def grid_pixel_indexes_2d_slim_from( grid_scaled_2d_slim:", "ymax] and with a (y,x) centre. This functions operates as", "the border (if its inside the border, do nothing). The", "factor of the 2D mask array. sub_size The size of", "grid will correspond to index 4 of the 1D grid.", "(y,x) pixel coordinates to a slimmed grid of 2D (y,x)", "grid of (y,x) scaled coordinates at the centre of every", "(0.0, 0.0), ) -> np.ndarray: \"\"\" Convert a slimmed grid", "values which are mapped to a 2D array. Returns -------", "new grid coordinates are computed. pixel_scales The pixel scale of", "grid of points from a 2D region of coordinates defined", "index. Masked pixels are given values (0.0, 0.0). Grids are", "- pixel [0,1] of the 2D grid will correspond to", "grid_scaled_2d_slim = np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]])", "centre_x = (np.max(grid_2d_slim[:, 1]) + np.min(grid_2d_slim[:, 1])) / 2.0 return", "y_upscale_step = pixel_scales[0] / upscale_factor x_upscale_half = pixel_scales[1] / 2", "autoarray.structures.arrays.two_d import array_2d_util from autoarray.geometry import geometry_util from autoarray import", "/ (sub_size) x_sub_half = pixel_scales[1] / 2 x_sub_step = pixel_scales[1]", "the 1 index. Masked coordinates are therefore removed and not", "= max( [ distance_to_positive_x, distance_to_positive_y, distance_to_negative_x, distance_to_negative_y, ] ) if", "(float, flloat) The (y,x) origin of the 2D array, which", "sub-pixel corresponds to index [0,0]. Sub-pixels that are part of", "pixels [0,1,:] of the native 2D grid. - If slim_to_native[4]", "its border if they are outside the border, where the", "extent The extent of the grid the radii grid is", "of the slimmed 2D grid which are mapped to the", "of all unmasked pixels to a slimmed grid of shape", "the pixel-scale. 5) Rotate these radial coordinates by the input", "shape_native=shape_native, pixel_scales=pixel_scales, origin=origin, ) grid_pixel_indexes_2d_slim = np.zeros(grid_pixels_2d_slim.shape[0]) for slim_index in", "move_factor = ( border_grid_radii[closest_pixel_index] / grid_radii[pixel_index] ) if move_factor <", "---------- mask_2d A 2D array of bools, where `False` values", "pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\" grid_2d_slim = grid_2d_slim_via_mask_from( mask_2d=mask_2d,", "2D grid will correspond to index 4 of the 1D", "are mapped to the native 2D grid. mask_2d A 2D", "coordinates in scaled units which is converted to pixel indexes.", "coordinates were computed on. pixel_scales The (y,x) scaled units to", "returned `grid_radii` represents a radial set of points that in", "0, the border based on the 2D grid is used", "and (total_pixels,). For example: The pixel at the top-left, whose", "the grid the radii grid is computed using, with format", "pixel at the top-left, whose native index is [0,0], corresponds", "- border_origin[:]) + border_origin[:] ) return grid_relocated @numba_util.jit() def furthest_grid_2d_slim_index_from(", "mask_2d: np.ndarray, pixel_scales: Union[float, Tuple[float, float]], sub_size: int, origin: Tuple[float,", "row has 10 pixels. The scaled coordinate grid is defined", "distance from the centre to the edge of the extent", "if not mask_2d[y, x]: y_scaled = (y - centres_scaled[0]) *", "False, True]]) grid_2d_slim = grid_2d_slim_via_shape_native_from(shape_native=(3,3), pixel_scales=(0.5, 0.5), sub_size=2, origin=(0.0, 0.0))", "grid_2d_native : ndarray The native grid of (y,x) values which", "/ 2.0) ) upscale_index += 1 return grid_2d_slim_upscaled def grid_2d_of_points_within_radius(", "return grid_2d_slim_via_mask_from( mask_2d=np.full(fill_value=False, shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) def grid_2d_via_shape_native_from(", "distance_to_positive_y, distance_to_negative_x, distance_to_negative_y, ] ) if (scaled_distance == distance_to_positive_y) or", "to one another, such that the second sub-pixel in the", "A 2D array of bools, where `False` values are unmasked", "- coordinate[1]) ** 2 + (y - coordinate[0]) ** 2", "are part of the same mask array pixel are indexed", "/ 2.0) ) grid_2d_slim_upscaled[upscale_index, 1] = ( x_grid - x_upscale_half", "(y_pixels, x_pixels, 2). The pixel coordinate origin is at the", "slim_index in slim_indexes: y = grid_2d_slim[slim_index, 0] x = grid_2d_slim[slim_index,", "defined from the top-left corner, where the first sub-pixel corresponds", "have shape (y_pixels, x_pixels, 2). The pixel coordinate origin is", "each unmasked pixels sub-array. Returns ------- ndarray A 1D grid", "+= pixel_scale / sub_size return grid_scaled_2d_slim_radii @numba_util.jit() def grid_pixels_2d_slim_from( grid_scaled_2d_slim:", "sub grid array has dimensions (total_y_pixels*sub_size, total_x_pixels*sub_size). Examples -------- mask", "for example: - If slim_to_native[0] = [0,0], the first value", "origin of the grid, which the scaled grid is shifted.", "\"\"\" grid_scaled_2d_slim = np.zeros((grid_pixels_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales,", "shifted Returns ------- ndarray A native grid of 2D (y,x)", "Create a (y,x) grid of radial points where all points", "this 2D mask array. The sub-grid is returned on an", "np.min(border_grid_radii) grid_radii = np.sqrt( np.add( np.square(np.subtract(grid[:, 0], border_origin[0])), np.square(np.subtract(grid[:, 1],", "inside the border, do nothing). The method can be used", "in the x dimension is used). 3) Determine the number", "array_2d_native=grid_2d_native[:, :, 1], mask_2d=mask, sub_size=sub_size ) return np.stack((grid_1d_slim_y, grid_1d_slim_x), axis=-1)", "longest radial path from centre to extent edge | |", "[0,1], the second value of the 1D array maps to", "has index 2, and so forth. Parameters ---------- shape_native The", "to a slimmed grid of pixel indexes. Pixel coordinates are", "example: - If slim_to_native[0] = [0,0], the first value of", "grid_2d_slim_upscaled_from( grid_slim: np.ndarray, upscale_factor: int, pixel_scales: Union[float, Tuple[float, float]], )", "grid of (y,x) coordinates in pixel values which is converted", "points where all points are at the centre's y value", "- ->x | x = centre | | <-> =", "np.ndarray) -> Tuple[float, float]: \"\"\" Returns the centre of a", "return np.stack((grid_2d_native_y, grid_2d_native_x), axis=-1) @numba_util.jit() def grid_2d_slim_upscaled_from( grid_slim: np.ndarray, upscale_factor:", ") ** 2 > radius ** 2: y_inside.append(grid_2d[i, 0]) x_inside.append(grid_2d[i,", "above. 4) Create a (y,x) grid of radial points where", "0. The fifth pixel on the top row, whose native", ":, 1], mask_2d=mask, sub_size=sub_size ) return np.stack((grid_1d_slim_y, grid_1d_slim_x), axis=-1) def", "+= centre[0] radii = centre[1] for slim_index in range(shape_slim): grid_scaled_2d_slim_radii[slim_index,", "grid_1d_slim_x = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 1], mask_2d=mask, sub_size=sub_size ) return", "0]) border_origin[1] = np.mean(border_grid[:, 1]) border_grid_radii = np.sqrt( np.add( np.square(np.subtract(border_grid[:,", ") ) for pixel_index in range(grid.shape[0]): if grid_radii[pixel_index] > border_min_radii:", "distance_to_centre = distance_to_centre_new furthest_grid_2d_slim_index = slim_index return furthest_grid_2d_slim_index def grid_2d_slim_from(", ") grid_pixels_2d_slim[slim_index, 1] = ( (grid_scaled_2d_slim[slim_index, 1] / pixel_scales[1]) +", "grids are both native resolution and therefore have shape (y_pixels,", "the new grid coordinates are computed. pixel_scales The pixel scale", "grid that is returned. If 0, the border based on", "coordinates in scaled units which is converted to slimmed pixel", "y_sub_half + y1 * y_sub_step + (y_sub_step / 2.0) )", "input and output grids are both slimmed and have shapes", "@numba_util.jit() def grid_pixel_centres_2d_from( grid_scaled_2d: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float,", "= grid_slim[slim_index, 1] for y in range(upscale_factor): for x in", "2D mask with shape (total_y_pixels, total_x_pixels) is divided into a", "pixel_scales=pixel_scales, origin=origin, ) grid_pixel_indexes_2d_slim = np.zeros(grid_pixels_2d_slim.shape[0]) for slim_index in range(grid_pixels_2d_slim.shape[0]):", "/ (sub_size) for y in range(mask_2d.shape[0]): for x in range(mask_2d.shape[1]):", "total_x_pixels, 2], map the values of all unmasked pixels to", "or irregular grids, however for irregular grids the border of", "= np.array([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]) grid_pixel_centres_2d", "(total_y_pixels*sub_size, total_x_pixels*sub_size). y coordinates are stored in the 0 index", "coordinates over which a square uniform grid is overlaid. upscale_factor", "0.0)) \"\"\" grid_scaled_2d_slim = np.zeros((grid_pixels_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native,", "to determine the origin of the grid. 2: Compute the", "to the highest (most positive) y scaled coordinate and lowest", "= 0 y_sub_half = pixel_scales[0] / 2 y_sub_step = pixel_scales[0]", "for slim_index in range(grid_scaled_2d_slim.shape[0]): grid_pixels_2d_slim[slim_index, 0] = int( (-grid_scaled_2d_slim[slim_index, 0]", "grid_pixel_indexes_2d_slim @numba_util.jit() def grid_scaled_2d_slim_from( grid_pixels_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales:", "import Tuple, Union, Optional from autoarray.structures.arrays.two_d import array_2d_util from autoarray.geometry", "input `angle` clockwise. A schematric is shown below: ------------------- |", "5: If its radial distance is larger, use the ratio", "Tuple[float, float]], ) -> np.ndarray: \"\"\" From an input slimmed", "index 4 of the 1D grid. Parameters ---------- grid_2d_native :", "units to pixel units conversion factor of the 2D mask", "by extracting the unmasked values from a native 2D grid", "centres_scaled[1] - 0.5 ) * pixel_scales[1] return grid_scaled_2d_slim @numba_util.jit() def", "the decimal offset from each pixel's top-left corner relative to", "1 of the 1D grid. - pixel [1,0] of the", ") -> np.ndarray: \"\"\" Determine a projected radial grid of", "to the slimmed grid. mask_2d A 2D array of bools,", "= radii radii += pixel_scale / sub_size return grid_scaled_2d_slim_radii @numba_util.jit()", "irregular grids, however for irregular grids the border of the", "def grid_2d_native_from( grid_2d_slim: np.ndarray, mask_2d: np.ndarray, sub_size: int ) ->", "by an extent [xmin, xmax, ymin, ymax] and with a", "of (y,x) coordinates. \"\"\" grid_2d_slim_upscaled = np.zeros( shape=(grid_slim.shape[0] * upscale_factor", "with dimensions (total_pixels,). Examples -------- grid_scaled_2d_slim = np.array([[1.0, 1.0], [2.0,", "coordinates to a slimmed grid of 2D (y,x) scaled values.", "corresponds to index 0. Sub-pixels that are part of the", "dimensions (total_pixels,). Examples -------- grid_scaled_2d_slim = np.array([[1.0, 1.0], [2.0, 2.0],", "are contained within. The input and output grids are both", "x in range(mask_2d.shape[1]): if not mask_2d[y, x]: y_scaled = (y", "grid_2d_slim_via_mask_from( mask_2d=mask_2d, pixel_scales=pixel_scales, sub_size=sub_size, origin=origin ) return grid_2d_native_from( grid_2d_slim=grid_2d_slim, mask_2d=mask_2d,", "= pixel_scales[0] / (sub_size) x_sub_half = pixel_scales[1] / 2 x_sub_step", "the pixels [1,1,:] of the native 2D grid. Parameters ----------", "input and output grids are both of shape (total_pixels, 2).", "def grid_2d_of_points_within_radius( radius: float, centre: Tuple[float, float], grid_2d: np.ndarray ):", "of points that in 1D sample the 2D grid outwards", "index 0 of the 1D grid. - pixel [0,1] of", "= grid_pixel_indexes_2d_slim_from(grid_scaled_2d_slim=grid_scaled_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0)) \"\"\" grid_pixels_2d_slim =", "0.0)) \"\"\" grid_pixels_2d_slim = grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim=grid_scaled_2d_slim, shape_native=shape_native, pixel_scales=pixel_scales, origin=origin, )", "Determine the number of pixels between the centre and the", "upscale_factor ** 2, 2) ) upscale_index = 0 y_upscale_half =", "Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], sub_size: int, origin: Tuple[float,", "values which is converted to scaled coordinates. shape_native The (y,x)", "+ centres_scaled[1] + 0.5 ) return grid_pixels_2d @numba_util.jit() def relocated_grid_via_jit_from(grid,", "coordinates are returned as integers such that they are the", "such that they map directly to the pixel they are", "before computing their 1D grid pixel indexes. The input and", "grid_scaled_2d_slim @numba_util.jit() def grid_pixel_centres_2d_from( grid_scaled_2d: np.ndarray, shape_native: Tuple[int, int], pixel_scales:", "and have shapes (total_pixels, 2) and (total_pixels,). For example: The", "grid_2d_via_mask_from(mask=mask, pixel_scales=(0.5, 0.5), sub_size=1, origin=(0.0, 0.0)) \"\"\" grid_2d_slim = grid_2d_slim_via_mask_from(", "that is returned. If 0, the border based on the", "2D grid where (y,x) coordinates are added at an upscaled", "to index 0. Sub-pixels that are part of the same", "this origin before computing their 1D grid pixel indexes. Parameters", "unmasked and are included in the mapping. sub_size The size", "the scaled grid is shifted Returns ------- ndarray A native", "centre_y = (np.max(grid_2d_slim[:, 0]) + np.min(grid_2d_slim[:, 0])) / 2.0 centre_x", "value of the grid's y and x coordinates to determine", "range(shape_slim): grid_scaled_2d_slim_radii[slim_index, 1] = radii radii += pixel_scale / sub_size", "to the native 2D grid where masked values are set", "int( grid_pixels_2d_slim[slim_index, 0] * shape_native[1] + grid_pixels_2d_slim[slim_index, 1] ) return", "return grid_2d_slim_upscaled def grid_2d_of_points_within_radius( radius: float, centre: Tuple[float, float], grid_2d:", "(where all y values are the same) as opposed to", "(y,x) shape of the original 2D array the scaled coordinates", "1D grid pixel indexes. Parameters ---------- grid_pixels_2d_slim: np.ndarray The slimmed", "and downwards, such that for an grid of shape (3,3)", "grid's native unmasked pixels, for example: - If slim_to_native[0] =", "is defined by an origin and coordinates are shifted to", "-------- grid_2d = grid_2d_via_shape_native_from(shape_native=(3, 3), pixel_scales=(1.0, 1.0), sub_size=2, origin=(0.0, 0.0))", "grid_pixel_centres_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]],", "x, 0] = int( (-grid_scaled_2d[y, x, 0] / pixel_scales[0]) +", "range(mask_2d.shape[1]): if not mask_2d[y, x]: y_scaled = (y - centres_scaled[0])", "be used in functions which require that a 2D grid", "top-left of the 2D grid going rights and then downwards.", "ndarray A native grid of 2D (y,x) pixel indexes with", "= np.mean(border_grid[:, 1]) border_grid_radii = np.sqrt( np.add( np.square(np.subtract(border_grid[:, 0], border_origin[0])),", "their 1D grid pixel indexes. The input and output grids", "sample the 2D grid outwards from its centre. This grid", "x_upscale_step + (x_upscale_step / 2.0) ) upscale_index += 1 return", "dimensions (total_pixels, 2). Examples -------- grid_scaled_2d_slim = np.array([[1.0, 1.0], [2.0,", "shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for y in range(grid_scaled_2d.shape[0]): for x", "pixel_scales=pixel_scales, sub_size=sub_size, origin=origin ) return grid_2d_native_from( grid_2d_slim=grid_2d_slim, mask_2d=mask_2d, sub_size=sub_size )", "are therefore removed and not included in the slimmed grid.", "** 2 + ( grid_2d[i, 1] - centre[1] ) **", "[1,0], [1,1]) grid_pixels_2d_slim = grid_scaled_2d_slim_from(grid_pixels_2d_slim=grid_pixels_2d_slim, shape=(2,2), pixel_scales=(0.5, 0.5), origin=(0.0, 0.0))", "pixel coordinate values. Pixel coordinates are returned as floats such", "np.ndarray, upscale_factor: int, pixel_scales: Union[float, Tuple[float, float]], ) -> np.ndarray:", "from the 1D grid pixel indexes. Parameters ---------- grid_pixels_2d_slim: np.ndarray", "size (sub_size x sub_size) of each unmasked pixels sub-array. Returns", ") -> np.ndarray: \"\"\" Convert a slimmed grid of 2D", "np.zeros((grid_pixels_2d_slim.shape[0], 2)) centres_scaled = geometry_util.central_scaled_coordinate_2d_from( shape_native=shape_native, pixel_scales=pixel_scales, origin=origin ) for", "np.mean(border_grid[:, 0]) border_origin[1] = np.mean(border_grid[:, 1]) border_grid_radii = np.sqrt( np.add(", "-> np.ndarray: \"\"\" Convert a slimmed grid of 2d (y,x)", "(total_unmasked_pixels*sub_size**2, 2). Examples -------- mask = np.array([[True, False, True], [False,", "unmasked pixels sub-array. Returns ------- ndarray A 1D grid of", "np from typing import Tuple, Union, Optional from autoarray.structures.arrays.two_d import", "border_grid : Grid2D The grid of border (y,x) coordinates. \"\"\"", "mean value of the grid's y and x coordinates to", "shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]], origin: Tuple[float, float]", "-> np.ndarray: \"\"\" From an input slimmed 2D grid, return", "radius: float, centre: Tuple[float, float], grid_2d: np.ndarray ): y_inside =", "shape=shape_native), pixel_scales=pixel_scales, sub_size=sub_size, origin=origin, ) @numba_util.jit() def grid_scaled_2d_slim_radial_projected_from( extent: np.ndarray,", "the 1D grid pixel indexes. Parameters ---------- grid_pixels_2d_slim: np.ndarray The", "outside it. border_grid : Grid2D The grid of border (y,x)", "/ 2 y_upscale_step = pixel_scales[0] / upscale_factor x_upscale_half = pixel_scales[1]", "( -(grid_pixels_2d_slim[slim_index, 0] - centres_scaled[0] - 0.5) * pixel_scales[0] )", "xmax, ymin, ymax] and with a (y,x) centre. This functions", "an upscaled slimmed 2D grid where (y,x) coordinates are added", "origin, and coordinates are shifted to this origin before computing", "x axes). 2) Use the pixel-scale corresponding to the direction", "to the (y,x) values of the native 2D mapped from", "downwards. The input and output grids are both slimmed and", "2D grid structure is input. Parameters ---------- extent The extent", "y in range(grid_scaled_2d.shape[0]): for x in range(grid_scaled_2d.shape[1]): grid_pixels_2d[y, x, 0]", "used in functions which require that a 2D grid structure", "return grid_2d_native_from( grid_2d_slim=grid_2d_slim, mask_2d=mask_2d, sub_size=sub_size ) def grid_2d_slim_via_shape_native_from( shape_native: Tuple[int,", "= int( grid_pixels_2d_slim[slim_index, 0] * shape_native[1] + grid_pixels_2d_slim[slim_index, 1] )", "has index 2, and so forth. Parameters ---------- mask_2d A", "is shifted around. Returns ------- ndarray A sub grid of", "input and output grids are both native resolution and therefore", "range(grid_scaled_2d.shape[1]): grid_pixels_2d[y, x, 0] = int( (-grid_scaled_2d[y, x, 0] /", "Use the pixel-scale corresponding to the direction chosen (e.g. if", "the radii grid is computed using, with format [xmin, xmax,", "np.square(grid[pixel_index, 0] - border_grid[:, 0]) + np.square(grid[pixel_index, 1] - border_grid[:,", "= array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 0], mask_2d=mask, sub_size=sub_size ) grid_1d_slim_x =", "for i in range(len(grid_2d[:, 0])): if (grid_2d[i, 0] - centre[0])", "10 if a row has 10 pixels. The scaled coordinate", "pixel_scales[1] / (sub_size) for y in range(mask_2d.shape[0]): for x in", "For example: The pixel at the top-left, whose native index", "are both native resolution and therefore have shape (y_pixels, x_pixels,", "for slim_index in range(shape_slim): grid_scaled_2d_slim_radii[slim_index, 1] = radii radii +=", "edge of the grid's mask (see *mask._border_1d_indexes*). This is performed", "the 2D array, which the sub-grid is shifted around. Returns", "False, True], [False, False, False] [True, False, True]]) grid_2d_slim =", "dimensions with shape (total_y_pixels*sub_size, total_x_pixels*sub_size). y coordinates are stored in", "[0,0], corresponds to slimmed pixel index 0. The fifth pixel", "a the centre of every sub-pixel defined by this 2D", "the 0 index of the second dimension, x coordinates in", "by the input `angle` clockwise. A schematric is shown below:", "class attribute origin, and coordinates are shifted to this origin", "sub_size: int, origin: Tuple[float, float] = (0.0, 0.0), ) ->", "the 1 index. Grid2D are defined from the top-left corner,", "edge of the extent window. The returned `grid_radii` represents a", "range(sub_size): grid_slim[sub_index, 0] = -( y_scaled - y_sub_half + y1", "extent [xmin, xmax, ymin, ymax] and with a (y,x) centre.", "(total_pixels, 2) and (total_pixels,). For example: The pixel at the", "where (y,x) coordinates are added at an upscaled resolution to", "grid_pixels_2d_slim_from( grid_scaled_2d_slim: np.ndarray, shape_native: Tuple[int, int], pixel_scales: Union[float, Tuple[float, float]],", "the 2D grid is used (due to numba None cannot", "shapes (total_pixels, 2) and (total_pixels,). For example: The pixel at" ]
[ "gevent.queue import Queue from gevent import monkey; monkey.patch_all() from pyquery", "size = pq.find('tbody tr').size() for index in range(size): item =", "import monkey; monkey.patch_all() from pyquery import PyQuery class Proxies(): def", "# 国内普通代理 base_url = self.domestic_pt_url elif type == 3: #", "quantity): while not queue.empty(): url = queue.get() html = self.s.get(url,", "= { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5)", "_type = item.find('td').eq(3).text() self.result_arr.append({ str(_type).lower(): '{0}://{1}:{2}'.format(str(_type).lower(), ip, port) }) if", "type == 4: # 国外普通代理 base_url = self.abroad_pt_url # 获取所需要的页面URL", "1.国内高匿代理 2.国内普通代理 3.国外高匿代理 4.国外普通代理 ''' url_queue = Queue() need_pages =", "requests, math import gevent from gevent.queue import Queue from gevent", "coding: utf-8 import requests, math import gevent from gevent.queue import", "return self.result_arr if __name__ == '__main__': p = Proxies() p.get_proxies(20,", "type == 3: # 国外高匿代理 base_url = self.abroad_gn_url elif type", "get_proxies(self, quantity, type): ''' quantity: 数量 type: 类型 1.国内高匿代理 2.国内普通代理", "from gevent.queue import Queue from gevent import monkey; monkey.patch_all() from", "def get_result(self): return self.result_arr if __name__ == '__main__': p =", "3: # 国外高匿代理 base_url = self.abroad_gn_url elif type == 4:", "url_queue, quantity) ) gevent.joinall(gevent_list) def get_result(self): return self.result_arr if __name__", "ip = item.find('td').eq(0).text() port = item.find('td').eq(1).text() _type = item.find('td').eq(3).text() self.result_arr.append({", "国外高匿代理 base_url = self.abroad_gn_url elif type == 4: # 国外普通代理", "item.find('td').eq(0).text() port = item.find('td').eq(1).text() _type = item.find('td').eq(3).text() self.result_arr.append({ str(_type).lower(): '{0}://{1}:{2}'.format(str(_type).lower(),", "range(2): gevent_list.append( gevent.spawn(self.fetch_urls, url_queue, quantity) ) gevent.joinall(gevent_list) def get_result(self): return", "''' quantity: 数量 type: 类型 1.国内高匿代理 2.国内普通代理 3.国外高匿代理 4.国外普通代理 '''", "= self.abroad_gn_url elif type == 4: # 国外普通代理 base_url =", "if type == 1: # 国内高匿代理 base_url = self.domestic_gn_url elif", "tr').eq(index) ip = item.find('td').eq(0).text() port = item.find('td').eq(1).text() _type = item.find('td').eq(3).text()", "= 'http://www.kuaidaili.com/free/outha/{0}/' self.abroad_pt_url = 'http://www.kuaidaili.com/free/outtr/{0}/' self.result_arr = [] self.s =", "'__main__': p = Proxies() p.get_proxies(20, 1) result = p.get_result() print(result)", "like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'Referer': 'http://www.kuaidaili.com/' } def fetch_urls(self, queue,", "url = queue.get() html = self.s.get(url, headers=self.headers).text pq = PyQuery(html)", "# 国内高匿代理 base_url = self.domestic_gn_url elif type == 2: #", "item.find('td').eq(3).text() self.result_arr.append({ str(_type).lower(): '{0}://{1}:{2}'.format(str(_type).lower(), ip, port) }) if len(self.result_arr) >=", "X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'Referer': 'http://www.kuaidaili.com/'", "PyQuery(html) size = pq.find('tbody tr').size() for index in range(size): item", "= pq.find('tbody tr').size() for index in range(size): item = pq.find('tbody", "elif type == 3: # 国外高匿代理 base_url = self.abroad_gn_url elif", "= base_url.format(index+1) url_queue.put(url) # 处理所有URL,开启2个协程 gevent_list = [] for index", "# 处理所有URL,开启2个协程 gevent_list = [] for index in range(2): gevent_list.append(", "base_url = self.domestic_gn_url elif type == 2: # 国内普通代理 base_url", "''' url_queue = Queue() need_pages = int(math.ceil(quantity/15)) # 判断类型 if", "获取所需要的页面URL for index in range(need_pages): url = base_url.format(index+1) url_queue.put(url) #", "base_url.format(index+1) url_queue.put(url) # 处理所有URL,开启2个协程 gevent_list = [] for index in", "= self.domestic_gn_url elif type == 2: # 国内普通代理 base_url =", "range(size): item = pq.find('tbody tr').eq(index) ip = item.find('td').eq(0).text() port =", "Queue from gevent import monkey; monkey.patch_all() from pyquery import PyQuery", "quantity, type): ''' quantity: 数量 type: 类型 1.国内高匿代理 2.国内普通代理 3.国外高匿代理", "'http://www.kuaidaili.com/free/inha/{0}/' self.domestic_pt_url = 'http://www.kuaidaili.com/free/intr/{0}/' self.abroad_gn_url = 'http://www.kuaidaili.com/free/outha/{0}/' self.abroad_pt_url = 'http://www.kuaidaili.com/free/outtr/{0}/'", "self.result_arr if __name__ == '__main__': p = Proxies() p.get_proxies(20, 1)", "= requests.Session() self.headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac", "ip, port) }) if len(self.result_arr) >= quantity: break def get_proxies(self,", "self.domestic_pt_url elif type == 3: # 国外高匿代理 base_url = self.abroad_gn_url", "(KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'Referer': 'http://www.kuaidaili.com/' } def fetch_urls(self,", "= self.domestic_pt_url elif type == 3: # 国外高匿代理 base_url =", "# 国外高匿代理 base_url = self.abroad_gn_url elif type == 4: #", "type == 1: # 国内高匿代理 base_url = self.domestic_gn_url elif type", "import gevent from gevent.queue import Queue from gevent import monkey;", "= [] self.s = requests.Session() self.headers = { 'User-Agent': 'Mozilla/5.0", "not queue.empty(): url = queue.get() html = self.s.get(url, headers=self.headers).text pq", "import PyQuery class Proxies(): def __init__(self): self.domestic_gn_url = 'http://www.kuaidaili.com/free/inha/{0}/' self.domestic_pt_url", "url = base_url.format(index+1) url_queue.put(url) # 处理所有URL,开启2个协程 gevent_list = [] for", "url_queue.put(url) # 处理所有URL,开启2个协程 gevent_list = [] for index in range(2):", "'http://www.kuaidaili.com/free/outha/{0}/' self.abroad_pt_url = 'http://www.kuaidaili.com/free/outtr/{0}/' self.result_arr = [] self.s = requests.Session()", "= item.find('td').eq(1).text() _type = item.find('td').eq(3).text() self.result_arr.append({ str(_type).lower(): '{0}://{1}:{2}'.format(str(_type).lower(), ip, port)", "import Queue from gevent import monkey; monkey.patch_all() from pyquery import", "elif type == 2: # 国内普通代理 base_url = self.domestic_pt_url elif", "item.find('td').eq(1).text() _type = item.find('td').eq(3).text() self.result_arr.append({ str(_type).lower(): '{0}://{1}:{2}'.format(str(_type).lower(), ip, port) })", "国外普通代理 base_url = self.abroad_pt_url # 获取所需要的页面URL for index in range(need_pages):", "(Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko)", "self.result_arr = [] self.s = requests.Session() self.headers = { 'User-Agent':", "10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'Referer': 'http://www.kuaidaili.com/' }", "== '__main__': p = Proxies() p.get_proxies(20, 1) result = p.get_result()", "gevent import monkey; monkey.patch_all() from pyquery import PyQuery class Proxies():", "from pyquery import PyQuery class Proxies(): def __init__(self): self.domestic_gn_url =", "def __init__(self): self.domestic_gn_url = 'http://www.kuaidaili.com/free/inha/{0}/' self.domestic_pt_url = 'http://www.kuaidaili.com/free/intr/{0}/' self.abroad_gn_url =", "= int(math.ceil(quantity/15)) # 判断类型 if type == 1: # 国内高匿代理", "queue.get() html = self.s.get(url, headers=self.headers).text pq = PyQuery(html) size =", "OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'Referer':", "quantity: 数量 type: 类型 1.国内高匿代理 2.国内普通代理 3.国外高匿代理 4.国外普通代理 ''' url_queue", "__init__(self): self.domestic_gn_url = 'http://www.kuaidaili.com/free/inha/{0}/' self.domestic_pt_url = 'http://www.kuaidaili.com/free/intr/{0}/' self.abroad_gn_url = 'http://www.kuaidaili.com/free/outha/{0}/'", "type: 类型 1.国内高匿代理 2.国内普通代理 3.国外高匿代理 4.国外普通代理 ''' url_queue = Queue()", "'http://www.kuaidaili.com/free/intr/{0}/' self.abroad_gn_url = 'http://www.kuaidaili.com/free/outha/{0}/' self.abroad_pt_url = 'http://www.kuaidaili.com/free/outtr/{0}/' self.result_arr = []", "self.abroad_pt_url = 'http://www.kuaidaili.com/free/outtr/{0}/' self.result_arr = [] self.s = requests.Session() self.headers", "for index in range(need_pages): url = base_url.format(index+1) url_queue.put(url) # 处理所有URL,开启2个协程", "'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like", "'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML,", "monkey.patch_all() from pyquery import PyQuery class Proxies(): def __init__(self): self.domestic_gn_url", "self.domestic_pt_url = 'http://www.kuaidaili.com/free/intr/{0}/' self.abroad_gn_url = 'http://www.kuaidaili.com/free/outha/{0}/' self.abroad_pt_url = 'http://www.kuaidaili.com/free/outtr/{0}/' self.result_arr", "3.国外高匿代理 4.国外普通代理 ''' url_queue = Queue() need_pages = int(math.ceil(quantity/15)) #", "requests.Session() self.headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS", "index in range(size): item = pq.find('tbody tr').eq(index) ip = item.find('td').eq(0).text()", "break def get_proxies(self, quantity, type): ''' quantity: 数量 type: 类型", "self.abroad_pt_url # 获取所需要的页面URL for index in range(need_pages): url = base_url.format(index+1)", ") gevent.joinall(gevent_list) def get_result(self): return self.result_arr if __name__ == '__main__':", "tr').size() for index in range(size): item = pq.find('tbody tr').eq(index) ip", "math import gevent from gevent.queue import Queue from gevent import", "def get_proxies(self, quantity, type): ''' quantity: 数量 type: 类型 1.国内高匿代理", "= [] for index in range(2): gevent_list.append( gevent.spawn(self.fetch_urls, url_queue, quantity)", "== 1: # 国内高匿代理 base_url = self.domestic_gn_url elif type ==", "类型 1.国内高匿代理 2.国内普通代理 3.国外高匿代理 4.国外普通代理 ''' url_queue = Queue() need_pages", "monkey; monkey.patch_all() from pyquery import PyQuery class Proxies(): def __init__(self):", "range(need_pages): url = base_url.format(index+1) url_queue.put(url) # 处理所有URL,开启2个协程 gevent_list = []", "= item.find('td').eq(3).text() self.result_arr.append({ str(_type).lower(): '{0}://{1}:{2}'.format(str(_type).lower(), ip, port) }) if len(self.result_arr)", "PyQuery class Proxies(): def __init__(self): self.domestic_gn_url = 'http://www.kuaidaili.com/free/inha/{0}/' self.domestic_pt_url =", "'http://www.kuaidaili.com/' } def fetch_urls(self, queue, quantity): while not queue.empty(): url", "国内高匿代理 base_url = self.domestic_gn_url elif type == 2: # 国内普通代理", "4.国外普通代理 ''' url_queue = Queue() need_pages = int(math.ceil(quantity/15)) # 判断类型", "index in range(need_pages): url = base_url.format(index+1) url_queue.put(url) # 处理所有URL,开启2个协程 gevent_list", "self.result_arr.append({ str(_type).lower(): '{0}://{1}:{2}'.format(str(_type).lower(), ip, port) }) if len(self.result_arr) >= quantity:", "gevent.joinall(gevent_list) def get_result(self): return self.result_arr if __name__ == '__main__': p", "queue.empty(): url = queue.get() html = self.s.get(url, headers=self.headers).text pq =", "in range(2): gevent_list.append( gevent.spawn(self.fetch_urls, url_queue, quantity) ) gevent.joinall(gevent_list) def get_result(self):", "base_url = self.abroad_gn_url elif type == 4: # 国外普通代理 base_url", "type): ''' quantity: 数量 type: 类型 1.国内高匿代理 2.国内普通代理 3.国外高匿代理 4.国外普通代理", "处理所有URL,开启2个协程 gevent_list = [] for index in range(2): gevent_list.append( gevent.spawn(self.fetch_urls,", "if len(self.result_arr) >= quantity: break def get_proxies(self, quantity, type): '''", "2: # 国内普通代理 base_url = self.domestic_pt_url elif type == 3:", "}) if len(self.result_arr) >= quantity: break def get_proxies(self, quantity, type):", "# 判断类型 if type == 1: # 国内高匿代理 base_url =", "pq.find('tbody tr').eq(index) ip = item.find('td').eq(0).text() port = item.find('td').eq(1).text() _type =", "== 3: # 国外高匿代理 base_url = self.abroad_gn_url elif type ==", "= 'http://www.kuaidaili.com/free/intr/{0}/' self.abroad_gn_url = 'http://www.kuaidaili.com/free/outha/{0}/' self.abroad_pt_url = 'http://www.kuaidaili.com/free/outtr/{0}/' self.result_arr =", "base_url = self.domestic_pt_url elif type == 3: # 国外高匿代理 base_url", "utf-8 import requests, math import gevent from gevent.queue import Queue", "Proxies(): def __init__(self): self.domestic_gn_url = 'http://www.kuaidaili.com/free/inha/{0}/' self.domestic_pt_url = 'http://www.kuaidaili.com/free/intr/{0}/' self.abroad_gn_url", "elif type == 4: # 国外普通代理 base_url = self.abroad_pt_url #", "self.abroad_gn_url elif type == 4: # 国外普通代理 base_url = self.abroad_pt_url", "for index in range(2): gevent_list.append( gevent.spawn(self.fetch_urls, url_queue, quantity) ) gevent.joinall(gevent_list)", "{ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36", "index in range(2): gevent_list.append( gevent.spawn(self.fetch_urls, url_queue, quantity) ) gevent.joinall(gevent_list) def", "if __name__ == '__main__': p = Proxies() p.get_proxies(20, 1) result", "str(_type).lower(): '{0}://{1}:{2}'.format(str(_type).lower(), ip, port) }) if len(self.result_arr) >= quantity: break", "2.国内普通代理 3.国外高匿代理 4.国外普通代理 ''' url_queue = Queue() need_pages = int(math.ceil(quantity/15))", "in range(need_pages): url = base_url.format(index+1) url_queue.put(url) # 处理所有URL,开启2个协程 gevent_list =", "gevent_list = [] for index in range(2): gevent_list.append( gevent.spawn(self.fetch_urls, url_queue,", "get_result(self): return self.result_arr if __name__ == '__main__': p = Proxies()", "Chrome/51.0.2704.103 Safari/537.36', 'Referer': 'http://www.kuaidaili.com/' } def fetch_urls(self, queue, quantity): while", "type == 2: # 国内普通代理 base_url = self.domestic_pt_url elif type", "判断类型 if type == 1: # 国内高匿代理 base_url = self.domestic_gn_url", "url_queue = Queue() need_pages = int(math.ceil(quantity/15)) # 判断类型 if type", "in range(size): item = pq.find('tbody tr').eq(index) ip = item.find('td').eq(0).text() port", "[] for index in range(2): gevent_list.append( gevent.spawn(self.fetch_urls, url_queue, quantity) )", "need_pages = int(math.ceil(quantity/15)) # 判断类型 if type == 1: #", "gevent_list.append( gevent.spawn(self.fetch_urls, url_queue, quantity) ) gevent.joinall(gevent_list) def get_result(self): return self.result_arr", "class Proxies(): def __init__(self): self.domestic_gn_url = 'http://www.kuaidaili.com/free/inha/{0}/' self.domestic_pt_url = 'http://www.kuaidaili.com/free/intr/{0}/'", "= Queue() need_pages = int(math.ceil(quantity/15)) # 判断类型 if type ==", "quantity) ) gevent.joinall(gevent_list) def get_result(self): return self.result_arr if __name__ ==", "int(math.ceil(quantity/15)) # 判断类型 if type == 1: # 国内高匿代理 base_url", "queue, quantity): while not queue.empty(): url = queue.get() html =", "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'Referer': 'http://www.kuaidaili.com/' } def", "self.domestic_gn_url = 'http://www.kuaidaili.com/free/inha/{0}/' self.domestic_pt_url = 'http://www.kuaidaili.com/free/intr/{0}/' self.abroad_gn_url = 'http://www.kuaidaili.com/free/outha/{0}/' self.abroad_pt_url", "self.s.get(url, headers=self.headers).text pq = PyQuery(html) size = pq.find('tbody tr').size() for", "item = pq.find('tbody tr').eq(index) ip = item.find('td').eq(0).text() port = item.find('td').eq(1).text()", "# coding: utf-8 import requests, math import gevent from gevent.queue", "pq.find('tbody tr').size() for index in range(size): item = pq.find('tbody tr').eq(index)", "= item.find('td').eq(0).text() port = item.find('td').eq(1).text() _type = item.find('td').eq(3).text() self.result_arr.append({ str(_type).lower():", "# 获取所需要的页面URL for index in range(need_pages): url = base_url.format(index+1) url_queue.put(url)", "self.headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X", "国内普通代理 base_url = self.domestic_pt_url elif type == 3: # 国外高匿代理", "= self.abroad_pt_url # 获取所需要的页面URL for index in range(need_pages): url =", "__name__ == '__main__': p = Proxies() p.get_proxies(20, 1) result =", "= self.s.get(url, headers=self.headers).text pq = PyQuery(html) size = pq.find('tbody tr').size()", "== 4: # 国外普通代理 base_url = self.abroad_pt_url # 获取所需要的页面URL for", "for index in range(size): item = pq.find('tbody tr').eq(index) ip =", "'{0}://{1}:{2}'.format(str(_type).lower(), ip, port) }) if len(self.result_arr) >= quantity: break def", "headers=self.headers).text pq = PyQuery(html) size = pq.find('tbody tr').size() for index", "port) }) if len(self.result_arr) >= quantity: break def get_proxies(self, quantity,", "4: # 国外普通代理 base_url = self.abroad_pt_url # 获取所需要的页面URL for index", "while not queue.empty(): url = queue.get() html = self.s.get(url, headers=self.headers).text", "= pq.find('tbody tr').eq(index) ip = item.find('td').eq(0).text() port = item.find('td').eq(1).text() _type", "1: # 国内高匿代理 base_url = self.domestic_gn_url elif type == 2:", "self.abroad_gn_url = 'http://www.kuaidaili.com/free/outha/{0}/' self.abroad_pt_url = 'http://www.kuaidaili.com/free/outtr/{0}/' self.result_arr = [] self.s", "数量 type: 类型 1.国内高匿代理 2.国内普通代理 3.国外高匿代理 4.国外普通代理 ''' url_queue =", "self.domestic_gn_url elif type == 2: # 国内普通代理 base_url = self.domestic_pt_url", "def fetch_urls(self, queue, quantity): while not queue.empty(): url = queue.get()", "'http://www.kuaidaili.com/free/outtr/{0}/' self.result_arr = [] self.s = requests.Session() self.headers = {", "gevent.spawn(self.fetch_urls, url_queue, quantity) ) gevent.joinall(gevent_list) def get_result(self): return self.result_arr if", "= queue.get() html = self.s.get(url, headers=self.headers).text pq = PyQuery(html) size", "Queue() need_pages = int(math.ceil(quantity/15)) # 判断类型 if type == 1:", "} def fetch_urls(self, queue, quantity): while not queue.empty(): url =", "= 'http://www.kuaidaili.com/free/inha/{0}/' self.domestic_pt_url = 'http://www.kuaidaili.com/free/intr/{0}/' self.abroad_gn_url = 'http://www.kuaidaili.com/free/outha/{0}/' self.abroad_pt_url =", "Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103", "pyquery import PyQuery class Proxies(): def __init__(self): self.domestic_gn_url = 'http://www.kuaidaili.com/free/inha/{0}/'", "self.s = requests.Session() self.headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel", "Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',", "Gecko) Chrome/51.0.2704.103 Safari/537.36', 'Referer': 'http://www.kuaidaili.com/' } def fetch_urls(self, queue, quantity):", "= PyQuery(html) size = pq.find('tbody tr').size() for index in range(size):", "base_url = self.abroad_pt_url # 获取所需要的页面URL for index in range(need_pages): url", "from gevent import monkey; monkey.patch_all() from pyquery import PyQuery class", ">= quantity: break def get_proxies(self, quantity, type): ''' quantity: 数量", "gevent from gevent.queue import Queue from gevent import monkey; monkey.patch_all()", "import requests, math import gevent from gevent.queue import Queue from", "'Referer': 'http://www.kuaidaili.com/' } def fetch_urls(self, queue, quantity): while not queue.empty():", "fetch_urls(self, queue, quantity): while not queue.empty(): url = queue.get() html", "port = item.find('td').eq(1).text() _type = item.find('td').eq(3).text() self.result_arr.append({ str(_type).lower(): '{0}://{1}:{2}'.format(str(_type).lower(), ip,", "# 国外普通代理 base_url = self.abroad_pt_url # 获取所需要的页面URL for index in", "= 'http://www.kuaidaili.com/free/outtr/{0}/' self.result_arr = [] self.s = requests.Session() self.headers =", "Safari/537.36', 'Referer': 'http://www.kuaidaili.com/' } def fetch_urls(self, queue, quantity): while not", "[] self.s = requests.Session() self.headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh;", "quantity: break def get_proxies(self, quantity, type): ''' quantity: 数量 type:", "pq = PyQuery(html) size = pq.find('tbody tr').size() for index in", "len(self.result_arr) >= quantity: break def get_proxies(self, quantity, type): ''' quantity:", "== 2: # 国内普通代理 base_url = self.domestic_pt_url elif type ==", "html = self.s.get(url, headers=self.headers).text pq = PyQuery(html) size = pq.find('tbody" ]
[ "M2M100EncoderPolicy, ) self.builtin_policies[M2M100PreTrainedModel] = [ M2M100EncoderPolicy, M2M100DecoderPolicy, ] with suppress(Exception):", "parallelformers.policies.layoutlm import LayoutLMPolicy self.builtin_policies[LayoutLMPreTrainedModel] = [ LayoutLMPolicy, ] with suppress(Exception):", "MPNetEncoderPolicy, MPNetLayerPolicy, ] with suppress(Exception): from transformers.models.luke.modeling_luke import ( LukePreTrainedModel,", ") self.builtin_policies[BartPretrainedModel] = [ BartEncoderPolicy, BartDecoderPolicy, ] with suppress(Exception): from", "import ( DistilBertPreTrainedModel, ) from parallelformers.policies.distil_bert import DistilBertPolicy self.builtin_policies[DistilBertPreTrainedModel] =", "parallelformers.policies.longformer import LongformerPolicy self.builtin_policies[LongformerPreTrainedModel] = [ LongformerPolicy, ] with suppress(Exception):", "] with suppress(Exception): from transformers.models.xlnet.modeling_xlnet import ( XLNetPreTrainedModel, ) from", "from parallelformers.policies.mobilebert import MobileBertPolicy self.builtin_policies[MobileBertPreTrainedModel] = [ MobileBertPolicy, ] with", "from parallelformers.policies.luke import LukePolicy self.builtin_policies[LukePreTrainedModel] = [ LukePolicy, ] with", "MobileBertPolicy self.builtin_policies[MobileBertPreTrainedModel] = [ MobileBertPolicy, ] with suppress(Exception): from transformers.models.mpnet.modeling_mpnet", "import ( FSMTDecoderPolicy, FSMTEncoderPolicy, ) self.builtin_policies[PretrainedFSMTModel] = [ FSMTEncoderPolicy, FSMTDecoderPolicy,", "2.0 (the \"License\"); # you may not use this file", "= [ OpenAIGPTPolicy, ] with suppress(Exception): from transformers.models.electra.modeling_electra import (", ") self.builtin_policies[MPNetPreTrainedModel] = [ MPNetEncoderPolicy, MPNetLayerPolicy, ] with suppress(Exception): from", "with suppress(Exception): from transformers.models.tapas.modeling_tapas import ( TapasPreTrainedModel, ) from parallelformers.policies.tapas", "import ( MPNetEncoderPolicy, MPNetLayerPolicy, ) self.builtin_policies[MPNetPreTrainedModel] = [ MPNetEncoderPolicy, MPNetLayerPolicy,", "import DistilBertPolicy self.builtin_policies[DistilBertPreTrainedModel] = [ DistilBertPolicy, ] with suppress(Exception): from", "[ TapasPolicy, ] with suppress(Exception): from transformers.models.funnel.modeling_funnel import ( FunnelPreTrainedModel,", "= [ FunnelPolicy, ] with suppress(Exception): from transformers.models.layoutlm.modeling_layoutlm import (", "= [ BertPolicy, ] with suppress(Exception): from transformers.models.big_bird.modeling_big_bird import (", "import ( XLNetPreTrainedModel, ) from parallelformers.policies.xlnet import XLNetPolicy self.builtin_policies[XLNetPreTrainedModel] =", "from transformers.models.mbart.modeling_mbart import ( MBartPreTrainedModel, ) from parallelformers.policies.mbart import (", "from transformers.models.transfo_xl.modeling_transfo_xl import ( TransfoXLPreTrainedModel, ) from parallelformers.policies.transfo_xl import TransfoXLPolicy", "[ ReformerPolicy, ] with suppress(Exception): from transformers.models.longformer.modeling_longformer import ( LongformerPreTrainedModel,", "T5Policy self.builtin_policies[T5PreTrainedModel] = [ T5Policy, ] with suppress(Exception): from transformers.models.pegasus.modeling_pegasus", "MBartPreTrainedModel, ) from parallelformers.policies.mbart import ( MBartDecoderPolicy, MBartEncoderPolicy, ) self.builtin_policies[MBartPreTrainedModel]", "self.builtin_policies[DPRPretrainedQuestionEncoder] = [ BertPolicy, ] self.builtin_policies[DPRPretrainedContextEncoder] = [ BertPolicy, ]", "with suppress(Exception): from transformers.models.vit.modeling_vit import ViTPreTrainedModel from parallelformers.policies.vit import ViTPolicy", "MarianPreTrainedModel, ) from parallelformers.policies.marian import ( MarianDecoderPolicy, MarianEncoderPolicy, ) self.builtin_policies[MarianPreTrainedModel]", "( BertGenerationPreTrainedModel, ) from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertGenerationPreTrainedModel] = [", "[ MarianEncoderPolicy, MarianDecoderPolicy, ] with suppress(Exception): from transformers.models.mobilebert.modeling_mobilebert import (", "] with suppress(Exception): from transformers.models.prophetnet.modeling_prophetnet import ( ProphetNetPreTrainedModel, ) from", "( MegatronBertPreTrainedModel, ) from parallelformers.policies.megtron_bert import ( MegatronBertPolicy, ) self.builtin_policies[MegatronBertPreTrainedModel]", "parallelformers.policies.megtron_bert import ( MegatronBertPolicy, ) self.builtin_policies[MegatronBertPreTrainedModel] = [ MegatronBertPolicy, ]", "] def get_policy(self, model: nn.Module) -> Union[List[Policy], None]: \"\"\" Find", "under the License. from contextlib import suppress from typing import", "policies or none \"\"\" for k, v in self.available().items(): if", "[ LayoutLMPolicy, ] with suppress(Exception): from transformers.models.led.modeling_led import LEDPreTrainedModel from", "BlenderbotSmallDecoderPolicy, BlenderbotSmallEncoderPolicy, ) self.builtin_policies[BlenderbotSmallPreTrainedModel] = [ BlenderbotSmallEncoderPolicy, BlenderbotSmallDecoderPolicy, ] with", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "OpenAIGPTPolicy self.builtin_policies[OpenAIGPTPreTrainedModel] = [ OpenAIGPTPolicy, ] with suppress(Exception): from transformers.models.electra.modeling_electra", ") self.builtin_policies[ProphetNetPreTrainedModel] = [ ProphetNetEncoderPolicy, ProphetNetDecoderPolicy, ] with suppress(Exception): from", "parallelformers.policies.roberta import RobertaPolicy self.builtin_policies[RobertaPreTrainedModel] = [ RobertaPolicy, ] with suppress(Exception):", "XLMMLPPolicy, ] with suppress(Exception): from transformers.models.m2m_100.modeling_m2m_100 import ( M2M100PreTrainedModel, )", ") from parallelformers.policies.convbert import ConvBertPolicy self.builtin_policies[ConvBertPreTrainedModel] = [ ConvBertPolicy, ]", "GPTJPreTrainedModel, ) from parallelformers.policies.gptj import GPTJPolicy self.builtin_policies[GPTJPreTrainedModel] = [ GPTJPolicy,", "suppress from typing import List, Union from torch import nn", "[ RobertaPolicy, ] with suppress(Exception): from transformers.models.albert.modeling_albert import ( AlbertPreTrainedModel,", "import ( PegasusDecoderPolicy, PegasusEncoderPolicy, ) self.builtin_policies[PegasusPreTrainedModel] = [ PegasusEncoderPolicy, PegasusDecoderPolicy,", "[ BertPolicy, ] with suppress(Exception): from transformers.models.clip.modeling_clip import ( CLIPPreTrainedModel,", "XLMAttentionPolicy, XLMMLPPolicy, ) self.builtin_policies[XLMPreTrainedModel] = [ XLMAttentionPolicy, XLMMLPPolicy, ] with", "[ Wav2VecPolicy, ] with suppress(Exception): from transformers.models.xlnet.modeling_xlnet import ( XLNetPreTrainedModel,", "suppress(Exception): from transformers.models.deberta.modeling_deberta import ( DebertaPreTrainedModel, ) from parallelformers.policies.deberta import", "transformers.models.transfo_xl.modeling_transfo_xl import ( TransfoXLPreTrainedModel, ) from parallelformers.policies.transfo_xl import TransfoXLPolicy self.builtin_policies[TransfoXLPreTrainedModel]", "import ( BartPretrainedModel, ) from parallelformers.policies.bart import ( BartDecoderPolicy, BartEncoderPolicy,", "= [ M2M100EncoderPolicy, M2M100DecoderPolicy, ] with suppress(Exception): from transformers.models.marian.modeling_marian import", "from parallelformers.policies.deberta import DebertaPolicy self.builtin_policies[DebertaPreTrainedModel] = [ DebertaPolicy, ] with", ") self.builtin_policies[MegatronBertPreTrainedModel] = [ MegatronBertPolicy, ] def get_policy(self, model: nn.Module)", "( ProphetNetPreTrainedModel, ) from parallelformers.policies.prophetnet import ( ProphetNetDecoderPolicy, ProphetNetEncoderPolicy, )", "( BlenderbotPreTrainedModel, ) from parallelformers.policies.blenderbot import ( BlenderbotDecoderPolicy, BlenderbotEncoderPolicy, )", "[ CTRLPolicy, ] with suppress(Exception): from transformers.models.deberta_v2.modeling_deberta_v2 import ( DebertaV2PreTrainedModel,", "DebertaPolicy self.builtin_policies[DebertaPreTrainedModel] = [ DebertaPolicy, ] with suppress(Exception): from transformers.models.transfo_xl.modeling_transfo_xl", "LxmertPreTrainedModel, ) from parallelformers.policies.lxmert import LxmertPolicy self.builtin_policies[LxmertPreTrainedModel] = [ LxmertPolicy,", "import ( AlbertPreTrainedModel, ) from parallelformers.policies.albert import AlbertPolicy self.builtin_policies[AlbertPreTrainedModel] =", "( BlenderbotSmallDecoderPolicy, BlenderbotSmallEncoderPolicy, ) self.builtin_policies[BlenderbotSmallPreTrainedModel] = [ BlenderbotSmallEncoderPolicy, BlenderbotSmallDecoderPolicy, ]", "language governing permissions and # limitations under the License. from", "( MBartPreTrainedModel, ) from parallelformers.policies.mbart import ( MBartDecoderPolicy, MBartEncoderPolicy, )", "import LukePolicy self.builtin_policies[LukePreTrainedModel] = [ LukePolicy, ] with suppress(Exception): from", "ConvBertPolicy, ] with suppress(Exception): from transformers.models.bert_generation.modeling_bert_generation import ( BertGenerationPreTrainedModel, )", "Policy class AutoPolicy: \"\"\"Class for finds automatically appropriate policies for", "parallelformers.policies.bart import ( BartDecoderPolicy, BartEncoderPolicy, ) self.builtin_policies[BartPretrainedModel] = [ BartEncoderPolicy,", "from parallelformers.policies.electra import ElectraPolicy self.builtin_policies[ElectraPreTrainedModel] = [ ElectraPolicy, ] with", "appropriate policies for the current model\"\"\" def __init__(self): self.builtin_policies =", "] with suppress(Exception): from transformers.models.deit.modeling_deit import ( DeiTPreTrainedModel, ) from", "= [ LukePolicy, ] with suppress(Exception): from transformers.models.dpr.modeling_dpr import (", "import ( HubertPreTrainedModel, ) from parallelformers.policies.hubert import HubertPolicy self.builtin_policies[HubertPreTrainedModel] =", "from parallelformers.policies.wav2vec import Wav2VecPolicy self.builtin_policies[Wav2Vec2PreTrainedModel] = [ Wav2VecPolicy, ] with", "from transformers.models.clip.modeling_clip import ( CLIPPreTrainedModel, ) from parallelformers.policies.clip import (", "from parallelformers.policies.reformer import ReformerPolicy self.builtin_policies[ReformerPreTrainedModel] = [ ReformerPolicy, ] with", "= [ RoformerPolicy, ] with suppress(Exception): from transformers.models.ibert.modeling_ibert import (", "from transformers.models.funnel.modeling_funnel import ( FunnelPreTrainedModel, ) from parallelformers.policies.funnel import FunnelPolicy", "use this file except in compliance with the License. #", "] with suppress(Exception): from transformers.models.led.modeling_led import LEDPreTrainedModel from parallelformers.policies.led import", "suppress(Exception): from transformers.models.tapas.modeling_tapas import ( TapasPreTrainedModel, ) from parallelformers.policies.tapas import", "Speech2TextPreTrainedModel, ) from parallelformers.policies.speech_to_text import ( Speech2TextDecoderPolicy, Speech2TextEncoderPolicy, ) self.builtin_policies[Speech2TextPreTrainedModel]", "M2M100EncoderPolicy, M2M100DecoderPolicy, ] with suppress(Exception): from transformers.models.marian.modeling_marian import ( MarianPreTrainedModel,", "import ( GPTNeoPreTrainedModel, ) from parallelformers.policies.gpt_neo import GPTNeoPolicy self.builtin_policies[GPTNeoPreTrainedModel] =", "[ BlenderbotEncoderPolicy, BlenderbotDecoderPolicy, ] with suppress(Exception): from transformers.models.deberta.modeling_deberta import (", "= [ AlbertPolicy, ] with suppress(Exception): from transformers.models.gpt2.modeling_gpt2 import (", "] with suppress(Exception): from transformers.models.m2m_100.modeling_m2m_100 import ( M2M100PreTrainedModel, ) from", "import BertPolicy self.builtin_policies[BertGenerationPreTrainedModel] = [ BertPolicy, ] with suppress(Exception): from", "DeiTPolicy self.builtin_policies[DeiTPreTrainedModel] = [DeiTPolicy] with suppress(Exception): from transformers.models.mbart.modeling_mbart import (", "] with suppress(Exception): from transformers.models.longformer.modeling_longformer import ( LongformerPreTrainedModel, ) from", ") from parallelformers.policies.longformer import LongformerPolicy self.builtin_policies[LongformerPreTrainedModel] = [ LongformerPolicy, ]", "DebertaPolicy, ] with suppress(Exception): from transformers.models.transfo_xl.modeling_transfo_xl import ( TransfoXLPreTrainedModel, )", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "XLMMLPPolicy, ) self.builtin_policies[XLMPreTrainedModel] = [ XLMAttentionPolicy, XLMMLPPolicy, ] with suppress(Exception):", "] with suppress(Exception): from transformers.models.blenderbot.modeling_blenderbot import ( BlenderbotPreTrainedModel, ) from", "] with suppress(Exception): from transformers.models.funnel.modeling_funnel import ( FunnelPreTrainedModel, ) from", "with suppress(Exception): from transformers.models.distilbert.modeling_distilbert import ( DistilBertPreTrainedModel, ) from parallelformers.policies.distil_bert", "License. # You may obtain a copy of the License", ") self.builtin_policies[BigBirdPegasusPreTrainedModel] = [ BigBirdPegasusEncoderPolicy, BigBirdPegasusDecoderPolicy, ] with suppress(Exception): from", "( GPT2PreTrainedModel, ) from parallelformers.policies.gpt2 import GPT2Policy self.builtin_policies[GPT2PreTrainedModel] = [", "-> Union[List[Policy], None]: \"\"\" Find appropriate policies for the current", "self.builtin_policies[ViTPreTrainedModel] = [ ViTPolicy, ] with suppress(Exception): from transformers.models.deit.modeling_deit import", "suppress(Exception): from transformers.models.bart.modeling_bart import ( BartPretrainedModel, ) from parallelformers.policies.bart import", "PegasusEncoderPolicy, ) self.builtin_policies[PegasusPreTrainedModel] = [ PegasusEncoderPolicy, PegasusDecoderPolicy, ] with suppress(Exception):", "CLIPTextPolicy, CLIPVisionPolicy, ] with suppress(Exception): from transformers.models.detr.modeling_detr import ( DetrPreTrainedModel,", "under the License is distributed on an \"AS IS\" BASIS,", "suppress(Exception): from transformers.models.blenderbot.modeling_blenderbot import ( BlenderbotPreTrainedModel, ) from parallelformers.policies.blenderbot import", "License for the specific language governing permissions and # limitations", "from parallelformers.policies.m2m_100 import ( M2M100DecoderPolicy, M2M100EncoderPolicy, ) self.builtin_policies[M2M100PreTrainedModel] = [", ") self.builtin_policies[DetrPreTrainedModel] = [ DetrEncoderPolicy, DetrDecoderPolicy, ] with suppress(Exception): from", "transformers.models.fsmt.modeling_fsmt import ( PretrainedFSMTModel, ) from parallelformers.policies.fsmt import ( FSMTDecoderPolicy,", "self.builtin_policies[DebertaPreTrainedModel] = [ DebertaPolicy, ] with suppress(Exception): from transformers.models.transfo_xl.modeling_transfo_xl import", "import ( LxmertPreTrainedModel, ) from parallelformers.policies.lxmert import LxmertPolicy self.builtin_policies[LxmertPreTrainedModel] =", "] with suppress(Exception): from transformers.models.bart.modeling_bart import ( BartPretrainedModel, ) from", "from transformers.models.bart.modeling_bart import ( BartPretrainedModel, ) from parallelformers.policies.bart import (", "import ( BertPreTrainedModel, ) from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertPreTrainedModel] =", "suppress(Exception): from transformers.models.wav2vec2.modeling_wav2vec2 import ( Wav2Vec2PreTrainedModel, ) from parallelformers.policies.wav2vec import", "import XLMPreTrainedModel from parallelformers.policies.xlm import ( XLMAttentionPolicy, XLMMLPPolicy, ) self.builtin_policies[XLMPreTrainedModel]", "LEDEncoderPolicy, ) self.builtin_policies[LEDPreTrainedModel] = [ LEDEncoderPolicy, LEDDecoderPolicy, ] with suppress(Exception):", "transformers.models.big_bird.modeling_big_bird import ( BigBirdPreTrainedModel, ) from parallelformers.policies.bigbird import BigBirdPolicy self.builtin_policies[BigBirdPreTrainedModel]", "self.builtin_policies[BigBirdPreTrainedModel] = [ BigBirdPolicy, ] with suppress(Exception): from transformers.models.bigbird_pegasus.modeling_bigbird_pegasus import", "= [ MPNetEncoderPolicy, MPNetLayerPolicy, ] with suppress(Exception): from transformers.models.luke.modeling_luke import", "import ( CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ) self.builtin_policies[CLIPPreTrainedModel] = [ CLIPLayerPolicy,", ") self.builtin_policies[LEDPreTrainedModel] = [ LEDEncoderPolicy, LEDDecoderPolicy, ] with suppress(Exception): from", "= [ MBartEncoderPolicy, MBartDecoderPolicy, ] with suppress(Exception): from transformers.models.t5.modeling_t5 import", "parallelformers.policies.bert import BertPolicy self.builtin_policies[BertPreTrainedModel] = [ BertPolicy, ] with suppress(Exception):", "import suppress from typing import List, Union from torch import", "current model Args: model (nn.Module): model to parallelize Returns: Union[List[Policy],", ") from parallelformers.policies.xlnet import XLNetPolicy self.builtin_policies[XLNetPreTrainedModel] = [ XLNetPolicy, ]", "[ LukePolicy, ] with suppress(Exception): from transformers.models.dpr.modeling_dpr import ( DPRPretrainedContextEncoder,", "import ( DebertaPreTrainedModel, ) from parallelformers.policies.deberta import DebertaPolicy self.builtin_policies[DebertaPreTrainedModel] =", "import ( DPRPretrainedContextEncoder, DPRPretrainedQuestionEncoder, DPRPretrainedReader, ) self.builtin_policies[DPRPretrainedReader] = [ BertPolicy,", "TapasPolicy, ] with suppress(Exception): from transformers.models.funnel.modeling_funnel import ( FunnelPreTrainedModel, )", "= [ BlenderbotSmallEncoderPolicy, BlenderbotSmallDecoderPolicy, ] with suppress(Exception): from transformers.models.distilbert.modeling_distilbert import", "from parallelformers.policies.vit import ViTPolicy self.builtin_policies[ViTPreTrainedModel] = [ ViTPolicy, ] with", "suppress(Exception): from transformers.models.m2m_100.modeling_m2m_100 import ( M2M100PreTrainedModel, ) from parallelformers.policies.m2m_100 import", "DetrPreTrainedModel, ) from parallelformers.policies.detr import ( DetrDecoderPolicy, DetrEncoderPolicy, ) self.builtin_policies[DetrPreTrainedModel]", "from parallelformers.policies.roformer import RoformerPolicy self.builtin_policies[RoFormerPreTrainedModel] = [ RoformerPolicy, ] with", "import VisualBertPolicy self.builtin_policies[VisualBertPreTrainedModel] = [ VisualBertPolicy, ] with suppress(Exception): from", "AlbertPreTrainedModel, ) from parallelformers.policies.albert import AlbertPolicy self.builtin_policies[AlbertPreTrainedModel] = [ AlbertPolicy,", "GPTNeoPolicy, ] with suppress(Exception): from transformers.models.bert.modeling_bert import ( BertPreTrainedModel, )", "BlenderbotSmallEncoderPolicy, ) self.builtin_policies[BlenderbotSmallPreTrainedModel] = [ BlenderbotSmallEncoderPolicy, BlenderbotSmallDecoderPolicy, ] with suppress(Exception):", "import ( DetrPreTrainedModel, ) from parallelformers.policies.detr import ( DetrDecoderPolicy, DetrEncoderPolicy,", "= [ DetrEncoderPolicy, DetrDecoderPolicy, ] with suppress(Exception): from transformers.models.reformer.modeling_reformer import", "suppress(Exception): from transformers.models.albert.modeling_albert import ( AlbertPreTrainedModel, ) from parallelformers.policies.albert import", "Returns: Union[List[Policy], None]: appropriate policies or none \"\"\" for k,", "( RoFormerPreTrainedModel, ) from parallelformers.policies.roformer import RoformerPolicy self.builtin_policies[RoFormerPreTrainedModel] = [", "import ( Speech2TextPreTrainedModel, ) from parallelformers.policies.speech_to_text import ( Speech2TextDecoderPolicy, Speech2TextEncoderPolicy,", "from parallelformers.policies.clip import ( CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ) self.builtin_policies[CLIPPreTrainedModel] =", "import FunnelPolicy self.builtin_policies[FunnelPreTrainedModel] = [ FunnelPolicy, ] with suppress(Exception): from", "GPTJPolicy, ] with suppress(Exception): from transformers.models.megatron_bert import ( MegatronBertPreTrainedModel, )", "] with suppress(Exception): from transformers.models.bert.modeling_bert import ( BertPreTrainedModel, ) from", "in compliance with the License. # You may obtain a", "MarianEncoderPolicy, MarianDecoderPolicy, ] with suppress(Exception): from transformers.models.mobilebert.modeling_mobilebert import ( MobileBertPreTrainedModel,", "from parallelformers.policies.convbert import ConvBertPolicy self.builtin_policies[ConvBertPreTrainedModel] = [ ConvBertPolicy, ] with", "transformers.models.wav2vec2.modeling_wav2vec2 import ( Wav2Vec2PreTrainedModel, ) from parallelformers.policies.wav2vec import Wav2VecPolicy self.builtin_policies[Wav2Vec2PreTrainedModel]", "from parallelformers.policies.ibert import IBertPolicy self.builtin_policies[IBertPreTrainedModel] = [ IBertPolicy, ] with", "( DebertaV2PreTrainedModel, ) from parallelformers.policies.deberta_v2 import DebertaV2Policy self.builtin_policies[DebertaV2PreTrainedModel] = [", "software # distributed under the License is distributed on an", "[ XLMAttentionPolicy, XLMMLPPolicy, ] with suppress(Exception): from transformers.models.m2m_100.modeling_m2m_100 import (", "transformers.models.clip.modeling_clip import ( CLIPPreTrainedModel, ) from parallelformers.policies.clip import ( CLIPLayerPolicy,", "none \"\"\" for k, v in self.available().items(): if isinstance(model, k):", "suppress(Exception): from transformers.models.mbart.modeling_mbart import ( MBartPreTrainedModel, ) from parallelformers.policies.mbart import", ") from parallelformers.policies.blenderbot_small import ( BlenderbotSmallDecoderPolicy, BlenderbotSmallEncoderPolicy, ) self.builtin_policies[BlenderbotSmallPreTrainedModel] =", "import ( MPNetPreTrainedModel, ) from parallelformers.policies.mpnet import ( MPNetEncoderPolicy, MPNetLayerPolicy,", "TapasPreTrainedModel, ) from parallelformers.policies.tapas import TapasPolicy self.builtin_policies[TapasPreTrainedModel] = [ TapasPolicy,", "with suppress(Exception): from transformers.models.roformer.modeling_roformer import ( RoFormerPreTrainedModel, ) from parallelformers.policies.roformer", "self.builtin_policies[CTRLPreTrainedModel] = [ CTRLPolicy, ] with suppress(Exception): from transformers.models.deberta_v2.modeling_deberta_v2 import", "import ( MBartDecoderPolicy, MBartEncoderPolicy, ) self.builtin_policies[MBartPreTrainedModel] = [ MBartEncoderPolicy, MBartDecoderPolicy,", "MBartDecoderPolicy, ] with suppress(Exception): from transformers.models.t5.modeling_t5 import T5PreTrainedModel from parallelformers.policies.t5", "transformers.models.gpt_neo.modeling_gpt_neo import ( GPTNeoPreTrainedModel, ) from parallelformers.policies.gpt_neo import GPTNeoPolicy self.builtin_policies[GPTNeoPreTrainedModel]", "[ GPTJPolicy, ] with suppress(Exception): from transformers.models.megatron_bert import ( MegatronBertPreTrainedModel,", "parallelformers.policies.lxmert import LxmertPolicy self.builtin_policies[LxmertPreTrainedModel] = [ LxmertPolicy, ] with suppress(Exception):", "suppress(Exception): from transformers.models.mpnet.modeling_mpnet import ( MPNetPreTrainedModel, ) from parallelformers.policies.mpnet import", "( PegasusPreTrainedModel, ) from parallelformers.policies.pegasus import ( PegasusDecoderPolicy, PegasusEncoderPolicy, )", "with suppress(Exception): from transformers.models.m2m_100.modeling_m2m_100 import ( M2M100PreTrainedModel, ) from parallelformers.policies.m2m_100", ") from parallelformers.policies.transfo_xl import TransfoXLPolicy self.builtin_policies[TransfoXLPreTrainedModel] = [ TransfoXLPolicy, ]", "parallelformers.policies.mpnet import ( MPNetEncoderPolicy, MPNetLayerPolicy, ) self.builtin_policies[MPNetPreTrainedModel] = [ MPNetEncoderPolicy,", "= [ LxmertPolicy, ] with suppress(Exception): from transformers.models.hubert.modeling_hubert import (", "from transformers.models.speech_to_text.modeling_speech_to_text import ( Speech2TextPreTrainedModel, ) from parallelformers.policies.speech_to_text import (", "= [ FSMTEncoderPolicy, FSMTDecoderPolicy, ] with suppress(Exception): from transformers.models.xlm.modeling_xlm import", "policies for the current model Args: model (nn.Module): model to", "MarianEncoderPolicy, ) self.builtin_policies[MarianPreTrainedModel] = [ MarianEncoderPolicy, MarianDecoderPolicy, ] with suppress(Exception):", "parallelformers.policies.t5 import T5Policy self.builtin_policies[T5PreTrainedModel] = [ T5Policy, ] with suppress(Exception):", "2021 TUNiB inc. # # Licensed under the Apache License,", "with suppress(Exception): from transformers.models.t5.modeling_t5 import T5PreTrainedModel from parallelformers.policies.t5 import T5Policy", "transformers.models.electra.modeling_electra import ( ElectraPreTrainedModel, ) from parallelformers.policies.electra import ElectraPolicy self.builtin_policies[ElectraPreTrainedModel]", "transformers.models.bert.modeling_bert import ( BertPreTrainedModel, ) from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertPreTrainedModel]", "nn.Module) -> Union[List[Policy], None]: \"\"\" Find appropriate policies for the", "( CTRLPreTrainedModel, ) from parallelformers.policies.ctrl import CTRLPolicy self.builtin_policies[CTRLPreTrainedModel] = [", "( ConvBertPreTrainedModel, ) from parallelformers.policies.convbert import ConvBertPolicy self.builtin_policies[ConvBertPreTrainedModel] = [", "from transformers.models.bigbird_pegasus.modeling_bigbird_pegasus import ( BigBirdPegasusPreTrainedModel, ) from parallelformers.policies.bigbird_pegasus import (", "model: nn.Module) -> Union[List[Policy], None]: \"\"\" Find appropriate policies for", "transformers.models.layoutlm.modeling_layoutlm import ( LayoutLMPreTrainedModel, ) from parallelformers.policies.layoutlm import LayoutLMPolicy self.builtin_policies[LayoutLMPreTrainedModel]", ") from parallelformers.policies.tapas import TapasPolicy self.builtin_policies[TapasPreTrainedModel] = [ TapasPolicy, ]", "IBertPolicy self.builtin_policies[IBertPreTrainedModel] = [ IBertPolicy, ] with suppress(Exception): from transformers.models.tapas.modeling_tapas", "model\"\"\" def __init__(self): self.builtin_policies = {} with suppress(Exception): from transformers.models.gpt_neo.modeling_gpt_neo", "with suppress(Exception): from transformers.models.layoutlm.modeling_layoutlm import ( LayoutLMPreTrainedModel, ) from parallelformers.policies.layoutlm", ") from parallelformers.policies.ibert import IBertPolicy self.builtin_policies[IBertPreTrainedModel] = [ IBertPolicy, ]", "ViTPreTrainedModel from parallelformers.policies.vit import ViTPolicy self.builtin_policies[ViTPreTrainedModel] = [ ViTPolicy, ]", "] with suppress(Exception): from transformers.models.marian.modeling_marian import ( MarianPreTrainedModel, ) from", "= [ XLNetPolicy, ] with suppress(Exception): from transformers.models.retribert.modeling_retribert import (", "= [ CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ] with suppress(Exception): from transformers.models.detr.modeling_detr", "suppress(Exception): from transformers.models.gpt_neo.modeling_gpt_neo import ( GPTNeoPreTrainedModel, ) from parallelformers.policies.gpt_neo import", "k): return v return None def available(self): \"\"\"Dictionary of available", "MarianDecoderPolicy, MarianEncoderPolicy, ) self.builtin_policies[MarianPreTrainedModel] = [ MarianEncoderPolicy, MarianDecoderPolicy, ] with", "VisualBertPreTrainedModel, ) from parallelformers.policies.visual_bert import VisualBertPolicy self.builtin_policies[VisualBertPreTrainedModel] = [ VisualBertPolicy,", "import ( MegatronBertPreTrainedModel, ) from parallelformers.policies.megtron_bert import ( MegatronBertPolicy, )", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "transformers.models.mobilebert.modeling_mobilebert import ( MobileBertPreTrainedModel, ) from parallelformers.policies.mobilebert import MobileBertPolicy self.builtin_policies[MobileBertPreTrainedModel]", "import ( ProphetNetDecoderPolicy, ProphetNetEncoderPolicy, ) self.builtin_policies[ProphetNetPreTrainedModel] = [ ProphetNetEncoderPolicy, ProphetNetDecoderPolicy,", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "] with suppress(Exception): from transformers.models.gpt2.modeling_gpt2 import ( GPT2PreTrainedModel, ) from", "= [ IBertPolicy, ] with suppress(Exception): from transformers.models.tapas.modeling_tapas import (", "transformers.models.bart.modeling_bart import ( BartPretrainedModel, ) from parallelformers.policies.bart import ( BartDecoderPolicy,", "from parallelformers.policies.openai import OpenAIGPTPolicy self.builtin_policies[OpenAIGPTPreTrainedModel] = [ OpenAIGPTPolicy, ] with", "( HubertPreTrainedModel, ) from parallelformers.policies.hubert import HubertPolicy self.builtin_policies[HubertPreTrainedModel] = [", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "GPTNeoPolicy self.builtin_policies[GPTNeoPreTrainedModel] = [ GPTNeoPolicy, ] with suppress(Exception): from transformers.models.bert.modeling_bert", "from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertPreTrainedModel] = [ BertPolicy, ] with", "( BigBirdPreTrainedModel, ) from parallelformers.policies.bigbird import BigBirdPolicy self.builtin_policies[BigBirdPreTrainedModel] = [", ") from parallelformers.policies.albert import AlbertPolicy self.builtin_policies[AlbertPreTrainedModel] = [ AlbertPolicy, ]", "import ( LongformerPreTrainedModel, ) from parallelformers.policies.longformer import LongformerPolicy self.builtin_policies[LongformerPreTrainedModel] =", "to in writing, software # distributed under the License is", "from transformers.models.deberta_v2.modeling_deberta_v2 import ( DebertaV2PreTrainedModel, ) from parallelformers.policies.deberta_v2 import DebertaV2Policy", "get_policy(self, model: nn.Module) -> Union[List[Policy], None]: \"\"\" Find appropriate policies", "import ViTPolicy self.builtin_policies[ViTPreTrainedModel] = [ ViTPolicy, ] with suppress(Exception): from", "[ T5Policy, ] with suppress(Exception): from transformers.models.pegasus.modeling_pegasus import ( PegasusPreTrainedModel,", "self.builtin_policies[LEDPreTrainedModel] = [ LEDEncoderPolicy, LEDDecoderPolicy, ] with suppress(Exception): from transformers.models.prophetnet.modeling_prophetnet", "from typing import List, Union from torch import nn from", "# See the License for the specific language governing permissions", "suppress(Exception): from transformers.models.hubert.modeling_hubert import ( HubertPreTrainedModel, ) from parallelformers.policies.hubert import", ") self.builtin_policies[DPRPretrainedReader] = [ BertPolicy, ] self.builtin_policies[DPRPretrainedQuestionEncoder] = [ BertPolicy,", "parallelformers.policies.bert import BertPolicy self.builtin_policies[BertGenerationPreTrainedModel] = [ BertPolicy, ] with suppress(Exception):", "transformers.models.tapas.modeling_tapas import ( TapasPreTrainedModel, ) from parallelformers.policies.tapas import TapasPolicy self.builtin_policies[TapasPreTrainedModel]", "( MobileBertPreTrainedModel, ) from parallelformers.policies.mobilebert import MobileBertPolicy self.builtin_policies[MobileBertPreTrainedModel] = [", "= [ XLMAttentionPolicy, XLMMLPPolicy, ] with suppress(Exception): from transformers.models.m2m_100.modeling_m2m_100 import", "v in self.available().items(): if isinstance(model, k): return v return None", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "None]: \"\"\" Find appropriate policies for the current model Args:", ") self.builtin_policies[MBartPreTrainedModel] = [ MBartEncoderPolicy, MBartDecoderPolicy, ] with suppress(Exception): from", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "BigBirdPegasusPreTrainedModel, ) from parallelformers.policies.bigbird_pegasus import ( BigBirdPegasusDecoderPolicy, BigBirdPegasusEncoderPolicy, ) self.builtin_policies[BigBirdPegasusPreTrainedModel]", "import CTRLPolicy self.builtin_policies[CTRLPreTrainedModel] = [ CTRLPolicy, ] with suppress(Exception): from", "LxmertPolicy self.builtin_policies[LxmertPreTrainedModel] = [ LxmertPolicy, ] with suppress(Exception): from transformers.models.hubert.modeling_hubert", "with the License. # You may obtain a copy of", "transformers.models.gpt2.modeling_gpt2 import ( GPT2PreTrainedModel, ) from parallelformers.policies.gpt2 import GPT2Policy self.builtin_policies[GPT2PreTrainedModel]", "= [ ViTPolicy, ] with suppress(Exception): from transformers.models.deit.modeling_deit import (", "] with suppress(Exception): from transformers.models.albert.modeling_albert import ( AlbertPreTrainedModel, ) from", "LongformerPolicy, ] with suppress(Exception): from transformers.models.roformer.modeling_roformer import ( RoFormerPreTrainedModel, )", "] with suppress(Exception): from transformers.models.big_bird.modeling_big_bird import ( BigBirdPreTrainedModel, ) from", "suppress(Exception): from transformers.models.longformer.modeling_longformer import ( LongformerPreTrainedModel, ) from parallelformers.policies.longformer import", "import ( GPT2PreTrainedModel, ) from parallelformers.policies.gpt2 import GPT2Policy self.builtin_policies[GPT2PreTrainedModel] =", "BertPolicy, ] self.builtin_policies[DPRPretrainedContextEncoder] = [ BertPolicy, ] with suppress(Exception): from", "transformers.models.longformer.modeling_longformer import ( LongformerPreTrainedModel, ) from parallelformers.policies.longformer import LongformerPolicy self.builtin_policies[LongformerPreTrainedModel]", "from parallelformers.policies.led import ( LEDDecoderPolicy, LEDEncoderPolicy, ) self.builtin_policies[LEDPreTrainedModel] = [", ") self.builtin_policies[PretrainedFSMTModel] = [ FSMTEncoderPolicy, FSMTDecoderPolicy, ] with suppress(Exception): from", "( GPTNeoPreTrainedModel, ) from parallelformers.policies.gpt_neo import GPTNeoPolicy self.builtin_policies[GPTNeoPreTrainedModel] = [", "compliance with the License. # You may obtain a copy", ") self.builtin_policies[BlenderbotSmallPreTrainedModel] = [ BlenderbotSmallEncoderPolicy, BlenderbotSmallDecoderPolicy, ] with suppress(Exception): from", "transformers.models.deit.modeling_deit import ( DeiTPreTrainedModel, ) from parallelformers.policies.deit import DeiTPolicy self.builtin_policies[DeiTPreTrainedModel]", "agreed to in writing, software # distributed under the License", "parallelformers.policies.transfo_xl import TransfoXLPolicy self.builtin_policies[TransfoXLPreTrainedModel] = [ TransfoXLPolicy, ] with suppress(Exception):", "ViTPolicy, ] with suppress(Exception): from transformers.models.deit.modeling_deit import ( DeiTPreTrainedModel, )", ") from parallelformers.policies.deit import DeiTPolicy self.builtin_policies[DeiTPreTrainedModel] = [DeiTPolicy] with suppress(Exception):", "import ( XLMAttentionPolicy, XLMMLPPolicy, ) self.builtin_policies[XLMPreTrainedModel] = [ XLMAttentionPolicy, XLMMLPPolicy,", "with suppress(Exception): from transformers.models.blenderbot.modeling_blenderbot import ( BlenderbotPreTrainedModel, ) from parallelformers.policies.blenderbot", "suppress(Exception): from transformers.models.luke.modeling_luke import ( LukePreTrainedModel, ) from parallelformers.policies.luke import", "from transformers.models.lxmert.modeling_lxmert import ( LxmertPreTrainedModel, ) from parallelformers.policies.lxmert import LxmertPolicy", "with suppress(Exception): from transformers.models.xlnet.modeling_xlnet import ( XLNetPreTrainedModel, ) from parallelformers.policies.xlnet", ") from parallelformers.policies.speech_to_text import ( Speech2TextDecoderPolicy, Speech2TextEncoderPolicy, ) self.builtin_policies[Speech2TextPreTrainedModel] =", "distributed under the License is distributed on an \"AS IS\"", "suppress(Exception): from transformers.models.big_bird.modeling_big_bird import ( BigBirdPreTrainedModel, ) from parallelformers.policies.bigbird import", "parallelformers.policies.gptj import GPTJPolicy self.builtin_policies[GPTJPreTrainedModel] = [ GPTJPolicy, ] with suppress(Exception):", "from parallelformers.policies.hubert import HubertPolicy self.builtin_policies[HubertPreTrainedModel] = [ HubertPolicy, ] with", "( ReformerPreTrainedModel, ) from parallelformers.policies.reformer import ReformerPolicy self.builtin_policies[ReformerPreTrainedModel] = [", "( MegatronBertPolicy, ) self.builtin_policies[MegatronBertPreTrainedModel] = [ MegatronBertPolicy, ] def get_policy(self,", "from transformers.models.visual_bert.modeling_visual_bert import ( VisualBertPreTrainedModel, ) from parallelformers.policies.visual_bert import VisualBertPolicy", "CLIPVisionPolicy, ) self.builtin_policies[CLIPPreTrainedModel] = [ CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ] with", "RobertaPreTrainedModel, ) from parallelformers.policies.roberta import RobertaPolicy self.builtin_policies[RobertaPreTrainedModel] = [ RobertaPolicy,", "ReformerPolicy, ] with suppress(Exception): from transformers.models.longformer.modeling_longformer import ( LongformerPreTrainedModel, )", "FunnelPolicy self.builtin_policies[FunnelPreTrainedModel] = [ FunnelPolicy, ] with suppress(Exception): from transformers.models.layoutlm.modeling_layoutlm", "nn from parallelformers.policies.base import Policy class AutoPolicy: \"\"\"Class for finds", "transformers.models.marian.modeling_marian import ( MarianPreTrainedModel, ) from parallelformers.policies.marian import ( MarianDecoderPolicy,", "parallelformers.policies.pegasus import ( PegasusDecoderPolicy, PegasusEncoderPolicy, ) self.builtin_policies[PegasusPreTrainedModel] = [ PegasusEncoderPolicy,", "with suppress(Exception): from transformers.models.bart.modeling_bart import ( BartPretrainedModel, ) from parallelformers.policies.bart", "express or implied. # See the License for the specific", "import ( BigBirdPegasusPreTrainedModel, ) from parallelformers.policies.bigbird_pegasus import ( BigBirdPegasusDecoderPolicy, BigBirdPegasusEncoderPolicy,", "self.builtin_policies[GPTNeoPreTrainedModel] = [ GPTNeoPolicy, ] with suppress(Exception): from transformers.models.bert.modeling_bert import", "except in compliance with the License. # You may obtain", "from transformers.models.deit.modeling_deit import ( DeiTPreTrainedModel, ) from parallelformers.policies.deit import DeiTPolicy", "= [ HubertPolicy, ] with suppress(Exception): from transformers.models.wav2vec2.modeling_wav2vec2 import (", "with suppress(Exception): from transformers.models.electra.modeling_electra import ( ElectraPreTrainedModel, ) from parallelformers.policies.electra", ") from parallelformers.policies.deberta_v2 import DebertaV2Policy self.builtin_policies[DebertaV2PreTrainedModel] = [ DebertaV2Policy, ]", "suppress(Exception): from transformers.models.vit.modeling_vit import ViTPreTrainedModel from parallelformers.policies.vit import ViTPolicy self.builtin_policies[ViTPreTrainedModel]", "from parallelformers.policies.t5 import T5Policy self.builtin_policies[T5PreTrainedModel] = [ T5Policy, ] with", "from parallelformers.policies.blenderbot import ( BlenderbotDecoderPolicy, BlenderbotEncoderPolicy, ) self.builtin_policies[BlenderbotPreTrainedModel] = [", "suppress(Exception): from transformers.models.mobilebert.modeling_mobilebert import ( MobileBertPreTrainedModel, ) from parallelformers.policies.mobilebert import", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "parallelformers.policies.electra import ElectraPolicy self.builtin_policies[ElectraPreTrainedModel] = [ ElectraPolicy, ] with suppress(Exception):", "( PegasusDecoderPolicy, PegasusEncoderPolicy, ) self.builtin_policies[PegasusPreTrainedModel] = [ PegasusEncoderPolicy, PegasusDecoderPolicy, ]", "from transformers.models.blenderbot_small.modeling_blenderbot_small import ( BlenderbotSmallPreTrainedModel, ) from parallelformers.policies.blenderbot_small import (", "parallelformers.policies.luke import LukePolicy self.builtin_policies[LukePreTrainedModel] = [ LukePolicy, ] with suppress(Exception):", "not use this file except in compliance with the License.", "transformers.models.dpr.modeling_dpr import ( DPRPretrainedContextEncoder, DPRPretrainedQuestionEncoder, DPRPretrainedReader, ) self.builtin_policies[DPRPretrainedReader] = [", "from transformers.models.retribert.modeling_retribert import ( RetriBertPreTrainedModel, ) self.builtin_policies[RetriBertPreTrainedModel] = [ BertPolicy,", "= [ BertPolicy, ] self.builtin_policies[DPRPretrainedQuestionEncoder] = [ BertPolicy, ] self.builtin_policies[DPRPretrainedContextEncoder]", ") from parallelformers.policies.prophetnet import ( ProphetNetDecoderPolicy, ProphetNetEncoderPolicy, ) self.builtin_policies[ProphetNetPreTrainedModel] =", ") from parallelformers.policies.blenderbot import ( BlenderbotDecoderPolicy, BlenderbotEncoderPolicy, ) self.builtin_policies[BlenderbotPreTrainedModel] =", "[ BigBirdPolicy, ] with suppress(Exception): from transformers.models.bigbird_pegasus.modeling_bigbird_pegasus import ( BigBirdPegasusPreTrainedModel,", "MBartEncoderPolicy, MBartDecoderPolicy, ] with suppress(Exception): from transformers.models.t5.modeling_t5 import T5PreTrainedModel from", "( M2M100DecoderPolicy, M2M100EncoderPolicy, ) self.builtin_policies[M2M100PreTrainedModel] = [ M2M100EncoderPolicy, M2M100DecoderPolicy, ]", "] with suppress(Exception): from transformers.models.detr.modeling_detr import ( DetrPreTrainedModel, ) from", "import RobertaPolicy self.builtin_policies[RobertaPreTrainedModel] = [ RobertaPolicy, ] with suppress(Exception): from", "] with suppress(Exception): from transformers.models.hubert.modeling_hubert import ( HubertPreTrainedModel, ) from", "from contextlib import suppress from typing import List, Union from", "writing, software # distributed under the License is distributed on", "self.builtin_policies[ConvBertPreTrainedModel] = [ ConvBertPolicy, ] with suppress(Exception): from transformers.models.bert_generation.modeling_bert_generation import", "self.available().items(): if isinstance(model, k): return v return None def available(self):", "transformers.models.reformer.modeling_reformer import ( ReformerPreTrainedModel, ) from parallelformers.policies.reformer import ReformerPolicy self.builtin_policies[ReformerPreTrainedModel]", "you may not use this file except in compliance with", "import ( BlenderbotPreTrainedModel, ) from parallelformers.policies.blenderbot import ( BlenderbotDecoderPolicy, BlenderbotEncoderPolicy,", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "suppress(Exception): from transformers.models.bert_generation.modeling_bert_generation import ( BertGenerationPreTrainedModel, ) from parallelformers.policies.bert import", "from parallelformers.policies.bart import ( BartDecoderPolicy, BartEncoderPolicy, ) self.builtin_policies[BartPretrainedModel] = [", "LukePolicy, ] with suppress(Exception): from transformers.models.dpr.modeling_dpr import ( DPRPretrainedContextEncoder, DPRPretrainedQuestionEncoder,", "parallelformers.policies.detr import ( DetrDecoderPolicy, DetrEncoderPolicy, ) self.builtin_policies[DetrPreTrainedModel] = [ DetrEncoderPolicy,", "( LukePreTrainedModel, ) from parallelformers.policies.luke import LukePolicy self.builtin_policies[LukePreTrainedModel] = [", "with suppress(Exception): from transformers.models.dpr.modeling_dpr import ( DPRPretrainedContextEncoder, DPRPretrainedQuestionEncoder, DPRPretrainedReader, )", "from transformers.models.layoutlm.modeling_layoutlm import ( LayoutLMPreTrainedModel, ) from parallelformers.policies.layoutlm import LayoutLMPolicy", "from transformers.models.detr.modeling_detr import ( DetrPreTrainedModel, ) from parallelformers.policies.detr import (", "with suppress(Exception): from transformers.models.albert.modeling_albert import ( AlbertPreTrainedModel, ) from parallelformers.policies.albert", "DPRPretrainedQuestionEncoder, DPRPretrainedReader, ) self.builtin_policies[DPRPretrainedReader] = [ BertPolicy, ] self.builtin_policies[DPRPretrainedQuestionEncoder] =", "] self.builtin_policies[DPRPretrainedContextEncoder] = [ BertPolicy, ] with suppress(Exception): from transformers.models.lxmert.modeling_lxmert", "import ( MegatronBertPolicy, ) self.builtin_policies[MegatronBertPreTrainedModel] = [ MegatronBertPolicy, ] def", "import GPT2Policy self.builtin_policies[GPT2PreTrainedModel] = [ GPT2Policy, ] with suppress(Exception): from", "parallelformers.policies.xlnet import XLNetPolicy self.builtin_policies[XLNetPreTrainedModel] = [ XLNetPolicy, ] with suppress(Exception):", "from parallelformers.policies.detr import ( DetrDecoderPolicy, DetrEncoderPolicy, ) self.builtin_policies[DetrPreTrainedModel] = [", "( DeiTPreTrainedModel, ) from parallelformers.policies.deit import DeiTPolicy self.builtin_policies[DeiTPreTrainedModel] = [DeiTPolicy]", "RobertaPolicy, ] with suppress(Exception): from transformers.models.albert.modeling_albert import ( AlbertPreTrainedModel, )", "= [ GPTJPolicy, ] with suppress(Exception): from transformers.models.megatron_bert import (", "( BlenderbotSmallPreTrainedModel, ) from parallelformers.policies.blenderbot_small import ( BlenderbotSmallDecoderPolicy, BlenderbotSmallEncoderPolicy, )", "= [ MegatronBertPolicy, ] def get_policy(self, model: nn.Module) -> Union[List[Policy],", "( BlenderbotDecoderPolicy, BlenderbotEncoderPolicy, ) self.builtin_policies[BlenderbotPreTrainedModel] = [ BlenderbotEncoderPolicy, BlenderbotDecoderPolicy, ]", "import OpenAIGPTPolicy self.builtin_policies[OpenAIGPTPreTrainedModel] = [ OpenAIGPTPolicy, ] with suppress(Exception): from", "self.builtin_policies[HubertPreTrainedModel] = [ HubertPolicy, ] with suppress(Exception): from transformers.models.wav2vec2.modeling_wav2vec2 import", ") self.builtin_policies[CLIPPreTrainedModel] = [ CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ] with suppress(Exception):", "ElectraPolicy self.builtin_policies[ElectraPreTrainedModel] = [ ElectraPolicy, ] with suppress(Exception): from transformers.models.blenderbot_small.modeling_blenderbot_small", "CONDITIONS OF ANY KIND, either express or implied. # See", "self.builtin_policies[DistilBertPreTrainedModel] = [ DistilBertPolicy, ] with suppress(Exception): from transformers.models.convbert.modeling_convbert import", "suppress(Exception): from transformers.models.ibert.modeling_ibert import ( IBertPreTrainedModel, ) from parallelformers.policies.ibert import", "parallelformers.policies.bigbird_pegasus import ( BigBirdPegasusDecoderPolicy, BigBirdPegasusEncoderPolicy, ) self.builtin_policies[BigBirdPegasusPreTrainedModel] = [ BigBirdPegasusEncoderPolicy,", "with suppress(Exception): from transformers.models.ibert.modeling_ibert import ( IBertPreTrainedModel, ) from parallelformers.policies.ibert", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "self.builtin_policies[RobertaPreTrainedModel] = [ RobertaPolicy, ] with suppress(Exception): from transformers.models.albert.modeling_albert import", "[ DistilBertPolicy, ] with suppress(Exception): from transformers.models.convbert.modeling_convbert import ( ConvBertPreTrainedModel,", "AutoPolicy: \"\"\"Class for finds automatically appropriate policies for the current", "transformers.models.vit.modeling_vit import ViTPreTrainedModel from parallelformers.policies.vit import ViTPolicy self.builtin_policies[ViTPreTrainedModel] = [", "= [DeiTPolicy] with suppress(Exception): from transformers.models.mbart.modeling_mbart import ( MBartPreTrainedModel, )", "from parallelformers.policies.xlnet import XLNetPolicy self.builtin_policies[XLNetPreTrainedModel] = [ XLNetPolicy, ] with", ") self.builtin_policies[RetriBertPreTrainedModel] = [ BertPolicy, ] with suppress(Exception): from transformers.models.clip.modeling_clip", "import HubertPolicy self.builtin_policies[HubertPreTrainedModel] = [ HubertPolicy, ] with suppress(Exception): from", "from parallelformers.policies.mbart import ( MBartDecoderPolicy, MBartEncoderPolicy, ) self.builtin_policies[MBartPreTrainedModel] = [", "MBartDecoderPolicy, MBartEncoderPolicy, ) self.builtin_policies[MBartPreTrainedModel] = [ MBartEncoderPolicy, MBartDecoderPolicy, ] with", "CLIPVisionPolicy, ] with suppress(Exception): from transformers.models.detr.modeling_detr import ( DetrPreTrainedModel, )", "XLMPreTrainedModel from parallelformers.policies.xlm import ( XLMAttentionPolicy, XLMMLPPolicy, ) self.builtin_policies[XLMPreTrainedModel] =", ") self.builtin_policies[Speech2TextPreTrainedModel] = [ Speech2TextEncoderPolicy, Speech2TextDecoderPolicy, ] with suppress(Exception): from", "suppress(Exception): from transformers.models.funnel.modeling_funnel import ( FunnelPreTrainedModel, ) from parallelformers.policies.funnel import", "from transformers.models.hubert.modeling_hubert import ( HubertPreTrainedModel, ) from parallelformers.policies.hubert import HubertPolicy", "MobileBertPolicy, ] with suppress(Exception): from transformers.models.mpnet.modeling_mpnet import ( MPNetPreTrainedModel, )", "self.builtin_policies[RetriBertPreTrainedModel] = [ BertPolicy, ] with suppress(Exception): from transformers.models.clip.modeling_clip import", "from parallelformers.policies.longformer import LongformerPolicy self.builtin_policies[LongformerPreTrainedModel] = [ LongformerPolicy, ] with", "import LEDPreTrainedModel from parallelformers.policies.led import ( LEDDecoderPolicy, LEDEncoderPolicy, ) self.builtin_policies[LEDPreTrainedModel]", "Args: model (nn.Module): model to parallelize Returns: Union[List[Policy], None]: appropriate", ") from parallelformers.policies.mpnet import ( MPNetEncoderPolicy, MPNetLayerPolicy, ) self.builtin_policies[MPNetPreTrainedModel] =", "= {} with suppress(Exception): from transformers.models.gpt_neo.modeling_gpt_neo import ( GPTNeoPreTrainedModel, )", "[ DetrEncoderPolicy, DetrDecoderPolicy, ] with suppress(Exception): from transformers.models.reformer.modeling_reformer import (", "[ ElectraPolicy, ] with suppress(Exception): from transformers.models.blenderbot_small.modeling_blenderbot_small import ( BlenderbotSmallPreTrainedModel,", "BlenderbotSmallDecoderPolicy, ] with suppress(Exception): from transformers.models.distilbert.modeling_distilbert import ( DistilBertPreTrainedModel, )", "AlbertPolicy, ] with suppress(Exception): from transformers.models.gpt2.modeling_gpt2 import ( GPT2PreTrainedModel, )", "= [ ElectraPolicy, ] with suppress(Exception): from transformers.models.blenderbot_small.modeling_blenderbot_small import (", "self.builtin_policies[BertGenerationPreTrainedModel] = [ BertPolicy, ] with suppress(Exception): from transformers.models.big_bird.modeling_big_bird import", "the License. from contextlib import suppress from typing import List,", "transformers.models.convbert.modeling_convbert import ( ConvBertPreTrainedModel, ) from parallelformers.policies.convbert import ConvBertPolicy self.builtin_policies[ConvBertPreTrainedModel]", "import List, Union from torch import nn from parallelformers.policies.base import", "with suppress(Exception): from transformers.models.funnel.modeling_funnel import ( FunnelPreTrainedModel, ) from parallelformers.policies.funnel", "None def available(self): \"\"\"Dictionary of available models and policies\"\"\" return", "parallelize Returns: Union[List[Policy], None]: appropriate policies or none \"\"\" for", "import ( VisualBertPreTrainedModel, ) from parallelformers.policies.visual_bert import VisualBertPolicy self.builtin_policies[VisualBertPreTrainedModel] =", "self.builtin_policies[DeiTPreTrainedModel] = [DeiTPolicy] with suppress(Exception): from transformers.models.mbart.modeling_mbart import ( MBartPreTrainedModel,", "self.builtin_policies[MarianPreTrainedModel] = [ MarianEncoderPolicy, MarianDecoderPolicy, ] with suppress(Exception): from transformers.models.mobilebert.modeling_mobilebert", "transformers.models.blenderbot_small.modeling_blenderbot_small import ( BlenderbotSmallPreTrainedModel, ) from parallelformers.policies.blenderbot_small import ( BlenderbotSmallDecoderPolicy,", "self.builtin_policies[XLMPreTrainedModel] = [ XLMAttentionPolicy, XLMMLPPolicy, ] with suppress(Exception): from transformers.models.m2m_100.modeling_m2m_100", "ProphetNetPreTrainedModel, ) from parallelformers.policies.prophetnet import ( ProphetNetDecoderPolicy, ProphetNetEncoderPolicy, ) self.builtin_policies[ProphetNetPreTrainedModel]", "self.builtin_policies[ProphetNetPreTrainedModel] = [ ProphetNetEncoderPolicy, ProphetNetDecoderPolicy, ] with suppress(Exception): from transformers.models.visual_bert.modeling_visual_bert", "= [ Speech2TextEncoderPolicy, Speech2TextDecoderPolicy, ] with suppress(Exception): from transformers.models.gptj.modeling_gptj import", "self.builtin_policies[GPTJPreTrainedModel] = [ GPTJPolicy, ] with suppress(Exception): from transformers.models.megatron_bert import", "import ( M2M100DecoderPolicy, M2M100EncoderPolicy, ) self.builtin_policies[M2M100PreTrainedModel] = [ M2M100EncoderPolicy, M2M100DecoderPolicy,", "import ( ProphetNetPreTrainedModel, ) from parallelformers.policies.prophetnet import ( ProphetNetDecoderPolicy, ProphetNetEncoderPolicy,", "BlenderbotSmallPreTrainedModel, ) from parallelformers.policies.blenderbot_small import ( BlenderbotSmallDecoderPolicy, BlenderbotSmallEncoderPolicy, ) self.builtin_policies[BlenderbotSmallPreTrainedModel]", "] with suppress(Exception): from transformers.models.roberta.modeling_roberta import ( RobertaPreTrainedModel, ) from", "OR CONDITIONS OF ANY KIND, either express or implied. #", "with suppress(Exception): from transformers.models.megatron_bert import ( MegatronBertPreTrainedModel, ) from parallelformers.policies.megtron_bert", "XLNetPreTrainedModel, ) from parallelformers.policies.xlnet import XLNetPolicy self.builtin_policies[XLNetPreTrainedModel] = [ XLNetPolicy,", "transformers.models.hubert.modeling_hubert import ( HubertPreTrainedModel, ) from parallelformers.policies.hubert import HubertPolicy self.builtin_policies[HubertPreTrainedModel]", "policies for the current model\"\"\" def __init__(self): self.builtin_policies = {}", "for the current model\"\"\" def __init__(self): self.builtin_policies = {} with", "FunnelPreTrainedModel, ) from parallelformers.policies.funnel import FunnelPolicy self.builtin_policies[FunnelPreTrainedModel] = [ FunnelPolicy,", "[ DebertaV2Policy, ] with suppress(Exception): from transformers.models.openai.modeling_openai import ( OpenAIGPTPreTrainedModel,", "from parallelformers.policies.layoutlm import LayoutLMPolicy self.builtin_policies[LayoutLMPreTrainedModel] = [ LayoutLMPolicy, ] with", "the License is distributed on an \"AS IS\" BASIS, #", "FunnelPolicy, ] with suppress(Exception): from transformers.models.layoutlm.modeling_layoutlm import ( LayoutLMPreTrainedModel, )", "suppress(Exception): from transformers.models.deit.modeling_deit import ( DeiTPreTrainedModel, ) from parallelformers.policies.deit import", "LEDDecoderPolicy, ] with suppress(Exception): from transformers.models.prophetnet.modeling_prophetnet import ( ProphetNetPreTrainedModel, )", "Speech2TextEncoderPolicy, ) self.builtin_policies[Speech2TextPreTrainedModel] = [ Speech2TextEncoderPolicy, Speech2TextDecoderPolicy, ] with suppress(Exception):", "MegatronBertPolicy, ] def get_policy(self, model: nn.Module) -> Union[List[Policy], None]: \"\"\"", "self.builtin_policies[DPRPretrainedContextEncoder] = [ BertPolicy, ] with suppress(Exception): from transformers.models.lxmert.modeling_lxmert import", "from transformers.models.dpr.modeling_dpr import ( DPRPretrainedContextEncoder, DPRPretrainedQuestionEncoder, DPRPretrainedReader, ) self.builtin_policies[DPRPretrainedReader] =", "] with suppress(Exception): from transformers.models.electra.modeling_electra import ( ElectraPreTrainedModel, ) from", "with suppress(Exception): from transformers.models.pegasus.modeling_pegasus import ( PegasusPreTrainedModel, ) from parallelformers.policies.pegasus", "( BartPretrainedModel, ) from parallelformers.policies.bart import ( BartDecoderPolicy, BartEncoderPolicy, )", "from parallelformers.policies.fsmt import ( FSMTDecoderPolicy, FSMTEncoderPolicy, ) self.builtin_policies[PretrainedFSMTModel] = [", "parallelformers.policies.m2m_100 import ( M2M100DecoderPolicy, M2M100EncoderPolicy, ) self.builtin_policies[M2M100PreTrainedModel] = [ M2M100EncoderPolicy,", ") from parallelformers.policies.bart import ( BartDecoderPolicy, BartEncoderPolicy, ) self.builtin_policies[BartPretrainedModel] =", "M2M100DecoderPolicy, ] with suppress(Exception): from transformers.models.marian.modeling_marian import ( MarianPreTrainedModel, )", "with suppress(Exception): from transformers.models.led.modeling_led import LEDPreTrainedModel from parallelformers.policies.led import (", "( LEDDecoderPolicy, LEDEncoderPolicy, ) self.builtin_policies[LEDPreTrainedModel] = [ LEDEncoderPolicy, LEDDecoderPolicy, ]", "transformers.models.blenderbot.modeling_blenderbot import ( BlenderbotPreTrainedModel, ) from parallelformers.policies.blenderbot import ( BlenderbotDecoderPolicy,", "parallelformers.policies.openai import OpenAIGPTPolicy self.builtin_policies[OpenAIGPTPreTrainedModel] = [ OpenAIGPTPolicy, ] with suppress(Exception):", ") from parallelformers.policies.electra import ElectraPolicy self.builtin_policies[ElectraPreTrainedModel] = [ ElectraPolicy, ]", "transformers.models.luke.modeling_luke import ( LukePreTrainedModel, ) from parallelformers.policies.luke import LukePolicy self.builtin_policies[LukePreTrainedModel]", "import MobileBertPolicy self.builtin_policies[MobileBertPreTrainedModel] = [ MobileBertPolicy, ] with suppress(Exception): from", "parallelformers.policies.hubert import HubertPolicy self.builtin_policies[HubertPreTrainedModel] = [ HubertPolicy, ] with suppress(Exception):", "from transformers.models.gpt_neo.modeling_gpt_neo import ( GPTNeoPreTrainedModel, ) from parallelformers.policies.gpt_neo import GPTNeoPolicy", "model Args: model (nn.Module): model to parallelize Returns: Union[List[Policy], None]:", "] with suppress(Exception): from transformers.models.layoutlm.modeling_layoutlm import ( LayoutLMPreTrainedModel, ) from", "GPTNeoPreTrainedModel, ) from parallelformers.policies.gpt_neo import GPTNeoPolicy self.builtin_policies[GPTNeoPreTrainedModel] = [ GPTNeoPolicy,", "( CLIPPreTrainedModel, ) from parallelformers.policies.clip import ( CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy,", "[ BertPolicy, ] self.builtin_policies[DPRPretrainedQuestionEncoder] = [ BertPolicy, ] self.builtin_policies[DPRPretrainedContextEncoder] =", "transformers.models.roberta.modeling_roberta import ( RobertaPreTrainedModel, ) from parallelformers.policies.roberta import RobertaPolicy self.builtin_policies[RobertaPreTrainedModel]", "] with suppress(Exception): from transformers.models.convbert.modeling_convbert import ( ConvBertPreTrainedModel, ) from", "CLIPTextPolicy, CLIPVisionPolicy, ) self.builtin_policies[CLIPPreTrainedModel] = [ CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ]", "with suppress(Exception): from transformers.models.deit.modeling_deit import ( DeiTPreTrainedModel, ) from parallelformers.policies.deit", "from transformers.models.roformer.modeling_roformer import ( RoFormerPreTrainedModel, ) from parallelformers.policies.roformer import RoformerPolicy", "Speech2TextEncoderPolicy, Speech2TextDecoderPolicy, ] with suppress(Exception): from transformers.models.gptj.modeling_gptj import ( GPTJPreTrainedModel,", "with suppress(Exception): from transformers.models.bert.modeling_bert import ( BertPreTrainedModel, ) from parallelformers.policies.bert", "CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ] with suppress(Exception): from transformers.models.detr.modeling_detr import (", "parallelformers.policies.blenderbot import ( BlenderbotDecoderPolicy, BlenderbotEncoderPolicy, ) self.builtin_policies[BlenderbotPreTrainedModel] = [ BlenderbotEncoderPolicy,", "from parallelformers.policies.transfo_xl import TransfoXLPolicy self.builtin_policies[TransfoXLPreTrainedModel] = [ TransfoXLPolicy, ] with", "def __init__(self): self.builtin_policies = {} with suppress(Exception): from transformers.models.gpt_neo.modeling_gpt_neo import", "law or agreed to in writing, software # distributed under", "CTRLPolicy self.builtin_policies[CTRLPreTrainedModel] = [ CTRLPolicy, ] with suppress(Exception): from transformers.models.deberta_v2.modeling_deberta_v2", "finds automatically appropriate policies for the current model\"\"\" def __init__(self):", "parallelformers.policies.ibert import IBertPolicy self.builtin_policies[IBertPreTrainedModel] = [ IBertPolicy, ] with suppress(Exception):", "parallelformers.policies.visual_bert import VisualBertPolicy self.builtin_policies[VisualBertPreTrainedModel] = [ VisualBertPolicy, ] with suppress(Exception):", "] with suppress(Exception): from transformers.models.bigbird_pegasus.modeling_bigbird_pegasus import ( BigBirdPegasusPreTrainedModel, ) from", "with suppress(Exception): from transformers.models.mobilebert.modeling_mobilebert import ( MobileBertPreTrainedModel, ) from parallelformers.policies.mobilebert", "( RetriBertPreTrainedModel, ) self.builtin_policies[RetriBertPreTrainedModel] = [ BertPolicy, ] with suppress(Exception):", ") from parallelformers.policies.roformer import RoformerPolicy self.builtin_policies[RoFormerPreTrainedModel] = [ RoformerPolicy, ]", "self.builtin_policies = {} with suppress(Exception): from transformers.models.gpt_neo.modeling_gpt_neo import ( GPTNeoPreTrainedModel,", "import ( DeiTPreTrainedModel, ) from parallelformers.policies.deit import DeiTPolicy self.builtin_policies[DeiTPreTrainedModel] =", "suppress(Exception): from transformers.models.visual_bert.modeling_visual_bert import ( VisualBertPreTrainedModel, ) from parallelformers.policies.visual_bert import", "] with suppress(Exception): from transformers.models.fsmt.modeling_fsmt import ( PretrainedFSMTModel, ) from", "from transformers.models.convbert.modeling_convbert import ( ConvBertPreTrainedModel, ) from parallelformers.policies.convbert import ConvBertPolicy", "from parallelformers.policies.funnel import FunnelPolicy self.builtin_policies[FunnelPreTrainedModel] = [ FunnelPolicy, ] with", "from parallelformers.policies.deberta_v2 import DebertaV2Policy self.builtin_policies[DebertaV2PreTrainedModel] = [ DebertaV2Policy, ] with", "import ( BigBirdPreTrainedModel, ) from parallelformers.policies.bigbird import BigBirdPolicy self.builtin_policies[BigBirdPreTrainedModel] =", "suppress(Exception): from transformers.models.blenderbot_small.modeling_blenderbot_small import ( BlenderbotSmallPreTrainedModel, ) from parallelformers.policies.blenderbot_small import", "( MPNetEncoderPolicy, MPNetLayerPolicy, ) self.builtin_policies[MPNetPreTrainedModel] = [ MPNetEncoderPolicy, MPNetLayerPolicy, ]", "for k, v in self.available().items(): if isinstance(model, k): return v", "BartEncoderPolicy, ) self.builtin_policies[BartPretrainedModel] = [ BartEncoderPolicy, BartDecoderPolicy, ] with suppress(Exception):", "with suppress(Exception): from transformers.models.marian.modeling_marian import ( MarianPreTrainedModel, ) from parallelformers.policies.marian", "[DeiTPolicy] with suppress(Exception): from transformers.models.mbart.modeling_mbart import ( MBartPreTrainedModel, ) from", "import T5PreTrainedModel from parallelformers.policies.t5 import T5Policy self.builtin_policies[T5PreTrainedModel] = [ T5Policy,", "with suppress(Exception): from transformers.models.lxmert.modeling_lxmert import ( LxmertPreTrainedModel, ) from parallelformers.policies.lxmert", "ConvBertPolicy self.builtin_policies[ConvBertPreTrainedModel] = [ ConvBertPolicy, ] with suppress(Exception): from transformers.models.bert_generation.modeling_bert_generation", "BlenderbotDecoderPolicy, BlenderbotEncoderPolicy, ) self.builtin_policies[BlenderbotPreTrainedModel] = [ BlenderbotEncoderPolicy, BlenderbotDecoderPolicy, ] with", "with suppress(Exception): from transformers.models.longformer.modeling_longformer import ( LongformerPreTrainedModel, ) from parallelformers.policies.longformer", "self.builtin_policies[IBertPreTrainedModel] = [ IBertPolicy, ] with suppress(Exception): from transformers.models.tapas.modeling_tapas import", "M2M100DecoderPolicy, M2M100EncoderPolicy, ) self.builtin_policies[M2M100PreTrainedModel] = [ M2M100EncoderPolicy, M2M100DecoderPolicy, ] with", "self.builtin_policies[LxmertPreTrainedModel] = [ LxmertPolicy, ] with suppress(Exception): from transformers.models.hubert.modeling_hubert import", "may obtain a copy of the License at # #", "parallelformers.policies.prophetnet import ( ProphetNetDecoderPolicy, ProphetNetEncoderPolicy, ) self.builtin_policies[ProphetNetPreTrainedModel] = [ ProphetNetEncoderPolicy,", "[ ProphetNetEncoderPolicy, ProphetNetDecoderPolicy, ] with suppress(Exception): from transformers.models.visual_bert.modeling_visual_bert import (", "with suppress(Exception): from transformers.models.transfo_xl.modeling_transfo_xl import ( TransfoXLPreTrainedModel, ) from parallelformers.policies.transfo_xl", "] with suppress(Exception): from transformers.models.lxmert.modeling_lxmert import ( LxmertPreTrainedModel, ) from", "from transformers.models.gpt2.modeling_gpt2 import ( GPT2PreTrainedModel, ) from parallelformers.policies.gpt2 import GPT2Policy", "from transformers.models.t5.modeling_t5 import T5PreTrainedModel from parallelformers.policies.t5 import T5Policy self.builtin_policies[T5PreTrainedModel] =", "parallelformers.policies.vit import ViTPolicy self.builtin_policies[ViTPreTrainedModel] = [ ViTPolicy, ] with suppress(Exception):", "with suppress(Exception): from transformers.models.gpt2.modeling_gpt2 import ( GPT2PreTrainedModel, ) from parallelformers.policies.gpt2", "BertPolicy, ] with suppress(Exception): from transformers.models.big_bird.modeling_big_bird import ( BigBirdPreTrainedModel, )", "import ( BigBirdPegasusDecoderPolicy, BigBirdPegasusEncoderPolicy, ) self.builtin_policies[BigBirdPegasusPreTrainedModel] = [ BigBirdPegasusEncoderPolicy, BigBirdPegasusDecoderPolicy,", "BertPolicy self.builtin_policies[BertPreTrainedModel] = [ BertPolicy, ] with suppress(Exception): from transformers.models.bart.modeling_bart", "PegasusPreTrainedModel, ) from parallelformers.policies.pegasus import ( PegasusDecoderPolicy, PegasusEncoderPolicy, ) self.builtin_policies[PegasusPreTrainedModel]", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "LukePreTrainedModel, ) from parallelformers.policies.luke import LukePolicy self.builtin_policies[LukePreTrainedModel] = [ LukePolicy,", "suppress(Exception): from transformers.models.retribert.modeling_retribert import ( RetriBertPreTrainedModel, ) self.builtin_policies[RetriBertPreTrainedModel] = [", "parallelformers.policies.mbart import ( MBartDecoderPolicy, MBartEncoderPolicy, ) self.builtin_policies[MBartPreTrainedModel] = [ MBartEncoderPolicy,", "IBertPolicy, ] with suppress(Exception): from transformers.models.tapas.modeling_tapas import ( TapasPreTrainedModel, )", "suppress(Exception): from transformers.models.bigbird_pegasus.modeling_bigbird_pegasus import ( BigBirdPegasusPreTrainedModel, ) from parallelformers.policies.bigbird_pegasus import", "self.builtin_policies[MobileBertPreTrainedModel] = [ MobileBertPolicy, ] with suppress(Exception): from transformers.models.mpnet.modeling_mpnet import", "import ( ReformerPreTrainedModel, ) from parallelformers.policies.reformer import ReformerPolicy self.builtin_policies[ReformerPreTrainedModel] =", "from transformers.models.tapas.modeling_tapas import ( TapasPreTrainedModel, ) from parallelformers.policies.tapas import TapasPolicy", "[ BigBirdPegasusEncoderPolicy, BigBirdPegasusDecoderPolicy, ] with suppress(Exception): from transformers.models.vit.modeling_vit import ViTPreTrainedModel", "= [ BlenderbotEncoderPolicy, BlenderbotDecoderPolicy, ] with suppress(Exception): from transformers.models.deberta.modeling_deberta import", "transformers.models.xlm.modeling_xlm import XLMPreTrainedModel from parallelformers.policies.xlm import ( XLMAttentionPolicy, XLMMLPPolicy, )", "transformers.models.ibert.modeling_ibert import ( IBertPreTrainedModel, ) from parallelformers.policies.ibert import IBertPolicy self.builtin_policies[IBertPreTrainedModel]", "import ( MarianPreTrainedModel, ) from parallelformers.policies.marian import ( MarianDecoderPolicy, MarianEncoderPolicy,", "may not use this file except in compliance with the", "import ( MBartPreTrainedModel, ) from parallelformers.policies.mbart import ( MBartDecoderPolicy, MBartEncoderPolicy,", "import ( LayoutLMPreTrainedModel, ) from parallelformers.policies.layoutlm import LayoutLMPolicy self.builtin_policies[LayoutLMPreTrainedModel] =", "transformers.models.led.modeling_led import LEDPreTrainedModel from parallelformers.policies.led import ( LEDDecoderPolicy, LEDEncoderPolicy, )", "] with suppress(Exception): from transformers.models.dpr.modeling_dpr import ( DPRPretrainedContextEncoder, DPRPretrainedQuestionEncoder, DPRPretrainedReader,", "\"\"\" for k, v in self.available().items(): if isinstance(model, k): return", "# Copyright 2021 TUNiB inc. # # Licensed under the", "MPNetLayerPolicy, ] with suppress(Exception): from transformers.models.luke.modeling_luke import ( LukePreTrainedModel, )", "return None def available(self): \"\"\"Dictionary of available models and policies\"\"\"", "the current model\"\"\" def __init__(self): self.builtin_policies = {} with suppress(Exception):", "governing permissions and # limitations under the License. from contextlib", "CTRLPreTrainedModel, ) from parallelformers.policies.ctrl import CTRLPolicy self.builtin_policies[CTRLPreTrainedModel] = [ CTRLPolicy,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "self.builtin_policies[DPRPretrainedReader] = [ BertPolicy, ] self.builtin_policies[DPRPretrainedQuestionEncoder] = [ BertPolicy, ]", "from parallelformers.policies.visual_bert import VisualBertPolicy self.builtin_policies[VisualBertPreTrainedModel] = [ VisualBertPolicy, ] with", "( MBartDecoderPolicy, MBartEncoderPolicy, ) self.builtin_policies[MBartPreTrainedModel] = [ MBartEncoderPolicy, MBartDecoderPolicy, ]", "XLNetPolicy self.builtin_policies[XLNetPreTrainedModel] = [ XLNetPolicy, ] with suppress(Exception): from transformers.models.retribert.modeling_retribert", "this file except in compliance with the License. # You", "with suppress(Exception): from transformers.models.gpt_neo.modeling_gpt_neo import ( GPTNeoPreTrainedModel, ) from parallelformers.policies.gpt_neo", "self.builtin_policies[BlenderbotSmallPreTrainedModel] = [ BlenderbotSmallEncoderPolicy, BlenderbotSmallDecoderPolicy, ] with suppress(Exception): from transformers.models.distilbert.modeling_distilbert", "the current model Args: model (nn.Module): model to parallelize Returns:", "parallelformers.policies.deberta import DebertaPolicy self.builtin_policies[DebertaPreTrainedModel] = [ DebertaPolicy, ] with suppress(Exception):", "License. from contextlib import suppress from typing import List, Union", "import ( MarianDecoderPolicy, MarianEncoderPolicy, ) self.builtin_policies[MarianPreTrainedModel] = [ MarianEncoderPolicy, MarianDecoderPolicy,", "TransfoXLPolicy self.builtin_policies[TransfoXLPreTrainedModel] = [ TransfoXLPolicy, ] with suppress(Exception): from transformers.models.roberta.modeling_roberta", "from transformers.models.luke.modeling_luke import ( LukePreTrainedModel, ) from parallelformers.policies.luke import LukePolicy", "] with suppress(Exception): from transformers.models.luke.modeling_luke import ( LukePreTrainedModel, ) from", ") from parallelformers.policies.distil_bert import DistilBertPolicy self.builtin_policies[DistilBertPreTrainedModel] = [ DistilBertPolicy, ]", "ProphetNetEncoderPolicy, ) self.builtin_policies[ProphetNetPreTrainedModel] = [ ProphetNetEncoderPolicy, ProphetNetDecoderPolicy, ] with suppress(Exception):", "transformers.models.bert_generation.modeling_bert_generation import ( BertGenerationPreTrainedModel, ) from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertGenerationPreTrainedModel]", "from parallelformers.policies.deit import DeiTPolicy self.builtin_policies[DeiTPreTrainedModel] = [DeiTPolicy] with suppress(Exception): from", "] with suppress(Exception): from transformers.models.ibert.modeling_ibert import ( IBertPreTrainedModel, ) from", "from parallelformers.policies.ctrl import CTRLPolicy self.builtin_policies[CTRLPreTrainedModel] = [ CTRLPolicy, ] with", "import BertPolicy self.builtin_policies[BertPreTrainedModel] = [ BertPolicy, ] with suppress(Exception): from", "[ TransfoXLPolicy, ] with suppress(Exception): from transformers.models.roberta.modeling_roberta import ( RobertaPreTrainedModel,", "( ProphetNetDecoderPolicy, ProphetNetEncoderPolicy, ) self.builtin_policies[ProphetNetPreTrainedModel] = [ ProphetNetEncoderPolicy, ProphetNetDecoderPolicy, ]", "self.builtin_policies[PegasusPreTrainedModel] = [ PegasusEncoderPolicy, PegasusDecoderPolicy, ] with suppress(Exception): from transformers.models.fsmt.modeling_fsmt", "LayoutLMPreTrainedModel, ) from parallelformers.policies.layoutlm import LayoutLMPolicy self.builtin_policies[LayoutLMPreTrainedModel] = [ LayoutLMPolicy,", "with suppress(Exception): from transformers.models.reformer.modeling_reformer import ( ReformerPreTrainedModel, ) from parallelformers.policies.reformer", "parallelformers.policies.base import Policy class AutoPolicy: \"\"\"Class for finds automatically appropriate", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "appropriate policies or none \"\"\" for k, v in self.available().items():", "# limitations under the License. from contextlib import suppress from", "# # Licensed under the Apache License, Version 2.0 (the", "with suppress(Exception): from transformers.models.bigbird_pegasus.modeling_bigbird_pegasus import ( BigBirdPegasusPreTrainedModel, ) from parallelformers.policies.bigbird_pegasus", "= [ LayoutLMPolicy, ] with suppress(Exception): from transformers.models.led.modeling_led import LEDPreTrainedModel", "TransfoXLPolicy, ] with suppress(Exception): from transformers.models.roberta.modeling_roberta import ( RobertaPreTrainedModel, )", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "and # limitations under the License. from contextlib import suppress", "from transformers.models.pegasus.modeling_pegasus import ( PegasusPreTrainedModel, ) from parallelformers.policies.pegasus import (", "= [ BertPolicy, ] self.builtin_policies[DPRPretrainedContextEncoder] = [ BertPolicy, ] with", "current model\"\"\" def __init__(self): self.builtin_policies = {} with suppress(Exception): from", "self.builtin_policies[BartPretrainedModel] = [ BartEncoderPolicy, BartDecoderPolicy, ] with suppress(Exception): from transformers.models.blenderbot.modeling_blenderbot", ") from parallelformers.policies.gpt_neo import GPTNeoPolicy self.builtin_policies[GPTNeoPreTrainedModel] = [ GPTNeoPolicy, ]", "MPNetLayerPolicy, ) self.builtin_policies[MPNetPreTrainedModel] = [ MPNetEncoderPolicy, MPNetLayerPolicy, ] with suppress(Exception):", "BlenderbotEncoderPolicy, BlenderbotDecoderPolicy, ] with suppress(Exception): from transformers.models.deberta.modeling_deberta import ( DebertaPreTrainedModel,", "GPT2Policy self.builtin_policies[GPT2PreTrainedModel] = [ GPT2Policy, ] with suppress(Exception): from transformers.models.ctrl.modeling_ctrl", ") from parallelformers.policies.deberta import DebertaPolicy self.builtin_policies[DebertaPreTrainedModel] = [ DebertaPolicy, ]", "parallelformers.policies.wav2vec import Wav2VecPolicy self.builtin_policies[Wav2Vec2PreTrainedModel] = [ Wav2VecPolicy, ] with suppress(Exception):", "( XLNetPreTrainedModel, ) from parallelformers.policies.xlnet import XLNetPolicy self.builtin_policies[XLNetPreTrainedModel] = [", "with suppress(Exception): from transformers.models.bert_generation.modeling_bert_generation import ( BertGenerationPreTrainedModel, ) from parallelformers.policies.bert", "DebertaV2Policy, ] with suppress(Exception): from transformers.models.openai.modeling_openai import ( OpenAIGPTPreTrainedModel, )", "( BigBirdPegasusDecoderPolicy, BigBirdPegasusEncoderPolicy, ) self.builtin_policies[BigBirdPegasusPreTrainedModel] = [ BigBirdPegasusEncoderPolicy, BigBirdPegasusDecoderPolicy, ]", "<filename>parallelformers/policies/base/auto.py # Copyright 2021 TUNiB inc. # # Licensed under", "with suppress(Exception): from transformers.models.wav2vec2.modeling_wav2vec2 import ( Wav2Vec2PreTrainedModel, ) from parallelformers.policies.wav2vec", "ProphetNetDecoderPolicy, ] with suppress(Exception): from transformers.models.visual_bert.modeling_visual_bert import ( VisualBertPreTrainedModel, )", "suppress(Exception): from transformers.models.clip.modeling_clip import ( CLIPPreTrainedModel, ) from parallelformers.policies.clip import", "[ HubertPolicy, ] with suppress(Exception): from transformers.models.wav2vec2.modeling_wav2vec2 import ( Wav2Vec2PreTrainedModel,", "( MPNetPreTrainedModel, ) from parallelformers.policies.mpnet import ( MPNetEncoderPolicy, MPNetLayerPolicy, )", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", ") from parallelformers.policies.clip import ( CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ) self.builtin_policies[CLIPPreTrainedModel]", "in self.available().items(): if isinstance(model, k): return v return None def", "suppress(Exception): from transformers.models.lxmert.modeling_lxmert import ( LxmertPreTrainedModel, ) from parallelformers.policies.lxmert import", "suppress(Exception): from transformers.models.speech_to_text.modeling_speech_to_text import ( Speech2TextPreTrainedModel, ) from parallelformers.policies.speech_to_text import", "] with suppress(Exception): from transformers.models.mpnet.modeling_mpnet import ( MPNetPreTrainedModel, ) from", "with suppress(Exception): from transformers.models.xlm.modeling_xlm import XLMPreTrainedModel from parallelformers.policies.xlm import (", "= [ GPTNeoPolicy, ] with suppress(Exception): from transformers.models.bert.modeling_bert import (", "MegatronBertPreTrainedModel, ) from parallelformers.policies.megtron_bert import ( MegatronBertPolicy, ) self.builtin_policies[MegatronBertPreTrainedModel] =", "from transformers.models.mobilebert.modeling_mobilebert import ( MobileBertPreTrainedModel, ) from parallelformers.policies.mobilebert import MobileBertPolicy", "parallelformers.policies.deberta_v2 import DebertaV2Policy self.builtin_policies[DebertaV2PreTrainedModel] = [ DebertaV2Policy, ] with suppress(Exception):", ") from parallelformers.policies.wav2vec import Wav2VecPolicy self.builtin_policies[Wav2Vec2PreTrainedModel] = [ Wav2VecPolicy, ]", "import ( RetriBertPreTrainedModel, ) self.builtin_policies[RetriBertPreTrainedModel] = [ BertPolicy, ] with", "import ( TapasPreTrainedModel, ) from parallelformers.policies.tapas import TapasPolicy self.builtin_policies[TapasPreTrainedModel] =", "T5Policy, ] with suppress(Exception): from transformers.models.pegasus.modeling_pegasus import ( PegasusPreTrainedModel, )", "= [ DistilBertPolicy, ] with suppress(Exception): from transformers.models.convbert.modeling_convbert import (", "Copyright 2021 TUNiB inc. # # Licensed under the Apache", "self.builtin_policies[XLNetPreTrainedModel] = [ XLNetPolicy, ] with suppress(Exception): from transformers.models.retribert.modeling_retribert import", "transformers.models.detr.modeling_detr import ( DetrPreTrainedModel, ) from parallelformers.policies.detr import ( DetrDecoderPolicy,", "GPTJPolicy self.builtin_policies[GPTJPreTrainedModel] = [ GPTJPolicy, ] with suppress(Exception): from transformers.models.megatron_bert", "suppress(Exception): from transformers.models.prophetnet.modeling_prophetnet import ( ProphetNetPreTrainedModel, ) from parallelformers.policies.prophetnet import", "import ( RoFormerPreTrainedModel, ) from parallelformers.policies.roformer import RoformerPolicy self.builtin_policies[RoFormerPreTrainedModel] =", "= [ LEDEncoderPolicy, LEDDecoderPolicy, ] with suppress(Exception): from transformers.models.prophetnet.modeling_prophetnet import", "BertPolicy, ] self.builtin_policies[DPRPretrainedQuestionEncoder] = [ BertPolicy, ] self.builtin_policies[DPRPretrainedContextEncoder] = [", "with suppress(Exception): from transformers.models.deberta.modeling_deberta import ( DebertaPreTrainedModel, ) from parallelformers.policies.deberta", "from transformers.models.deberta.modeling_deberta import ( DebertaPreTrainedModel, ) from parallelformers.policies.deberta import DebertaPolicy", ") from parallelformers.policies.roberta import RobertaPolicy self.builtin_policies[RobertaPreTrainedModel] = [ RobertaPolicy, ]", ") from parallelformers.policies.mbart import ( MBartDecoderPolicy, MBartEncoderPolicy, ) self.builtin_policies[MBartPreTrainedModel] =", "DetrEncoderPolicy, ) self.builtin_policies[DetrPreTrainedModel] = [ DetrEncoderPolicy, DetrDecoderPolicy, ] with suppress(Exception):", "if isinstance(model, k): return v return None def available(self): \"\"\"Dictionary", "BertPolicy, ] with suppress(Exception): from transformers.models.bart.modeling_bart import ( BartPretrainedModel, )", "parallelformers.policies.blenderbot_small import ( BlenderbotSmallDecoderPolicy, BlenderbotSmallEncoderPolicy, ) self.builtin_policies[BlenderbotSmallPreTrainedModel] = [ BlenderbotSmallEncoderPolicy,", "M2M100PreTrainedModel, ) from parallelformers.policies.m2m_100 import ( M2M100DecoderPolicy, M2M100EncoderPolicy, ) self.builtin_policies[M2M100PreTrainedModel]", "return v return None def available(self): \"\"\"Dictionary of available models", "] with suppress(Exception): from transformers.models.tapas.modeling_tapas import ( TapasPreTrainedModel, ) from", "Union[List[Policy], None]: appropriate policies or none \"\"\" for k, v", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", ") from parallelformers.policies.openai import OpenAIGPTPolicy self.builtin_policies[OpenAIGPTPreTrainedModel] = [ OpenAIGPTPolicy, ]", "BigBirdPolicy self.builtin_policies[BigBirdPreTrainedModel] = [ BigBirdPolicy, ] with suppress(Exception): from transformers.models.bigbird_pegasus.modeling_bigbird_pegasus", "suppress(Exception): from transformers.models.transfo_xl.modeling_transfo_xl import ( TransfoXLPreTrainedModel, ) from parallelformers.policies.transfo_xl import", "from transformers.models.roberta.modeling_roberta import ( RobertaPreTrainedModel, ) from parallelformers.policies.roberta import RobertaPolicy", "] with suppress(Exception): from transformers.models.megatron_bert import ( MegatronBertPreTrainedModel, ) from", ") from parallelformers.policies.gptj import GPTJPolicy self.builtin_policies[GPTJPreTrainedModel] = [ GPTJPolicy, ]", "Union from torch import nn from parallelformers.policies.base import Policy class", "transformers.models.deberta_v2.modeling_deberta_v2 import ( DebertaV2PreTrainedModel, ) from parallelformers.policies.deberta_v2 import DebertaV2Policy self.builtin_policies[DebertaV2PreTrainedModel]", "DebertaPreTrainedModel, ) from parallelformers.policies.deberta import DebertaPolicy self.builtin_policies[DebertaPreTrainedModel] = [ DebertaPolicy,", "import nn from parallelformers.policies.base import Policy class AutoPolicy: \"\"\"Class for", "or implied. # See the License for the specific language", "= [ T5Policy, ] with suppress(Exception): from transformers.models.pegasus.modeling_pegasus import (", "LukePolicy self.builtin_policies[LukePreTrainedModel] = [ LukePolicy, ] with suppress(Exception): from transformers.models.dpr.modeling_dpr", "from parallelformers.policies.lxmert import LxmertPolicy self.builtin_policies[LxmertPreTrainedModel] = [ LxmertPolicy, ] with", "with suppress(Exception): from transformers.models.luke.modeling_luke import ( LukePreTrainedModel, ) from parallelformers.policies.luke", "from transformers.models.led.modeling_led import LEDPreTrainedModel from parallelformers.policies.led import ( LEDDecoderPolicy, LEDEncoderPolicy,", "] with suppress(Exception): from transformers.models.bert_generation.modeling_bert_generation import ( BertGenerationPreTrainedModel, ) from", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "permissions and # limitations under the License. from contextlib import", "self.builtin_policies[BertPreTrainedModel] = [ BertPolicy, ] with suppress(Exception): from transformers.models.bart.modeling_bart import", "parallelformers.policies.distil_bert import DistilBertPolicy self.builtin_policies[DistilBertPreTrainedModel] = [ DistilBertPolicy, ] with suppress(Exception):", "from parallelformers.policies.bigbird import BigBirdPolicy self.builtin_policies[BigBirdPreTrainedModel] = [ BigBirdPolicy, ] with", "] with suppress(Exception): from transformers.models.speech_to_text.modeling_speech_to_text import ( Speech2TextPreTrainedModel, ) from", "torch import nn from parallelformers.policies.base import Policy class AutoPolicy: \"\"\"Class", "from transformers.models.bert.modeling_bert import ( BertPreTrainedModel, ) from parallelformers.policies.bert import BertPolicy", "from parallelformers.policies.xlm import ( XLMAttentionPolicy, XLMMLPPolicy, ) self.builtin_policies[XLMPreTrainedModel] = [", "self.builtin_policies[BigBirdPegasusPreTrainedModel] = [ BigBirdPegasusEncoderPolicy, BigBirdPegasusDecoderPolicy, ] with suppress(Exception): from transformers.models.vit.modeling_vit", "[ XLNetPolicy, ] with suppress(Exception): from transformers.models.retribert.modeling_retribert import ( RetriBertPreTrainedModel,", "LongformerPreTrainedModel, ) from parallelformers.policies.longformer import LongformerPolicy self.builtin_policies[LongformerPreTrainedModel] = [ LongformerPolicy,", "= [ ConvBertPolicy, ] with suppress(Exception): from transformers.models.bert_generation.modeling_bert_generation import (", "self.builtin_policies[MBartPreTrainedModel] = [ MBartEncoderPolicy, MBartDecoderPolicy, ] with suppress(Exception): from transformers.models.t5.modeling_t5", "transformers.models.lxmert.modeling_lxmert import ( LxmertPreTrainedModel, ) from parallelformers.policies.lxmert import LxmertPolicy self.builtin_policies[LxmertPreTrainedModel]", "( VisualBertPreTrainedModel, ) from parallelformers.policies.visual_bert import VisualBertPolicy self.builtin_policies[VisualBertPreTrainedModel] = [", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "import IBertPolicy self.builtin_policies[IBertPreTrainedModel] = [ IBertPolicy, ] with suppress(Exception): from", ") from parallelformers.policies.visual_bert import VisualBertPolicy self.builtin_policies[VisualBertPreTrainedModel] = [ VisualBertPolicy, ]", "HubertPolicy self.builtin_policies[HubertPreTrainedModel] = [ HubertPolicy, ] with suppress(Exception): from transformers.models.wav2vec2.modeling_wav2vec2", "typing import List, Union from torch import nn from parallelformers.policies.base", "{} with suppress(Exception): from transformers.models.gpt_neo.modeling_gpt_neo import ( GPTNeoPreTrainedModel, ) from", ") from parallelformers.policies.fsmt import ( FSMTDecoderPolicy, FSMTEncoderPolicy, ) self.builtin_policies[PretrainedFSMTModel] =", "from parallelformers.policies.megtron_bert import ( MegatronBertPolicy, ) self.builtin_policies[MegatronBertPreTrainedModel] = [ MegatronBertPolicy,", "CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ) self.builtin_policies[CLIPPreTrainedModel] = [ CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy,", "[ CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ] with suppress(Exception): from transformers.models.detr.modeling_detr import", "= [ ProphetNetEncoderPolicy, ProphetNetDecoderPolicy, ] with suppress(Exception): from transformers.models.visual_bert.modeling_visual_bert import", "from torch import nn from parallelformers.policies.base import Policy class AutoPolicy:", "import ( BlenderbotDecoderPolicy, BlenderbotEncoderPolicy, ) self.builtin_policies[BlenderbotPreTrainedModel] = [ BlenderbotEncoderPolicy, BlenderbotDecoderPolicy,", "from transformers.models.big_bird.modeling_big_bird import ( BigBirdPreTrainedModel, ) from parallelformers.policies.bigbird import BigBirdPolicy", "import LxmertPolicy self.builtin_policies[LxmertPreTrainedModel] = [ LxmertPolicy, ] with suppress(Exception): from", "BigBirdPegasusDecoderPolicy, BigBirdPegasusEncoderPolicy, ) self.builtin_policies[BigBirdPegasusPreTrainedModel] = [ BigBirdPegasusEncoderPolicy, BigBirdPegasusDecoderPolicy, ] with", "def get_policy(self, model: nn.Module) -> Union[List[Policy], None]: \"\"\" Find appropriate", "model (nn.Module): model to parallelize Returns: Union[List[Policy], None]: appropriate policies", "CLIPPreTrainedModel, ) from parallelformers.policies.clip import ( CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, )", "( TransfoXLPreTrainedModel, ) from parallelformers.policies.transfo_xl import TransfoXLPolicy self.builtin_policies[TransfoXLPreTrainedModel] = [", "[ BartEncoderPolicy, BartDecoderPolicy, ] with suppress(Exception): from transformers.models.blenderbot.modeling_blenderbot import (", "with suppress(Exception): from transformers.models.blenderbot_small.modeling_blenderbot_small import ( BlenderbotSmallPreTrainedModel, ) from parallelformers.policies.blenderbot_small", "transformers.models.funnel.modeling_funnel import ( FunnelPreTrainedModel, ) from parallelformers.policies.funnel import FunnelPolicy self.builtin_policies[FunnelPreTrainedModel]", "[ IBertPolicy, ] with suppress(Exception): from transformers.models.tapas.modeling_tapas import ( TapasPreTrainedModel,", "(the \"License\"); # you may not use this file except", "[ BlenderbotSmallEncoderPolicy, BlenderbotSmallDecoderPolicy, ] with suppress(Exception): from transformers.models.distilbert.modeling_distilbert import (", "# you may not use this file except in compliance", "DistilBertPolicy self.builtin_policies[DistilBertPreTrainedModel] = [ DistilBertPolicy, ] with suppress(Exception): from transformers.models.convbert.modeling_convbert", "= [ BertPolicy, ] with suppress(Exception): from transformers.models.lxmert.modeling_lxmert import (", "self.builtin_policies[MPNetPreTrainedModel] = [ MPNetEncoderPolicy, MPNetLayerPolicy, ] with suppress(Exception): from transformers.models.luke.modeling_luke", "self.builtin_policies[Speech2TextPreTrainedModel] = [ Speech2TextEncoderPolicy, Speech2TextDecoderPolicy, ] with suppress(Exception): from transformers.models.gptj.modeling_gptj", "import ConvBertPolicy self.builtin_policies[ConvBertPreTrainedModel] = [ ConvBertPolicy, ] with suppress(Exception): from", "BlenderbotDecoderPolicy, ] with suppress(Exception): from transformers.models.deberta.modeling_deberta import ( DebertaPreTrainedModel, )", "import DebertaPolicy self.builtin_policies[DebertaPreTrainedModel] = [ DebertaPolicy, ] with suppress(Exception): from", "( LongformerPreTrainedModel, ) from parallelformers.policies.longformer import LongformerPolicy self.builtin_policies[LongformerPreTrainedModel] = [", "from transformers.models.vit.modeling_vit import ViTPreTrainedModel from parallelformers.policies.vit import ViTPolicy self.builtin_policies[ViTPreTrainedModel] =", "self.builtin_policies[VisualBertPreTrainedModel] = [ VisualBertPolicy, ] with suppress(Exception): from transformers.models.speech_to_text.modeling_speech_to_text import", "(nn.Module): model to parallelize Returns: Union[List[Policy], None]: appropriate policies or", "ElectraPolicy, ] with suppress(Exception): from transformers.models.blenderbot_small.modeling_blenderbot_small import ( BlenderbotSmallPreTrainedModel, )", "( TapasPreTrainedModel, ) from parallelformers.policies.tapas import TapasPolicy self.builtin_policies[TapasPreTrainedModel] = [", "import ( OpenAIGPTPreTrainedModel, ) from parallelformers.policies.openai import OpenAIGPTPolicy self.builtin_policies[OpenAIGPTPreTrainedModel] =", "[ ConvBertPolicy, ] with suppress(Exception): from transformers.models.bert_generation.modeling_bert_generation import ( BertGenerationPreTrainedModel,", "from transformers.models.ibert.modeling_ibert import ( IBertPreTrainedModel, ) from parallelformers.policies.ibert import IBertPolicy", "transformers.models.openai.modeling_openai import ( OpenAIGPTPreTrainedModel, ) from parallelformers.policies.openai import OpenAIGPTPolicy self.builtin_policies[OpenAIGPTPreTrainedModel]", "self.builtin_policies[LayoutLMPreTrainedModel] = [ LayoutLMPolicy, ] with suppress(Exception): from transformers.models.led.modeling_led import", "DetrEncoderPolicy, DetrDecoderPolicy, ] with suppress(Exception): from transformers.models.reformer.modeling_reformer import ( ReformerPreTrainedModel,", "transformers.models.xlnet.modeling_xlnet import ( XLNetPreTrainedModel, ) from parallelformers.policies.xlnet import XLNetPolicy self.builtin_policies[XLNetPreTrainedModel]", "import ( IBertPreTrainedModel, ) from parallelformers.policies.ibert import IBertPolicy self.builtin_policies[IBertPreTrainedModel] =", "transformers.models.bigbird_pegasus.modeling_bigbird_pegasus import ( BigBirdPegasusPreTrainedModel, ) from parallelformers.policies.bigbird_pegasus import ( BigBirdPegasusDecoderPolicy,", "FSMTEncoderPolicy, ) self.builtin_policies[PretrainedFSMTModel] = [ FSMTEncoderPolicy, FSMTDecoderPolicy, ] with suppress(Exception):", "( CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ) self.builtin_policies[CLIPPreTrainedModel] = [ CLIPLayerPolicy, CLIPTextPolicy,", "suppress(Exception): from transformers.models.roberta.modeling_roberta import ( RobertaPreTrainedModel, ) from parallelformers.policies.roberta import", "model to parallelize Returns: Union[List[Policy], None]: appropriate policies or none", "from transformers.models.ctrl.modeling_ctrl import ( CTRLPreTrainedModel, ) from parallelformers.policies.ctrl import CTRLPolicy", "] with suppress(Exception): from transformers.models.xlm.modeling_xlm import XLMPreTrainedModel from parallelformers.policies.xlm import", "[ RoformerPolicy, ] with suppress(Exception): from transformers.models.ibert.modeling_ibert import ( IBertPreTrainedModel,", "# # Unless required by applicable law or agreed to", "transformers.models.gptj.modeling_gptj import ( GPTJPreTrainedModel, ) from parallelformers.policies.gptj import GPTJPolicy self.builtin_policies[GPTJPreTrainedModel]", "( LayoutLMPreTrainedModel, ) from parallelformers.policies.layoutlm import LayoutLMPolicy self.builtin_policies[LayoutLMPreTrainedModel] = [", "= [ CTRLPolicy, ] with suppress(Exception): from transformers.models.deberta_v2.modeling_deberta_v2 import (", "ProphetNetEncoderPolicy, ProphetNetDecoderPolicy, ] with suppress(Exception): from transformers.models.visual_bert.modeling_visual_bert import ( VisualBertPreTrainedModel,", "transformers.models.pegasus.modeling_pegasus import ( PegasusPreTrainedModel, ) from parallelformers.policies.pegasus import ( PegasusDecoderPolicy,", "= [ DebertaV2Policy, ] with suppress(Exception): from transformers.models.openai.modeling_openai import (", "= [ MobileBertPolicy, ] with suppress(Exception): from transformers.models.mpnet.modeling_mpnet import (", "class AutoPolicy: \"\"\"Class for finds automatically appropriate policies for the", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "( DPRPretrainedContextEncoder, DPRPretrainedQuestionEncoder, DPRPretrainedReader, ) self.builtin_policies[DPRPretrainedReader] = [ BertPolicy, ]", "BigBirdPegasusEncoderPolicy, BigBirdPegasusDecoderPolicy, ] with suppress(Exception): from transformers.models.vit.modeling_vit import ViTPreTrainedModel from", "MPNetPreTrainedModel, ) from parallelformers.policies.mpnet import ( MPNetEncoderPolicy, MPNetLayerPolicy, ) self.builtin_policies[MPNetPreTrainedModel]", "BlenderbotEncoderPolicy, ) self.builtin_policies[BlenderbotPreTrainedModel] = [ BlenderbotEncoderPolicy, BlenderbotDecoderPolicy, ] with suppress(Exception):", "= [ BartEncoderPolicy, BartDecoderPolicy, ] with suppress(Exception): from transformers.models.blenderbot.modeling_blenderbot import", "( GPTJPreTrainedModel, ) from parallelformers.policies.gptj import GPTJPolicy self.builtin_policies[GPTJPreTrainedModel] = [", "Version 2.0 (the \"License\"); # you may not use this", "from parallelformers.policies.pegasus import ( PegasusDecoderPolicy, PegasusEncoderPolicy, ) self.builtin_policies[PegasusPreTrainedModel] = [", ") from parallelformers.policies.lxmert import LxmertPolicy self.builtin_policies[LxmertPreTrainedModel] = [ LxmertPolicy, ]", "from parallelformers.policies.speech_to_text import ( Speech2TextDecoderPolicy, Speech2TextEncoderPolicy, ) self.builtin_policies[Speech2TextPreTrainedModel] = [", "( FSMTDecoderPolicy, FSMTEncoderPolicy, ) self.builtin_policies[PretrainedFSMTModel] = [ FSMTEncoderPolicy, FSMTDecoderPolicy, ]", "( OpenAIGPTPreTrainedModel, ) from parallelformers.policies.openai import OpenAIGPTPolicy self.builtin_policies[OpenAIGPTPreTrainedModel] = [", "OpenAIGPTPolicy, ] with suppress(Exception): from transformers.models.electra.modeling_electra import ( ElectraPreTrainedModel, )", "TransfoXLPreTrainedModel, ) from parallelformers.policies.transfo_xl import TransfoXLPolicy self.builtin_policies[TransfoXLPreTrainedModel] = [ TransfoXLPolicy,", ") from parallelformers.policies.ctrl import CTRLPolicy self.builtin_policies[CTRLPreTrainedModel] = [ CTRLPolicy, ]", "BlenderbotSmallEncoderPolicy, BlenderbotSmallDecoderPolicy, ] with suppress(Exception): from transformers.models.distilbert.modeling_distilbert import ( DistilBertPreTrainedModel,", "v return None def available(self): \"\"\"Dictionary of available models and", ") from parallelformers.policies.funnel import FunnelPolicy self.builtin_policies[FunnelPreTrainedModel] = [ FunnelPolicy, ]", "suppress(Exception): from transformers.models.fsmt.modeling_fsmt import ( PretrainedFSMTModel, ) from parallelformers.policies.fsmt import", "suppress(Exception): from transformers.models.marian.modeling_marian import ( MarianPreTrainedModel, ) from parallelformers.policies.marian import", "( Speech2TextPreTrainedModel, ) from parallelformers.policies.speech_to_text import ( Speech2TextDecoderPolicy, Speech2TextEncoderPolicy, )", "RoformerPolicy, ] with suppress(Exception): from transformers.models.ibert.modeling_ibert import ( IBertPreTrainedModel, )", ") self.builtin_policies[BlenderbotPreTrainedModel] = [ BlenderbotEncoderPolicy, BlenderbotDecoderPolicy, ] with suppress(Exception): from", "implied. # See the License for the specific language governing", "( Wav2Vec2PreTrainedModel, ) from parallelformers.policies.wav2vec import Wav2VecPolicy self.builtin_policies[Wav2Vec2PreTrainedModel] = [", "( AlbertPreTrainedModel, ) from parallelformers.policies.albert import AlbertPolicy self.builtin_policies[AlbertPreTrainedModel] = [", "GPT2Policy, ] with suppress(Exception): from transformers.models.ctrl.modeling_ctrl import ( CTRLPreTrainedModel, )", "BertPolicy self.builtin_policies[BertGenerationPreTrainedModel] = [ BertPolicy, ] with suppress(Exception): from transformers.models.big_bird.modeling_big_bird", "] with suppress(Exception): from transformers.models.pegasus.modeling_pegasus import ( PegasusPreTrainedModel, ) from", "under the Apache License, Version 2.0 (the \"License\"); # you", "self.builtin_policies[PretrainedFSMTModel] = [ FSMTEncoderPolicy, FSMTDecoderPolicy, ] with suppress(Exception): from transformers.models.xlm.modeling_xlm", "parallelformers.policies.albert import AlbertPolicy self.builtin_policies[AlbertPreTrainedModel] = [ AlbertPolicy, ] with suppress(Exception):", "import AlbertPolicy self.builtin_policies[AlbertPreTrainedModel] = [ AlbertPolicy, ] with suppress(Exception): from", "import ( M2M100PreTrainedModel, ) from parallelformers.policies.m2m_100 import ( M2M100DecoderPolicy, M2M100EncoderPolicy,", "] with suppress(Exception): from transformers.models.deberta_v2.modeling_deberta_v2 import ( DebertaV2PreTrainedModel, ) from", "MPNetEncoderPolicy, MPNetLayerPolicy, ) self.builtin_policies[MPNetPreTrainedModel] = [ MPNetEncoderPolicy, MPNetLayerPolicy, ] with", "BertPolicy, ] with suppress(Exception): from transformers.models.lxmert.modeling_lxmert import ( LxmertPreTrainedModel, )", "suppress(Exception): from transformers.models.xlnet.modeling_xlnet import ( XLNetPreTrainedModel, ) from parallelformers.policies.xlnet import", "suppress(Exception): from transformers.models.detr.modeling_detr import ( DetrPreTrainedModel, ) from parallelformers.policies.detr import", "( DetrDecoderPolicy, DetrEncoderPolicy, ) self.builtin_policies[DetrPreTrainedModel] = [ DetrEncoderPolicy, DetrDecoderPolicy, ]", "from transformers.models.reformer.modeling_reformer import ( ReformerPreTrainedModel, ) from parallelformers.policies.reformer import ReformerPolicy", "[ LEDEncoderPolicy, LEDDecoderPolicy, ] with suppress(Exception): from transformers.models.prophetnet.modeling_prophetnet import (", "self.builtin_policies[DebertaV2PreTrainedModel] = [ DebertaV2Policy, ] with suppress(Exception): from transformers.models.openai.modeling_openai import", "with suppress(Exception): from transformers.models.prophetnet.modeling_prophetnet import ( ProphetNetPreTrainedModel, ) from parallelformers.policies.prophetnet", "DPRPretrainedContextEncoder, DPRPretrainedQuestionEncoder, DPRPretrainedReader, ) self.builtin_policies[DPRPretrainedReader] = [ BertPolicy, ] self.builtin_policies[DPRPretrainedQuestionEncoder]", "import ( BartDecoderPolicy, BartEncoderPolicy, ) self.builtin_policies[BartPretrainedModel] = [ BartEncoderPolicy, BartDecoderPolicy,", "import ( PegasusPreTrainedModel, ) from parallelformers.policies.pegasus import ( PegasusDecoderPolicy, PegasusEncoderPolicy,", "from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertGenerationPreTrainedModel] = [ BertPolicy, ] with", "( BertPreTrainedModel, ) from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertPreTrainedModel] = [", "[ VisualBertPolicy, ] with suppress(Exception): from transformers.models.speech_to_text.modeling_speech_to_text import ( Speech2TextPreTrainedModel,", "import ( Wav2Vec2PreTrainedModel, ) from parallelformers.policies.wav2vec import Wav2VecPolicy self.builtin_policies[Wav2Vec2PreTrainedModel] =", "by applicable law or agreed to in writing, software #", "PegasusDecoderPolicy, PegasusEncoderPolicy, ) self.builtin_policies[PegasusPreTrainedModel] = [ PegasusEncoderPolicy, PegasusDecoderPolicy, ] with", "[ MobileBertPolicy, ] with suppress(Exception): from transformers.models.mpnet.modeling_mpnet import ( MPNetPreTrainedModel,", "Wav2VecPolicy self.builtin_policies[Wav2Vec2PreTrainedModel] = [ Wav2VecPolicy, ] with suppress(Exception): from transformers.models.xlnet.modeling_xlnet", "parallelformers.policies.speech_to_text import ( Speech2TextDecoderPolicy, Speech2TextEncoderPolicy, ) self.builtin_policies[Speech2TextPreTrainedModel] = [ Speech2TextEncoderPolicy,", "import ( PretrainedFSMTModel, ) from parallelformers.policies.fsmt import ( FSMTDecoderPolicy, FSMTEncoderPolicy,", "from transformers.models.openai.modeling_openai import ( OpenAIGPTPreTrainedModel, ) from parallelformers.policies.openai import OpenAIGPTPolicy", "transformers.models.visual_bert.modeling_visual_bert import ( VisualBertPreTrainedModel, ) from parallelformers.policies.visual_bert import VisualBertPolicy self.builtin_policies[VisualBertPreTrainedModel]", "[ MPNetEncoderPolicy, MPNetLayerPolicy, ] with suppress(Exception): from transformers.models.luke.modeling_luke import (", "from transformers.models.bert_generation.modeling_bert_generation import ( BertGenerationPreTrainedModel, ) from parallelformers.policies.bert import BertPolicy", "suppress(Exception): from transformers.models.ctrl.modeling_ctrl import ( CTRLPreTrainedModel, ) from parallelformers.policies.ctrl import", "= [ GPT2Policy, ] with suppress(Exception): from transformers.models.ctrl.modeling_ctrl import (", "import DebertaV2Policy self.builtin_policies[DebertaV2PreTrainedModel] = [ DebertaV2Policy, ] with suppress(Exception): from", "suppress(Exception): from transformers.models.xlm.modeling_xlm import XLMPreTrainedModel from parallelformers.policies.xlm import ( XLMAttentionPolicy,", "LxmertPolicy, ] with suppress(Exception): from transformers.models.hubert.modeling_hubert import ( HubertPreTrainedModel, )", "transformers.models.retribert.modeling_retribert import ( RetriBertPreTrainedModel, ) self.builtin_policies[RetriBertPreTrainedModel] = [ BertPolicy, ]", "from transformers.models.distilbert.modeling_distilbert import ( DistilBertPreTrainedModel, ) from parallelformers.policies.distil_bert import DistilBertPolicy", "Union[List[Policy], None]: \"\"\" Find appropriate policies for the current model", "from transformers.models.blenderbot.modeling_blenderbot import ( BlenderbotPreTrainedModel, ) from parallelformers.policies.blenderbot import (", "suppress(Exception): from transformers.models.gptj.modeling_gptj import ( GPTJPreTrainedModel, ) from parallelformers.policies.gptj import", "transformers.models.distilbert.modeling_distilbert import ( DistilBertPreTrainedModel, ) from parallelformers.policies.distil_bert import DistilBertPolicy self.builtin_policies[DistilBertPreTrainedModel]", "= [ TapasPolicy, ] with suppress(Exception): from transformers.models.funnel.modeling_funnel import (", "DetrDecoderPolicy, DetrEncoderPolicy, ) self.builtin_policies[DetrPreTrainedModel] = [ DetrEncoderPolicy, DetrDecoderPolicy, ] with", ") self.builtin_policies[M2M100PreTrainedModel] = [ M2M100EncoderPolicy, M2M100DecoderPolicy, ] with suppress(Exception): from", "DistilBertPreTrainedModel, ) from parallelformers.policies.distil_bert import DistilBertPolicy self.builtin_policies[DistilBertPreTrainedModel] = [ DistilBertPolicy,", "FSMTEncoderPolicy, FSMTDecoderPolicy, ] with suppress(Exception): from transformers.models.xlm.modeling_xlm import XLMPreTrainedModel from", "transformers.models.speech_to_text.modeling_speech_to_text import ( Speech2TextPreTrainedModel, ) from parallelformers.policies.speech_to_text import ( Speech2TextDecoderPolicy,", "] with suppress(Exception): from transformers.models.clip.modeling_clip import ( CLIPPreTrainedModel, ) from", "self.builtin_policies[ReformerPreTrainedModel] = [ ReformerPolicy, ] with suppress(Exception): from transformers.models.longformer.modeling_longformer import", "Wav2VecPolicy, ] with suppress(Exception): from transformers.models.xlnet.modeling_xlnet import ( XLNetPreTrainedModel, )", "self.builtin_policies[TransfoXLPreTrainedModel] = [ TransfoXLPolicy, ] with suppress(Exception): from transformers.models.roberta.modeling_roberta import", "self.builtin_policies[AlbertPreTrainedModel] = [ AlbertPolicy, ] with suppress(Exception): from transformers.models.gpt2.modeling_gpt2 import", "self.builtin_policies[ElectraPreTrainedModel] = [ ElectraPolicy, ] with suppress(Exception): from transformers.models.blenderbot_small.modeling_blenderbot_small import", ") from parallelformers.policies.detr import ( DetrDecoderPolicy, DetrEncoderPolicy, ) self.builtin_policies[DetrPreTrainedModel] =", "suppress(Exception): from transformers.models.convbert.modeling_convbert import ( ConvBertPreTrainedModel, ) from parallelformers.policies.convbert import", "[ DebertaPolicy, ] with suppress(Exception): from transformers.models.transfo_xl.modeling_transfo_xl import ( TransfoXLPreTrainedModel,", "PegasusDecoderPolicy, ] with suppress(Exception): from transformers.models.fsmt.modeling_fsmt import ( PretrainedFSMTModel, )", "] with suppress(Exception): from transformers.models.distilbert.modeling_distilbert import ( DistilBertPreTrainedModel, ) from", "BartEncoderPolicy, BartDecoderPolicy, ] with suppress(Exception): from transformers.models.blenderbot.modeling_blenderbot import ( BlenderbotPreTrainedModel,", "parallelformers.policies.mobilebert import MobileBertPolicy self.builtin_policies[MobileBertPreTrainedModel] = [ MobileBertPolicy, ] with suppress(Exception):", "BartDecoderPolicy, ] with suppress(Exception): from transformers.models.blenderbot.modeling_blenderbot import ( BlenderbotPreTrainedModel, )", "= [ BigBirdPolicy, ] with suppress(Exception): from transformers.models.bigbird_pegasus.modeling_bigbird_pegasus import (", "self.builtin_policies[CLIPPreTrainedModel] = [ CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ] with suppress(Exception): from", "( ElectraPreTrainedModel, ) from parallelformers.policies.electra import ElectraPolicy self.builtin_policies[ElectraPreTrainedModel] = [", "or none \"\"\" for k, v in self.available().items(): if isinstance(model,", "= [ ReformerPolicy, ] with suppress(Exception): from transformers.models.longformer.modeling_longformer import (", "LayoutLMPolicy, ] with suppress(Exception): from transformers.models.led.modeling_led import LEDPreTrainedModel from parallelformers.policies.led", ") from parallelformers.policies.layoutlm import LayoutLMPolicy self.builtin_policies[LayoutLMPreTrainedModel] = [ LayoutLMPolicy, ]", "isinstance(model, k): return v return None def available(self): \"\"\"Dictionary of", "CTRLPolicy, ] with suppress(Exception): from transformers.models.deberta_v2.modeling_deberta_v2 import ( DebertaV2PreTrainedModel, )", ") from parallelformers.policies.mobilebert import MobileBertPolicy self.builtin_policies[MobileBertPreTrainedModel] = [ MobileBertPolicy, ]", "parallelformers.policies.funnel import FunnelPolicy self.builtin_policies[FunnelPreTrainedModel] = [ FunnelPolicy, ] with suppress(Exception):", "TUNiB inc. # # Licensed under the Apache License, Version", "self.builtin_policies[BlenderbotPreTrainedModel] = [ BlenderbotEncoderPolicy, BlenderbotDecoderPolicy, ] with suppress(Exception): from transformers.models.deberta.modeling_deberta", "transformers.models.deberta.modeling_deberta import ( DebertaPreTrainedModel, ) from parallelformers.policies.deberta import DebertaPolicy self.builtin_policies[DebertaPreTrainedModel]", "import XLNetPolicy self.builtin_policies[XLNetPreTrainedModel] = [ XLNetPolicy, ] with suppress(Exception): from", "parallelformers.policies.gpt_neo import GPTNeoPolicy self.builtin_policies[GPTNeoPreTrainedModel] = [ GPTNeoPolicy, ] with suppress(Exception):", "BigBirdPegasusEncoderPolicy, ) self.builtin_policies[BigBirdPegasusPreTrainedModel] = [ BigBirdPegasusEncoderPolicy, BigBirdPegasusDecoderPolicy, ] with suppress(Exception):", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "import ViTPreTrainedModel from parallelformers.policies.vit import ViTPolicy self.builtin_policies[ViTPreTrainedModel] = [ ViTPolicy,", "import TransfoXLPolicy self.builtin_policies[TransfoXLPreTrainedModel] = [ TransfoXLPolicy, ] with suppress(Exception): from", ") from parallelformers.policies.hubert import HubertPolicy self.builtin_policies[HubertPreTrainedModel] = [ HubertPolicy, ]", "] with suppress(Exception): from transformers.models.retribert.modeling_retribert import ( RetriBertPreTrainedModel, ) self.builtin_policies[RetriBertPreTrainedModel]", "import ( RobertaPreTrainedModel, ) from parallelformers.policies.roberta import RobertaPolicy self.builtin_policies[RobertaPreTrainedModel] =", "Unless required by applicable law or agreed to in writing,", "VisualBertPolicy, ] with suppress(Exception): from transformers.models.speech_to_text.modeling_speech_to_text import ( Speech2TextPreTrainedModel, )", "= [ TransfoXLPolicy, ] with suppress(Exception): from transformers.models.roberta.modeling_roberta import (", "from transformers.models.gptj.modeling_gptj import ( GPTJPreTrainedModel, ) from parallelformers.policies.gptj import GPTJPolicy", "BartDecoderPolicy, BartEncoderPolicy, ) self.builtin_policies[BartPretrainedModel] = [ BartEncoderPolicy, BartDecoderPolicy, ] with", "with suppress(Exception): from transformers.models.clip.modeling_clip import ( CLIPPreTrainedModel, ) from parallelformers.policies.clip", "import ( FunnelPreTrainedModel, ) from parallelformers.policies.funnel import FunnelPolicy self.builtin_policies[FunnelPreTrainedModel] =", "[ LxmertPolicy, ] with suppress(Exception): from transformers.models.hubert.modeling_hubert import ( HubertPreTrainedModel,", "parallelformers.policies.roformer import RoformerPolicy self.builtin_policies[RoFormerPreTrainedModel] = [ RoformerPolicy, ] with suppress(Exception):", "[ FunnelPolicy, ] with suppress(Exception): from transformers.models.layoutlm.modeling_layoutlm import ( LayoutLMPreTrainedModel,", "import ( Speech2TextDecoderPolicy, Speech2TextEncoderPolicy, ) self.builtin_policies[Speech2TextPreTrainedModel] = [ Speech2TextEncoderPolicy, Speech2TextDecoderPolicy,", "with suppress(Exception): from transformers.models.ctrl.modeling_ctrl import ( CTRLPreTrainedModel, ) from parallelformers.policies.ctrl", "( MarianPreTrainedModel, ) from parallelformers.policies.marian import ( MarianDecoderPolicy, MarianEncoderPolicy, )", "] with suppress(Exception): from transformers.models.deberta.modeling_deberta import ( DebertaPreTrainedModel, ) from", ") from parallelformers.policies.megtron_bert import ( MegatronBertPolicy, ) self.builtin_policies[MegatronBertPreTrainedModel] = [", "DetrDecoderPolicy, ] with suppress(Exception): from transformers.models.reformer.modeling_reformer import ( ReformerPreTrainedModel, )", "= [ PegasusEncoderPolicy, PegasusDecoderPolicy, ] with suppress(Exception): from transformers.models.fsmt.modeling_fsmt import", "from parallelformers.policies.base import Policy class AutoPolicy: \"\"\"Class for finds automatically", "TapasPolicy self.builtin_policies[TapasPreTrainedModel] = [ TapasPolicy, ] with suppress(Exception): from transformers.models.funnel.modeling_funnel", "suppress(Exception): from transformers.models.dpr.modeling_dpr import ( DPRPretrainedContextEncoder, DPRPretrainedQuestionEncoder, DPRPretrainedReader, ) self.builtin_policies[DPRPretrainedReader]", "import GPTJPolicy self.builtin_policies[GPTJPreTrainedModel] = [ GPTJPolicy, ] with suppress(Exception): from", ") from parallelformers.policies.luke import LukePolicy self.builtin_policies[LukePreTrainedModel] = [ LukePolicy, ]", "the specific language governing permissions and # limitations under the", "GPT2PreTrainedModel, ) from parallelformers.policies.gpt2 import GPT2Policy self.builtin_policies[GPT2PreTrainedModel] = [ GPT2Policy,", "] with suppress(Exception): from transformers.models.mobilebert.modeling_mobilebert import ( MobileBertPreTrainedModel, ) from", "with suppress(Exception): from transformers.models.convbert.modeling_convbert import ( ConvBertPreTrainedModel, ) from parallelformers.policies.convbert", "( BigBirdPegasusPreTrainedModel, ) from parallelformers.policies.bigbird_pegasus import ( BigBirdPegasusDecoderPolicy, BigBirdPegasusEncoderPolicy, )", "import LayoutLMPolicy self.builtin_policies[LayoutLMPreTrainedModel] = [ LayoutLMPolicy, ] with suppress(Exception): from", "with suppress(Exception): from transformers.models.retribert.modeling_retribert import ( RetriBertPreTrainedModel, ) self.builtin_policies[RetriBertPreTrainedModel] =", "self.builtin_policies[M2M100PreTrainedModel] = [ M2M100EncoderPolicy, M2M100DecoderPolicy, ] with suppress(Exception): from transformers.models.marian.modeling_marian", "] self.builtin_policies[DPRPretrainedQuestionEncoder] = [ BertPolicy, ] self.builtin_policies[DPRPretrainedContextEncoder] = [ BertPolicy,", "BigBirdPreTrainedModel, ) from parallelformers.policies.bigbird import BigBirdPolicy self.builtin_policies[BigBirdPreTrainedModel] = [ BigBirdPolicy,", "applicable law or agreed to in writing, software # distributed", ") from parallelformers.policies.bigbird import BigBirdPolicy self.builtin_policies[BigBirdPreTrainedModel] = [ BigBirdPolicy, ]", "BigBirdPolicy, ] with suppress(Exception): from transformers.models.bigbird_pegasus.modeling_bigbird_pegasus import ( BigBirdPegasusPreTrainedModel, )", "PegasusEncoderPolicy, PegasusDecoderPolicy, ] with suppress(Exception): from transformers.models.fsmt.modeling_fsmt import ( PretrainedFSMTModel,", "from transformers.models.xlm.modeling_xlm import XLMPreTrainedModel from parallelformers.policies.xlm import ( XLMAttentionPolicy, XLMMLPPolicy,", "MegatronBertPolicy, ) self.builtin_policies[MegatronBertPreTrainedModel] = [ MegatronBertPolicy, ] def get_policy(self, model:", "\"\"\" Find appropriate policies for the current model Args: model", "BlenderbotPreTrainedModel, ) from parallelformers.policies.blenderbot import ( BlenderbotDecoderPolicy, BlenderbotEncoderPolicy, ) self.builtin_policies[BlenderbotPreTrainedModel]", "with suppress(Exception): from transformers.models.hubert.modeling_hubert import ( HubertPreTrainedModel, ) from parallelformers.policies.hubert", "( MarianDecoderPolicy, MarianEncoderPolicy, ) self.builtin_policies[MarianPreTrainedModel] = [ MarianEncoderPolicy, MarianDecoderPolicy, ]", "import ( CTRLPreTrainedModel, ) from parallelformers.policies.ctrl import CTRLPolicy self.builtin_policies[CTRLPreTrainedModel] =", "transformers.models.ctrl.modeling_ctrl import ( CTRLPreTrainedModel, ) from parallelformers.policies.ctrl import CTRLPolicy self.builtin_policies[CTRLPreTrainedModel]", "( RobertaPreTrainedModel, ) from parallelformers.policies.roberta import RobertaPolicy self.builtin_policies[RobertaPreTrainedModel] = [", "suppress(Exception): from transformers.models.reformer.modeling_reformer import ( ReformerPreTrainedModel, ) from parallelformers.policies.reformer import", "with suppress(Exception): from transformers.models.openai.modeling_openai import ( OpenAIGPTPreTrainedModel, ) from parallelformers.policies.openai", "MBartEncoderPolicy, ) self.builtin_policies[MBartPreTrainedModel] = [ MBartEncoderPolicy, MBartDecoderPolicy, ] with suppress(Exception):", "parallelformers.policies.xlm import ( XLMAttentionPolicy, XLMMLPPolicy, ) self.builtin_policies[XLMPreTrainedModel] = [ XLMAttentionPolicy,", "[ MegatronBertPolicy, ] def get_policy(self, model: nn.Module) -> Union[List[Policy], None]:", "[ OpenAIGPTPolicy, ] with suppress(Exception): from transformers.models.electra.modeling_electra import ( ElectraPreTrainedModel,", "] with suppress(Exception): from transformers.models.transfo_xl.modeling_transfo_xl import ( TransfoXLPreTrainedModel, ) from", "automatically appropriate policies for the current model\"\"\" def __init__(self): self.builtin_policies", "[ ViTPolicy, ] with suppress(Exception): from transformers.models.deit.modeling_deit import ( DeiTPreTrainedModel,", "in writing, software # distributed under the License is distributed", "[ GPTNeoPolicy, ] with suppress(Exception): from transformers.models.bert.modeling_bert import ( BertPreTrainedModel,", "( DistilBertPreTrainedModel, ) from parallelformers.policies.distil_bert import DistilBertPolicy self.builtin_policies[DistilBertPreTrainedModel] = [", "DeiTPreTrainedModel, ) from parallelformers.policies.deit import DeiTPolicy self.builtin_policies[DeiTPreTrainedModel] = [DeiTPolicy] with", ") from parallelformers.policies.m2m_100 import ( M2M100DecoderPolicy, M2M100EncoderPolicy, ) self.builtin_policies[M2M100PreTrainedModel] =", "] with suppress(Exception): from transformers.models.t5.modeling_t5 import T5PreTrainedModel from parallelformers.policies.t5 import", "transformers.models.albert.modeling_albert import ( AlbertPreTrainedModel, ) from parallelformers.policies.albert import AlbertPolicy self.builtin_policies[AlbertPreTrainedModel]", "self.builtin_policies[TapasPreTrainedModel] = [ TapasPolicy, ] with suppress(Exception): from transformers.models.funnel.modeling_funnel import", "] with suppress(Exception): from transformers.models.ctrl.modeling_ctrl import ( CTRLPreTrainedModel, ) from", "suppress(Exception): from transformers.models.distilbert.modeling_distilbert import ( DistilBertPreTrainedModel, ) from parallelformers.policies.distil_bert import", "import ( BlenderbotSmallDecoderPolicy, BlenderbotSmallEncoderPolicy, ) self.builtin_policies[BlenderbotSmallPreTrainedModel] = [ BlenderbotSmallEncoderPolicy, BlenderbotSmallDecoderPolicy,", "[ BertPolicy, ] with suppress(Exception): from transformers.models.big_bird.modeling_big_bird import ( BigBirdPreTrainedModel,", "from parallelformers.policies.marian import ( MarianDecoderPolicy, MarianEncoderPolicy, ) self.builtin_policies[MarianPreTrainedModel] = [", "= [ DebertaPolicy, ] with suppress(Exception): from transformers.models.transfo_xl.modeling_transfo_xl import (", ") from parallelformers.policies.gpt2 import GPT2Policy self.builtin_policies[GPT2PreTrainedModel] = [ GPT2Policy, ]", "] with suppress(Exception): from transformers.models.wav2vec2.modeling_wav2vec2 import ( Wav2Vec2PreTrainedModel, ) from", "BertGenerationPreTrainedModel, ) from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertGenerationPreTrainedModel] = [ BertPolicy,", "ViTPolicy self.builtin_policies[ViTPreTrainedModel] = [ ViTPolicy, ] with suppress(Exception): from transformers.models.deit.modeling_deit", "with suppress(Exception): from transformers.models.mbart.modeling_mbart import ( MBartPreTrainedModel, ) from parallelformers.policies.mbart", "ReformerPreTrainedModel, ) from parallelformers.policies.reformer import ReformerPolicy self.builtin_policies[ReformerPreTrainedModel] = [ ReformerPolicy,", "self.builtin_policies[FunnelPreTrainedModel] = [ FunnelPolicy, ] with suppress(Exception): from transformers.models.layoutlm.modeling_layoutlm import", "transformers.models.mpnet.modeling_mpnet import ( MPNetPreTrainedModel, ) from parallelformers.policies.mpnet import ( MPNetEncoderPolicy,", "\"\"\"Class for finds automatically appropriate policies for the current model\"\"\"", "] with suppress(Exception): from transformers.models.gptj.modeling_gptj import ( GPTJPreTrainedModel, ) from", "suppress(Exception): from transformers.models.roformer.modeling_roformer import ( RoFormerPreTrainedModel, ) from parallelformers.policies.roformer import", "parallelformers.policies.fsmt import ( FSMTDecoderPolicy, FSMTEncoderPolicy, ) self.builtin_policies[PretrainedFSMTModel] = [ FSMTEncoderPolicy,", "suppress(Exception): from transformers.models.megatron_bert import ( MegatronBertPreTrainedModel, ) from parallelformers.policies.megtron_bert import", "from parallelformers.policies.albert import AlbertPolicy self.builtin_policies[AlbertPreTrainedModel] = [ AlbertPolicy, ] with", "import ( ElectraPreTrainedModel, ) from parallelformers.policies.electra import ElectraPolicy self.builtin_policies[ElectraPreTrainedModel] =", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "= [ BigBirdPegasusEncoderPolicy, BigBirdPegasusDecoderPolicy, ] with suppress(Exception): from transformers.models.vit.modeling_vit import", "suppress(Exception): from transformers.models.pegasus.modeling_pegasus import ( PegasusPreTrainedModel, ) from parallelformers.policies.pegasus import", "= [ BertPolicy, ] with suppress(Exception): from transformers.models.bart.modeling_bart import (", "[ BertPolicy, ] self.builtin_policies[DPRPretrainedContextEncoder] = [ BertPolicy, ] with suppress(Exception):", "License, Version 2.0 (the \"License\"); # you may not use", "suppress(Exception): from transformers.models.electra.modeling_electra import ( ElectraPreTrainedModel, ) from parallelformers.policies.electra import", "parallelformers.policies.convbert import ConvBertPolicy self.builtin_policies[ConvBertPreTrainedModel] = [ ConvBertPolicy, ] with suppress(Exception):", "# You may obtain a copy of the License at", "import ( DetrDecoderPolicy, DetrEncoderPolicy, ) self.builtin_policies[DetrPreTrainedModel] = [ DetrEncoderPolicy, DetrDecoderPolicy,", "RobertaPolicy self.builtin_policies[RobertaPreTrainedModel] = [ RobertaPolicy, ] with suppress(Exception): from transformers.models.albert.modeling_albert", "import ( TransfoXLPreTrainedModel, ) from parallelformers.policies.transfo_xl import TransfoXLPolicy self.builtin_policies[TransfoXLPreTrainedModel] =", "self.builtin_policies[OpenAIGPTPreTrainedModel] = [ OpenAIGPTPolicy, ] with suppress(Exception): from transformers.models.electra.modeling_electra import", "( LxmertPreTrainedModel, ) from parallelformers.policies.lxmert import LxmertPolicy self.builtin_policies[LxmertPreTrainedModel] = [", "k, v in self.available().items(): if isinstance(model, k): return v return", "( IBertPreTrainedModel, ) from parallelformers.policies.ibert import IBertPolicy self.builtin_policies[IBertPreTrainedModel] = [", ") from parallelformers.policies.marian import ( MarianDecoderPolicy, MarianEncoderPolicy, ) self.builtin_policies[MarianPreTrainedModel] =", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", ") from parallelformers.policies.reformer import ReformerPolicy self.builtin_policies[ReformerPreTrainedModel] = [ ReformerPolicy, ]", "from parallelformers.policies.gpt2 import GPT2Policy self.builtin_policies[GPT2PreTrainedModel] = [ GPT2Policy, ] with", "parallelformers.policies.deit import DeiTPolicy self.builtin_policies[DeiTPreTrainedModel] = [DeiTPolicy] with suppress(Exception): from transformers.models.mbart.modeling_mbart", "import DeiTPolicy self.builtin_policies[DeiTPreTrainedModel] = [DeiTPolicy] with suppress(Exception): from transformers.models.mbart.modeling_mbart import", ") from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertGenerationPreTrainedModel] = [ BertPolicy, ]", "for finds automatically appropriate policies for the current model\"\"\" def", "import ReformerPolicy self.builtin_policies[ReformerPreTrainedModel] = [ ReformerPolicy, ] with suppress(Exception): from", "import RoformerPolicy self.builtin_policies[RoFormerPreTrainedModel] = [ RoformerPolicy, ] with suppress(Exception): from", "appropriate policies for the current model Args: model (nn.Module): model", "transformers.models.mbart.modeling_mbart import ( MBartPreTrainedModel, ) from parallelformers.policies.mbart import ( MBartDecoderPolicy,", "from parallelformers.policies.blenderbot_small import ( BlenderbotSmallDecoderPolicy, BlenderbotSmallEncoderPolicy, ) self.builtin_policies[BlenderbotSmallPreTrainedModel] = [", "Find appropriate policies for the current model Args: model (nn.Module):", "BertPreTrainedModel, ) from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertPreTrainedModel] = [ BertPolicy,", "from parallelformers.policies.gptj import GPTJPolicy self.builtin_policies[GPTJPreTrainedModel] = [ GPTJPolicy, ] with", "import ElectraPolicy self.builtin_policies[ElectraPreTrainedModel] = [ ElectraPolicy, ] with suppress(Exception): from", "parallelformers.policies.clip import ( CLIPLayerPolicy, CLIPTextPolicy, CLIPVisionPolicy, ) self.builtin_policies[CLIPPreTrainedModel] = [", "with suppress(Exception): from transformers.models.gptj.modeling_gptj import ( GPTJPreTrainedModel, ) from parallelformers.policies.gptj", "from transformers.models.megatron_bert import ( MegatronBertPreTrainedModel, ) from parallelformers.policies.megtron_bert import (", "None]: appropriate policies or none \"\"\" for k, v in", "FSMTDecoderPolicy, FSMTEncoderPolicy, ) self.builtin_policies[PretrainedFSMTModel] = [ FSMTEncoderPolicy, FSMTDecoderPolicy, ] with", "BertPolicy, ] with suppress(Exception): from transformers.models.clip.modeling_clip import ( CLIPPreTrainedModel, )", "self.builtin_policies[T5PreTrainedModel] = [ T5Policy, ] with suppress(Exception): from transformers.models.pegasus.modeling_pegasus import", "from transformers.models.fsmt.modeling_fsmt import ( PretrainedFSMTModel, ) from parallelformers.policies.fsmt import (", ") self.builtin_policies[XLMPreTrainedModel] = [ XLMAttentionPolicy, XLMMLPPolicy, ] with suppress(Exception): from", "ProphetNetDecoderPolicy, ProphetNetEncoderPolicy, ) self.builtin_policies[ProphetNetPreTrainedModel] = [ ProphetNetEncoderPolicy, ProphetNetDecoderPolicy, ] with", "FSMTDecoderPolicy, ] with suppress(Exception): from transformers.models.xlm.modeling_xlm import XLMPreTrainedModel from parallelformers.policies.xlm", "the License for the specific language governing permissions and #", "contextlib import suppress from typing import List, Union from torch", "from parallelformers.policies.prophetnet import ( ProphetNetDecoderPolicy, ProphetNetEncoderPolicy, ) self.builtin_policies[ProphetNetPreTrainedModel] = [", "import Policy class AutoPolicy: \"\"\"Class for finds automatically appropriate policies", "Apache License, Version 2.0 (the \"License\"); # you may not", "parallelformers.policies.tapas import TapasPolicy self.builtin_policies[TapasPreTrainedModel] = [ TapasPolicy, ] with suppress(Exception):", "DebertaV2PreTrainedModel, ) from parallelformers.policies.deberta_v2 import DebertaV2Policy self.builtin_policies[DebertaV2PreTrainedModel] = [ DebertaV2Policy,", "BigBirdPegasusDecoderPolicy, ] with suppress(Exception): from transformers.models.vit.modeling_vit import ViTPreTrainedModel from parallelformers.policies.vit", "either express or implied. # See the License for the", "with suppress(Exception): from transformers.models.detr.modeling_detr import ( DetrPreTrainedModel, ) from parallelformers.policies.detr", "LEDDecoderPolicy, LEDEncoderPolicy, ) self.builtin_policies[LEDPreTrainedModel] = [ LEDEncoderPolicy, LEDDecoderPolicy, ] with", "__init__(self): self.builtin_policies = {} with suppress(Exception): from transformers.models.gpt_neo.modeling_gpt_neo import (", "( Speech2TextDecoderPolicy, Speech2TextEncoderPolicy, ) self.builtin_policies[Speech2TextPreTrainedModel] = [ Speech2TextEncoderPolicy, Speech2TextDecoderPolicy, ]", "DebertaV2Policy self.builtin_policies[DebertaV2PreTrainedModel] = [ DebertaV2Policy, ] with suppress(Exception): from transformers.models.openai.modeling_openai", "[ M2M100EncoderPolicy, M2M100DecoderPolicy, ] with suppress(Exception): from transformers.models.marian.modeling_marian import (", "] with suppress(Exception): from transformers.models.roformer.modeling_roformer import ( RoFormerPreTrainedModel, ) from", "VisualBertPolicy self.builtin_policies[VisualBertPreTrainedModel] = [ VisualBertPolicy, ] with suppress(Exception): from transformers.models.speech_to_text.modeling_speech_to_text", "[ GPT2Policy, ] with suppress(Exception): from transformers.models.ctrl.modeling_ctrl import ( CTRLPreTrainedModel,", "( DetrPreTrainedModel, ) from parallelformers.policies.detr import ( DetrDecoderPolicy, DetrEncoderPolicy, )", "import ( DebertaV2PreTrainedModel, ) from parallelformers.policies.deberta_v2 import DebertaV2Policy self.builtin_policies[DebertaV2PreTrainedModel] =", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "transformers.models.prophetnet.modeling_prophetnet import ( ProphetNetPreTrainedModel, ) from parallelformers.policies.prophetnet import ( ProphetNetDecoderPolicy,", "from transformers.models.longformer.modeling_longformer import ( LongformerPreTrainedModel, ) from parallelformers.policies.longformer import LongformerPolicy", "HubertPolicy, ] with suppress(Exception): from transformers.models.wav2vec2.modeling_wav2vec2 import ( Wav2Vec2PreTrainedModel, )", "parallelformers.policies.gpt2 import GPT2Policy self.builtin_policies[GPT2PreTrainedModel] = [ GPT2Policy, ] with suppress(Exception):", "ConvBertPreTrainedModel, ) from parallelformers.policies.convbert import ConvBertPolicy self.builtin_policies[ConvBertPreTrainedModel] = [ ConvBertPolicy,", "= [ VisualBertPolicy, ] with suppress(Exception): from transformers.models.speech_to_text.modeling_speech_to_text import (", "XLNetPolicy, ] with suppress(Exception): from transformers.models.retribert.modeling_retribert import ( RetriBertPreTrainedModel, )", "import LongformerPolicy self.builtin_policies[LongformerPreTrainedModel] = [ LongformerPolicy, ] with suppress(Exception): from", "LayoutLMPolicy self.builtin_policies[LayoutLMPreTrainedModel] = [ LayoutLMPolicy, ] with suppress(Exception): from transformers.models.led.modeling_led", "with suppress(Exception): from transformers.models.speech_to_text.modeling_speech_to_text import ( Speech2TextPreTrainedModel, ) from parallelformers.policies.speech_to_text", "transformers.models.t5.modeling_t5 import T5PreTrainedModel from parallelformers.policies.t5 import T5Policy self.builtin_policies[T5PreTrainedModel] = [", "parallelformers.policies.reformer import ReformerPolicy self.builtin_policies[ReformerPreTrainedModel] = [ ReformerPolicy, ] with suppress(Exception):", "inc. # # Licensed under the Apache License, Version 2.0", "parallelformers.policies.marian import ( MarianDecoderPolicy, MarianEncoderPolicy, ) self.builtin_policies[MarianPreTrainedModel] = [ MarianEncoderPolicy,", "suppress(Exception): from transformers.models.led.modeling_led import LEDPreTrainedModel from parallelformers.policies.led import ( LEDDecoderPolicy,", "= [ Wav2VecPolicy, ] with suppress(Exception): from transformers.models.xlnet.modeling_xlnet import (", "parallelformers.policies.bigbird import BigBirdPolicy self.builtin_policies[BigBirdPreTrainedModel] = [ BigBirdPolicy, ] with suppress(Exception):", "suppress(Exception): from transformers.models.gpt2.modeling_gpt2 import ( GPT2PreTrainedModel, ) from parallelformers.policies.gpt2 import", "limitations under the License. from contextlib import suppress from typing", "transformers.models.megatron_bert import ( MegatronBertPreTrainedModel, ) from parallelformers.policies.megtron_bert import ( MegatronBertPolicy,", "BartPretrainedModel, ) from parallelformers.policies.bart import ( BartDecoderPolicy, BartEncoderPolicy, ) self.builtin_policies[BartPretrainedModel]", "with suppress(Exception): from transformers.models.mpnet.modeling_mpnet import ( MPNetPreTrainedModel, ) from parallelformers.policies.mpnet", "with suppress(Exception): from transformers.models.roberta.modeling_roberta import ( RobertaPreTrainedModel, ) from parallelformers.policies.roberta", "( XLMAttentionPolicy, XLMMLPPolicy, ) self.builtin_policies[XLMPreTrainedModel] = [ XLMAttentionPolicy, XLMMLPPolicy, ]", "from transformers.models.marian.modeling_marian import ( MarianPreTrainedModel, ) from parallelformers.policies.marian import (", "import GPTNeoPolicy self.builtin_policies[GPTNeoPreTrainedModel] = [ GPTNeoPolicy, ] with suppress(Exception): from", "import BigBirdPolicy self.builtin_policies[BigBirdPreTrainedModel] = [ BigBirdPolicy, ] with suppress(Exception): from", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "with suppress(Exception): from transformers.models.deberta_v2.modeling_deberta_v2 import ( DebertaV2PreTrainedModel, ) from parallelformers.policies.deberta_v2", "T5PreTrainedModel from parallelformers.policies.t5 import T5Policy self.builtin_policies[T5PreTrainedModel] = [ T5Policy, ]", "from parallelformers.policies.distil_bert import DistilBertPolicy self.builtin_policies[DistilBertPreTrainedModel] = [ DistilBertPolicy, ] with", "( M2M100PreTrainedModel, ) from parallelformers.policies.m2m_100 import ( M2M100DecoderPolicy, M2M100EncoderPolicy, )", "suppress(Exception): from transformers.models.openai.modeling_openai import ( OpenAIGPTPreTrainedModel, ) from parallelformers.policies.openai import", "RetriBertPreTrainedModel, ) self.builtin_policies[RetriBertPreTrainedModel] = [ BertPolicy, ] with suppress(Exception): from", "self.builtin_policies[DetrPreTrainedModel] = [ DetrEncoderPolicy, DetrDecoderPolicy, ] with suppress(Exception): from transformers.models.reformer.modeling_reformer", "LEDPreTrainedModel from parallelformers.policies.led import ( LEDDecoderPolicy, LEDEncoderPolicy, ) self.builtin_policies[LEDPreTrainedModel] =", "from transformers.models.m2m_100.modeling_m2m_100 import ( M2M100PreTrainedModel, ) from parallelformers.policies.m2m_100 import (", ") self.builtin_policies[PegasusPreTrainedModel] = [ PegasusEncoderPolicy, PegasusDecoderPolicy, ] with suppress(Exception): from", "= [ LongformerPolicy, ] with suppress(Exception): from transformers.models.roformer.modeling_roformer import (", "from transformers.models.prophetnet.modeling_prophetnet import ( ProphetNetPreTrainedModel, ) from parallelformers.policies.prophetnet import (", "[ FSMTEncoderPolicy, FSMTDecoderPolicy, ] with suppress(Exception): from transformers.models.xlm.modeling_xlm import XLMPreTrainedModel", "DistilBertPolicy, ] with suppress(Exception): from transformers.models.convbert.modeling_convbert import ( ConvBertPreTrainedModel, )", "from transformers.models.xlnet.modeling_xlnet import ( XLNetPreTrainedModel, ) from parallelformers.policies.xlnet import XLNetPolicy", "with suppress(Exception): from transformers.models.big_bird.modeling_big_bird import ( BigBirdPreTrainedModel, ) from parallelformers.policies.bigbird", "suppress(Exception): from transformers.models.layoutlm.modeling_layoutlm import ( LayoutLMPreTrainedModel, ) from parallelformers.policies.layoutlm import", "Speech2TextDecoderPolicy, Speech2TextEncoderPolicy, ) self.builtin_policies[Speech2TextPreTrainedModel] = [ Speech2TextEncoderPolicy, Speech2TextDecoderPolicy, ] with", "Speech2TextDecoderPolicy, ] with suppress(Exception): from transformers.models.gptj.modeling_gptj import ( GPTJPreTrainedModel, )", "import ( LukePreTrainedModel, ) from parallelformers.policies.luke import LukePolicy self.builtin_policies[LukePreTrainedModel] =", "to parallelize Returns: Union[List[Policy], None]: appropriate policies or none \"\"\"", "PretrainedFSMTModel, ) from parallelformers.policies.fsmt import ( FSMTDecoderPolicy, FSMTEncoderPolicy, ) self.builtin_policies[PretrainedFSMTModel]", "RoformerPolicy self.builtin_policies[RoFormerPreTrainedModel] = [ RoformerPolicy, ] with suppress(Exception): from transformers.models.ibert.modeling_ibert", "import ( GPTJPreTrainedModel, ) from parallelformers.policies.gptj import GPTJPolicy self.builtin_policies[GPTJPreTrainedModel] =", "AlbertPolicy self.builtin_policies[AlbertPreTrainedModel] = [ AlbertPolicy, ] with suppress(Exception): from transformers.models.gpt2.modeling_gpt2", ") from parallelformers.policies.bigbird_pegasus import ( BigBirdPegasusDecoderPolicy, BigBirdPegasusEncoderPolicy, ) self.builtin_policies[BigBirdPegasusPreTrainedModel] =", "] with suppress(Exception): from transformers.models.reformer.modeling_reformer import ( ReformerPreTrainedModel, ) from", "XLMAttentionPolicy, XLMMLPPolicy, ] with suppress(Exception): from transformers.models.m2m_100.modeling_m2m_100 import ( M2M100PreTrainedModel,", "LEDEncoderPolicy, LEDDecoderPolicy, ] with suppress(Exception): from transformers.models.prophetnet.modeling_prophetnet import ( ProphetNetPreTrainedModel,", "\"License\"); # you may not use this file except in", "( BartDecoderPolicy, BartEncoderPolicy, ) self.builtin_policies[BartPretrainedModel] = [ BartEncoderPolicy, BartDecoderPolicy, ]", "RoFormerPreTrainedModel, ) from parallelformers.policies.roformer import RoformerPolicy self.builtin_policies[RoFormerPreTrainedModel] = [ RoformerPolicy,", "] with suppress(Exception): from transformers.models.openai.modeling_openai import ( OpenAIGPTPreTrainedModel, ) from", "from transformers.models.electra.modeling_electra import ( ElectraPreTrainedModel, ) from parallelformers.policies.electra import ElectraPolicy", "LongformerPolicy self.builtin_policies[LongformerPreTrainedModel] = [ LongformerPolicy, ] with suppress(Exception): from transformers.models.roformer.modeling_roformer", "suppress(Exception): from transformers.models.deberta_v2.modeling_deberta_v2 import ( DebertaV2PreTrainedModel, ) from parallelformers.policies.deberta_v2 import", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", ") from parallelformers.policies.pegasus import ( PegasusDecoderPolicy, PegasusEncoderPolicy, ) self.builtin_policies[PegasusPreTrainedModel] =", "from parallelformers.policies.bigbird_pegasus import ( BigBirdPegasusDecoderPolicy, BigBirdPegasusEncoderPolicy, ) self.builtin_policies[BigBirdPegasusPreTrainedModel] = [", "from transformers.models.mpnet.modeling_mpnet import ( MPNetPreTrainedModel, ) from parallelformers.policies.mpnet import (", "( FunnelPreTrainedModel, ) from parallelformers.policies.funnel import FunnelPolicy self.builtin_policies[FunnelPreTrainedModel] = [", "import ( LEDDecoderPolicy, LEDEncoderPolicy, ) self.builtin_policies[LEDPreTrainedModel] = [ LEDEncoderPolicy, LEDDecoderPolicy,", "[ AlbertPolicy, ] with suppress(Exception): from transformers.models.gpt2.modeling_gpt2 import ( GPT2PreTrainedModel,", "from transformers.models.wav2vec2.modeling_wav2vec2 import ( Wav2Vec2PreTrainedModel, ) from parallelformers.policies.wav2vec import Wav2VecPolicy", "from parallelformers.policies.tapas import TapasPolicy self.builtin_policies[TapasPreTrainedModel] = [ TapasPolicy, ] with", "[ Speech2TextEncoderPolicy, Speech2TextDecoderPolicy, ] with suppress(Exception): from transformers.models.gptj.modeling_gptj import (", "self.builtin_policies[MegatronBertPreTrainedModel] = [ MegatronBertPolicy, ] def get_policy(self, model: nn.Module) ->", "for the current model Args: model (nn.Module): model to parallelize", "parallelformers.policies.ctrl import CTRLPolicy self.builtin_policies[CTRLPreTrainedModel] = [ CTRLPolicy, ] with suppress(Exception):", "self.builtin_policies[Wav2Vec2PreTrainedModel] = [ Wav2VecPolicy, ] with suppress(Exception): from transformers.models.xlnet.modeling_xlnet import", "# distributed under the License is distributed on an \"AS", ") from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertPreTrainedModel] = [ BertPolicy, ]", "[ BertPolicy, ] with suppress(Exception): from transformers.models.lxmert.modeling_lxmert import ( LxmertPreTrainedModel,", "self.builtin_policies[LukePreTrainedModel] = [ LukePolicy, ] with suppress(Exception): from transformers.models.dpr.modeling_dpr import", "HubertPreTrainedModel, ) from parallelformers.policies.hubert import HubertPolicy self.builtin_policies[HubertPreTrainedModel] = [ HubertPolicy,", "= [ BertPolicy, ] with suppress(Exception): from transformers.models.clip.modeling_clip import (", "# Unless required by applicable law or agreed to in", "transformers.models.m2m_100.modeling_m2m_100 import ( M2M100PreTrainedModel, ) from parallelformers.policies.m2m_100 import ( M2M100DecoderPolicy,", "import ( CLIPPreTrainedModel, ) from parallelformers.policies.clip import ( CLIPLayerPolicy, CLIPTextPolicy,", "] with suppress(Exception): from transformers.models.visual_bert.modeling_visual_bert import ( VisualBertPreTrainedModel, ) from", "ReformerPolicy self.builtin_policies[ReformerPreTrainedModel] = [ ReformerPolicy, ] with suppress(Exception): from transformers.models.longformer.modeling_longformer", "Wav2Vec2PreTrainedModel, ) from parallelformers.policies.wav2vec import Wav2VecPolicy self.builtin_policies[Wav2Vec2PreTrainedModel] = [ Wav2VecPolicy,", "import TapasPolicy self.builtin_policies[TapasPreTrainedModel] = [ TapasPolicy, ] with suppress(Exception): from", "from parallelformers.policies.gpt_neo import GPTNeoPolicy self.builtin_policies[GPTNeoPreTrainedModel] = [ GPTNeoPolicy, ] with", "DPRPretrainedReader, ) self.builtin_policies[DPRPretrainedReader] = [ BertPolicy, ] self.builtin_policies[DPRPretrainedQuestionEncoder] = [", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "[ BertPolicy, ] with suppress(Exception): from transformers.models.bart.modeling_bart import ( BartPretrainedModel,", "suppress(Exception): from transformers.models.t5.modeling_t5 import T5PreTrainedModel from parallelformers.policies.t5 import T5Policy self.builtin_policies[T5PreTrainedModel]", "MarianDecoderPolicy, ] with suppress(Exception): from transformers.models.mobilebert.modeling_mobilebert import ( MobileBertPreTrainedModel, )", "import ( ConvBertPreTrainedModel, ) from parallelformers.policies.convbert import ConvBertPolicy self.builtin_policies[ConvBertPreTrainedModel] =", "import ( BertGenerationPreTrainedModel, ) from parallelformers.policies.bert import BertPolicy self.builtin_policies[BertGenerationPreTrainedModel] =", "[ LongformerPolicy, ] with suppress(Exception): from transformers.models.roformer.modeling_roformer import ( RoFormerPreTrainedModel,", "[ PegasusEncoderPolicy, PegasusDecoderPolicy, ] with suppress(Exception): from transformers.models.fsmt.modeling_fsmt import (", "You may obtain a copy of the License at #", "( DebertaPreTrainedModel, ) from parallelformers.policies.deberta import DebertaPolicy self.builtin_policies[DebertaPreTrainedModel] = [", "suppress(Exception): from transformers.models.bert.modeling_bert import ( BertPreTrainedModel, ) from parallelformers.policies.bert import", "from transformers.models.albert.modeling_albert import ( AlbertPreTrainedModel, ) from parallelformers.policies.albert import AlbertPolicy", "ElectraPreTrainedModel, ) from parallelformers.policies.electra import ElectraPolicy self.builtin_policies[ElectraPreTrainedModel] = [ ElectraPolicy,", "def available(self): \"\"\"Dictionary of available models and policies\"\"\" return self.builtin_policies", "parallelformers.policies.led import ( LEDDecoderPolicy, LEDEncoderPolicy, ) self.builtin_policies[LEDPreTrainedModel] = [ LEDEncoderPolicy,", "List, Union from torch import nn from parallelformers.policies.base import Policy", "= [ RobertaPolicy, ] with suppress(Exception): from transformers.models.albert.modeling_albert import (", "] with suppress(Exception): from transformers.models.vit.modeling_vit import ViTPreTrainedModel from parallelformers.policies.vit import", "with suppress(Exception): from transformers.models.fsmt.modeling_fsmt import ( PretrainedFSMTModel, ) from parallelformers.policies.fsmt", "self.builtin_policies[LongformerPreTrainedModel] = [ LongformerPolicy, ] with suppress(Exception): from transformers.models.roformer.modeling_roformer import", "from parallelformers.policies.mpnet import ( MPNetEncoderPolicy, MPNetLayerPolicy, ) self.builtin_policies[MPNetPreTrainedModel] = [", "OpenAIGPTPreTrainedModel, ) from parallelformers.policies.openai import OpenAIGPTPolicy self.builtin_policies[OpenAIGPTPreTrainedModel] = [ OpenAIGPTPolicy,", "= [ MarianEncoderPolicy, MarianDecoderPolicy, ] with suppress(Exception): from transformers.models.mobilebert.modeling_mobilebert import", "import ( MobileBertPreTrainedModel, ) from parallelformers.policies.mobilebert import MobileBertPolicy self.builtin_policies[MobileBertPreTrainedModel] =", "MobileBertPreTrainedModel, ) from parallelformers.policies.mobilebert import MobileBertPolicy self.builtin_policies[MobileBertPreTrainedModel] = [ MobileBertPolicy,", "IBertPreTrainedModel, ) from parallelformers.policies.ibert import IBertPolicy self.builtin_policies[IBertPreTrainedModel] = [ IBertPolicy,", "import ( BlenderbotSmallPreTrainedModel, ) from parallelformers.policies.blenderbot_small import ( BlenderbotSmallDecoderPolicy, BlenderbotSmallEncoderPolicy,", "import T5Policy self.builtin_policies[T5PreTrainedModel] = [ T5Policy, ] with suppress(Exception): from", "the Apache License, Version 2.0 (the \"License\"); # you may", "self.builtin_policies[RoFormerPreTrainedModel] = [ RoformerPolicy, ] with suppress(Exception): from transformers.models.ibert.modeling_ibert import", "[ MBartEncoderPolicy, MBartDecoderPolicy, ] with suppress(Exception): from transformers.models.t5.modeling_t5 import T5PreTrainedModel", "with suppress(Exception): from transformers.models.visual_bert.modeling_visual_bert import ( VisualBertPreTrainedModel, ) from parallelformers.policies.visual_bert", "transformers.models.roformer.modeling_roformer import ( RoFormerPreTrainedModel, ) from parallelformers.policies.roformer import RoformerPolicy self.builtin_policies[RoFormerPreTrainedModel]", "from parallelformers.policies.roberta import RobertaPolicy self.builtin_policies[RobertaPreTrainedModel] = [ RobertaPolicy, ] with", ") self.builtin_policies[MarianPreTrainedModel] = [ MarianEncoderPolicy, MarianDecoderPolicy, ] with suppress(Exception): from", "( PretrainedFSMTModel, ) from parallelformers.policies.fsmt import ( FSMTDecoderPolicy, FSMTEncoderPolicy, )", "] with suppress(Exception): from transformers.models.blenderbot_small.modeling_blenderbot_small import ( BlenderbotSmallPreTrainedModel, ) from", "import Wav2VecPolicy self.builtin_policies[Wav2Vec2PreTrainedModel] = [ Wav2VecPolicy, ] with suppress(Exception): from", "self.builtin_policies[GPT2PreTrainedModel] = [ GPT2Policy, ] with suppress(Exception): from transformers.models.ctrl.modeling_ctrl import" ]
[ "temp_c, line_value=-36, color='#b22222') outname = output_name(args[\"file\"], pressure) print(outname) jp_map.save_fig(outname, str(pressure)", "argparse.ArgumentParser() parser.add_argument(\"-f\", \"--file\", help=\"set ncfile.\", type=str) p = parser.parse_args() args", "#label_upper = (30, 0) #lebel_min = (-30, -60) for i,", "0) #lebel_min = (-30, -60) for i, pressure in enumerate(isobaric_surface):", "def output_name(ncfile: str, isobaric_surface: int) -> str: \"\"\"output_name. Args: ncfile", "outname = output_name(args[\"file\"], pressure) print(outname) jp_map.save_fig(outname, str(pressure) + \"hPa\") if", "Make upper level weather chart. Usage: python3 upper_air_humidity.py --file <ncfile>", "lat, u_wind, v_wind, vector_interval=5, vector_scale=10, mode=\"wind\") #jp_map.gray_shade(lon, lat, rh, #", "lat, temp_c, line_value=-36, color='#b22222') outname = output_name(args[\"file\"], pressure) print(outname) jp_map.save_fig(outname,", "outname = (date_time + \"_\" + str(isobaric_surface)) return outname def", "type=str) p = parser.parse_args() args = {\"file\": p.file} return args", "v_wind, vector_interval=5, vector_scale=10, mode=\"wind\") #jp_map.gray_shade(lon, lat, rh, # label=\"relative humidity", "parser = argparse.ArgumentParser() parser.add_argument(\"-f\", \"--file\", help=\"set ncfile.\", type=str) p =", "= parse_args() meteo_tool = meteotool.MeteoTools(args[\"file\"]) lat, lon = meteo_tool.get_lat_lon() isobaric_surface", "color_bar_label_max=100, # color_bar_label_min=0, # ) if pressure == 850: jp_map.color_line(lon,", "utf-8 \"\"\" Name: upper_air_humidity.py Make upper level weather chart. Usage:", "str: \"\"\"output_name. Args: ncfile (str): ncfile isobaric_surface (int): isobaric_surface Returns:", "pressure == 500: jp_map.color_line(lon, lat, temp_c, line_value=-36, color='#b22222') outname =", "(date_time + \"_\" + str(isobaric_surface)) return outname def main(): \"\"\"main.", "# double_color_bar=True,) jp_map.shade_plot(lon, lat, rh, label=\"relative humidity (%)\", color_bar_label_max=100, color_bar_label_min=0,", "line_value=-6, color='#0000ff') if pressure == 500: jp_map.color_line(lon, lat, temp_c, line_value=-36,", "i, pressure in enumerate(isobaric_surface): # get parameter temp_c = meteo_tool.get_parameter('t',", "isobaric_surface=pressure) jp_map = japanmap.JpMap() jp_map.contour_plot(lon, lat, height_gpm) #jp_map.shade_plot(lon, lat, temp_c,", "meteotool.MeteoTools(args[\"file\"]) lat, lon = meteo_tool.get_lat_lon() isobaric_surface = (850, 500, 300)", "(%)\", # color_bar_label_max=100, # color_bar_label_min=0, # ) if pressure ==", "dict: \"\"\"parse_args. set file path. Args: Returns: dict: \"\"\" parser", "= meteo_tool.get_parameter('r', isobaric_surface=pressure) height_gpm = meteo_tool.get_parameter('gh', isobaric_surface=pressure) u_wind = meteo_tool.get_parameter('u',", "if pressure == 500: jp_map.color_line(lon, lat, temp_c, line_value=-36, color='#b22222') outname", "print(outname) jp_map.save_fig(outname, str(pressure) + \"hPa\") if __name__ == \"__main__\": main()", "color_map_type=\"gray\", double_color_bar=False,) jp_map.vector_plot(lon, lat, u_wind, v_wind, vector_interval=5, vector_scale=10, mode=\"wind\") #jp_map.gray_shade(lon,", "set file path. Args: Returns: dict: \"\"\" parser = argparse.ArgumentParser()", "- 273.15 rh = meteo_tool.get_parameter('r', isobaric_surface=pressure) height_gpm = meteo_tool.get_parameter('gh', isobaric_surface=pressure)", "temperature ($^\\circ$C)\", # color_bar_label_max=label_upper[i], # color_bar_label_min=lebel_min[i], # color_map_type=\"temperature\", # double_color_bar=True,)", "color_bar_label_max=label_upper[i], # color_bar_label_min=lebel_min[i], # color_map_type=\"temperature\", # double_color_bar=True,) jp_map.shade_plot(lon, lat, rh,", "meteo_tool.get_lat_lon() isobaric_surface = (850, 500, 300) #label_upper = (30, 0)", "300) #label_upper = (30, 0) #lebel_min = (-30, -60) for", "color='#0000ff') if pressure == 500: jp_map.color_line(lon, lat, temp_c, line_value=-36, color='#b22222')", "output_name(args[\"file\"], pressure) print(outname) jp_map.save_fig(outname, str(pressure) + \"hPa\") if __name__ ==", "p = parser.parse_args() args = {\"file\": p.file} return args def", "= meteo_tool.get_parameter('v', isobaric_surface=pressure) jp_map = japanmap.JpMap() jp_map.contour_plot(lon, lat, height_gpm) #jp_map.shade_plot(lon,", "= output_name(args[\"file\"], pressure) print(outname) jp_map.save_fig(outname, str(pressure) + \"hPa\") if __name__", "lat, height_gpm) #jp_map.shade_plot(lon, lat, temp_c, # label=\"2m temperature ($^\\circ$C)\", #", "(%)\", color_bar_label_max=100, color_bar_label_min=0, color_map_type=\"gray\", double_color_bar=False,) jp_map.vector_plot(lon, lat, u_wind, v_wind, vector_interval=5,", "color_bar_label_min=0, # ) if pressure == 850: jp_map.color_line(lon, lat, temp_c,", "output_name(ncfile: str, isobaric_surface: int) -> str: \"\"\"output_name. Args: ncfile (str):", "500, 300) #label_upper = (30, 0) #lebel_min = (-30, -60)", "= meteo_tool.get_parameter('t', isobaric_surface=pressure) - 273.15 rh = meteo_tool.get_parameter('r', isobaric_surface=pressure) height_gpm", "temp_c = meteo_tool.get_parameter('t', isobaric_surface=pressure) - 273.15 rh = meteo_tool.get_parameter('r', isobaric_surface=pressure)", "\"\"\"main. \"\"\" args = parse_args() meteo_tool = meteotool.MeteoTools(args[\"file\"]) lat, lon", "weather chart. Usage: python3 upper_air_humidity.py --file <ncfile> Author: <NAME> Date:", "return outname def main(): \"\"\"main. \"\"\" args = parse_args() meteo_tool", "(30, 0) #lebel_min = (-30, -60) for i, pressure in", "lat, rh, # label=\"relative humidity (%)\", # color_bar_label_max=100, # color_bar_label_min=0,", "u_wind = meteo_tool.get_parameter('u', isobaric_surface=pressure) v_wind = meteo_tool.get_parameter('v', isobaric_surface=pressure) jp_map =", "meteo_tool.get_parameter('u', isobaric_surface=pressure) v_wind = meteo_tool.get_parameter('v', isobaric_surface=pressure) jp_map = japanmap.JpMap() jp_map.contour_plot(lon,", "= parser.parse_args() args = {\"file\": p.file} return args def output_name(ncfile:", "(850, 500, 300) #label_upper = (30, 0) #lebel_min = (-30,", "= meteo_tool.get_lat_lon() isobaric_surface = (850, 500, 300) #label_upper = (30,", "height_gpm = meteo_tool.get_parameter('gh', isobaric_surface=pressure) u_wind = meteo_tool.get_parameter('u', isobaric_surface=pressure) v_wind =", "upper level weather chart. Usage: python3 upper_air_humidity.py --file <ncfile> Author:", "#jp_map.gray_shade(lon, lat, rh, # label=\"relative humidity (%)\", # color_bar_label_max=100, #", "def main(): \"\"\"main. \"\"\" args = parse_args() meteo_tool = meteotool.MeteoTools(args[\"file\"])", "Returns: str: \"\"\" date_time = fetchtime.fetch_time(ncfile) outname = (date_time +", "isobaric_surface Returns: str: \"\"\" date_time = fetchtime.fetch_time(ncfile) outname = (date_time", "= (date_time + \"_\" + str(isobaric_surface)) return outname def main():", "color_bar_label_min=0, color_map_type=\"gray\", double_color_bar=False,) jp_map.vector_plot(lon, lat, u_wind, v_wind, vector_interval=5, vector_scale=10, mode=\"wind\")", "-> dict: \"\"\"parse_args. set file path. Args: Returns: dict: \"\"\"", "(int): isobaric_surface Returns: str: \"\"\" date_time = fetchtime.fetch_time(ncfile) outname =", "\"\"\" Name: upper_air_humidity.py Make upper level weather chart. Usage: python3", "help=\"set ncfile.\", type=str) p = parser.parse_args() args = {\"file\": p.file}", "date_time = fetchtime.fetch_time(ncfile) outname = (date_time + \"_\" + str(isobaric_surface))", "fetchtime.fetch_time(ncfile) outname = (date_time + \"_\" + str(isobaric_surface)) return outname", "ncfile (str): ncfile isobaric_surface (int): isobaric_surface Returns: str: \"\"\" date_time", "isobaric_surface=pressure) - 273.15 rh = meteo_tool.get_parameter('r', isobaric_surface=pressure) height_gpm = meteo_tool.get_parameter('gh',", "= meteo_tool.get_parameter('u', isobaric_surface=pressure) v_wind = meteo_tool.get_parameter('v', isobaric_surface=pressure) jp_map = japanmap.JpMap()", "vector_interval=5, vector_scale=10, mode=\"wind\") #jp_map.gray_shade(lon, lat, rh, # label=\"relative humidity (%)\",", "meteo_tool.get_parameter('v', isobaric_surface=pressure) jp_map = japanmap.JpMap() jp_map.contour_plot(lon, lat, height_gpm) #jp_map.shade_plot(lon, lat,", "parser.add_argument(\"-f\", \"--file\", help=\"set ncfile.\", type=str) p = parser.parse_args() args =", "ncmagics import fetchtime, japanmap, meteotool def parse_args() -> dict: \"\"\"parse_args.", "lat, lon = meteo_tool.get_lat_lon() isobaric_surface = (850, 500, 300) #label_upper", "lon = meteo_tool.get_lat_lon() isobaric_surface = (850, 500, 300) #label_upper =", "pressure in enumerate(isobaric_surface): # get parameter temp_c = meteo_tool.get_parameter('t', isobaric_surface=pressure)", "height_gpm) #jp_map.shade_plot(lon, lat, temp_c, # label=\"2m temperature ($^\\circ$C)\", # color_bar_label_max=label_upper[i],", "temp_c, line_value=-6, color='#0000ff') if pressure == 500: jp_map.color_line(lon, lat, temp_c,", "isobaric_surface=pressure) u_wind = meteo_tool.get_parameter('u', isobaric_surface=pressure) v_wind = meteo_tool.get_parameter('v', isobaric_surface=pressure) jp_map", "(str): ncfile isobaric_surface (int): isobaric_surface Returns: str: \"\"\" date_time =", "import fetchtime, japanmap, meteotool def parse_args() -> dict: \"\"\"parse_args. set", "Args: ncfile (str): ncfile isobaric_surface (int): isobaric_surface Returns: str: \"\"\"", "return args def output_name(ncfile: str, isobaric_surface: int) -> str: \"\"\"output_name.", "str(isobaric_surface)) return outname def main(): \"\"\"main. \"\"\" args = parse_args()", "main(): \"\"\"main. \"\"\" args = parse_args() meteo_tool = meteotool.MeteoTools(args[\"file\"]) lat,", "rh, # label=\"relative humidity (%)\", # color_bar_label_max=100, # color_bar_label_min=0, #", "# color_bar_label_max=100, # color_bar_label_min=0, # ) if pressure == 850:", "isobaric_surface (int): isobaric_surface Returns: str: \"\"\" date_time = fetchtime.fetch_time(ncfile) outname", "dict: \"\"\" parser = argparse.ArgumentParser() parser.add_argument(\"-f\", \"--file\", help=\"set ncfile.\", type=str)", "color_bar_label_min=lebel_min[i], # color_map_type=\"temperature\", # double_color_bar=True,) jp_map.shade_plot(lon, lat, rh, label=\"relative humidity", "args = {\"file\": p.file} return args def output_name(ncfile: str, isobaric_surface:", "Args: Returns: dict: \"\"\" parser = argparse.ArgumentParser() parser.add_argument(\"-f\", \"--file\", help=\"set", "= meteo_tool.get_parameter('gh', isobaric_surface=pressure) u_wind = meteo_tool.get_parameter('u', isobaric_surface=pressure) v_wind = meteo_tool.get_parameter('v',", "pressure == 850: jp_map.color_line(lon, lat, temp_c, line_value=-6, color='#0000ff') if pressure", "\"--file\", help=\"set ncfile.\", type=str) p = parser.parse_args() args = {\"file\":", "parse_args() -> dict: \"\"\"parse_args. set file path. Args: Returns: dict:", "parse_args() meteo_tool = meteotool.MeteoTools(args[\"file\"]) lat, lon = meteo_tool.get_lat_lon() isobaric_surface =", "\"\"\"parse_args. set file path. Args: Returns: dict: \"\"\" parser =", "\"\"\"output_name. Args: ncfile (str): ncfile isobaric_surface (int): isobaric_surface Returns: str:", "vector_scale=10, mode=\"wind\") #jp_map.gray_shade(lon, lat, rh, # label=\"relative humidity (%)\", #", "jp_map = japanmap.JpMap() jp_map.contour_plot(lon, lat, height_gpm) #jp_map.shade_plot(lon, lat, temp_c, #", "#jp_map.shade_plot(lon, lat, temp_c, # label=\"2m temperature ($^\\circ$C)\", # color_bar_label_max=label_upper[i], #", "= argparse.ArgumentParser() parser.add_argument(\"-f\", \"--file\", help=\"set ncfile.\", type=str) p = parser.parse_args()", "Usage: python3 upper_air_humidity.py --file <ncfile> Author: <NAME> Date: 2022/01/07 \"\"\"", "enumerate(isobaric_surface): # get parameter temp_c = meteo_tool.get_parameter('t', isobaric_surface=pressure) - 273.15", "500: jp_map.color_line(lon, lat, temp_c, line_value=-36, color='#b22222') outname = output_name(args[\"file\"], pressure)", "\"\"\" date_time = fetchtime.fetch_time(ncfile) outname = (date_time + \"_\" +", "-60) for i, pressure in enumerate(isobaric_surface): # get parameter temp_c", "rh = meteo_tool.get_parameter('r', isobaric_surface=pressure) height_gpm = meteo_tool.get_parameter('gh', isobaric_surface=pressure) u_wind =", "meteo_tool.get_parameter('r', isobaric_surface=pressure) height_gpm = meteo_tool.get_parameter('gh', isobaric_surface=pressure) u_wind = meteo_tool.get_parameter('u', isobaric_surface=pressure)", "args = parse_args() meteo_tool = meteotool.MeteoTools(args[\"file\"]) lat, lon = meteo_tool.get_lat_lon()", "label=\"2m temperature ($^\\circ$C)\", # color_bar_label_max=label_upper[i], # color_bar_label_min=lebel_min[i], # color_map_type=\"temperature\", #", "humidity (%)\", color_bar_label_max=100, color_bar_label_min=0, color_map_type=\"gray\", double_color_bar=False,) jp_map.vector_plot(lon, lat, u_wind, v_wind,", "u_wind, v_wind, vector_interval=5, vector_scale=10, mode=\"wind\") #jp_map.gray_shade(lon, lat, rh, # label=\"relative", "color='#b22222') outname = output_name(args[\"file\"], pressure) print(outname) jp_map.save_fig(outname, str(pressure) + \"hPa\")", "import argparse from ncmagics import fetchtime, japanmap, meteotool def parse_args()", "meteo_tool.get_parameter('gh', isobaric_surface=pressure) u_wind = meteo_tool.get_parameter('u', isobaric_surface=pressure) v_wind = meteo_tool.get_parameter('v', isobaric_surface=pressure)", "== 500: jp_map.color_line(lon, lat, temp_c, line_value=-36, color='#b22222') outname = output_name(args[\"file\"],", "outname def main(): \"\"\"main. \"\"\" args = parse_args() meteo_tool =", "<ncfile> Author: <NAME> Date: 2022/01/07 \"\"\" import argparse from ncmagics", "\"_\" + str(isobaric_surface)) return outname def main(): \"\"\"main. \"\"\" args", "# ) if pressure == 850: jp_map.color_line(lon, lat, temp_c, line_value=-6,", "argparse from ncmagics import fetchtime, japanmap, meteotool def parse_args() ->", "ncfile.\", type=str) p = parser.parse_args() args = {\"file\": p.file} return", "int) -> str: \"\"\"output_name. Args: ncfile (str): ncfile isobaric_surface (int):", "str: \"\"\" date_time = fetchtime.fetch_time(ncfile) outname = (date_time + \"_\"", "temp_c, # label=\"2m temperature ($^\\circ$C)\", # color_bar_label_max=label_upper[i], # color_bar_label_min=lebel_min[i], #", "= (850, 500, 300) #label_upper = (30, 0) #lebel_min =", "double_color_bar=True,) jp_map.shade_plot(lon, lat, rh, label=\"relative humidity (%)\", color_bar_label_max=100, color_bar_label_min=0, color_map_type=\"gray\",", "if pressure == 850: jp_map.color_line(lon, lat, temp_c, line_value=-6, color='#0000ff') if", "fetchtime, japanmap, meteotool def parse_args() -> dict: \"\"\"parse_args. set file", "= (30, 0) #lebel_min = (-30, -60) for i, pressure", "--file <ncfile> Author: <NAME> Date: 2022/01/07 \"\"\" import argparse from", "file path. Args: Returns: dict: \"\"\" parser = argparse.ArgumentParser() parser.add_argument(\"-f\",", "= fetchtime.fetch_time(ncfile) outname = (date_time + \"_\" + str(isobaric_surface)) return", "# get parameter temp_c = meteo_tool.get_parameter('t', isobaric_surface=pressure) - 273.15 rh", "double_color_bar=False,) jp_map.vector_plot(lon, lat, u_wind, v_wind, vector_interval=5, vector_scale=10, mode=\"wind\") #jp_map.gray_shade(lon, lat,", "japanmap, meteotool def parse_args() -> dict: \"\"\"parse_args. set file path.", "\"\"\" import argparse from ncmagics import fetchtime, japanmap, meteotool def", "isobaric_surface = (850, 500, 300) #label_upper = (30, 0) #lebel_min", "color_bar_label_max=100, color_bar_label_min=0, color_map_type=\"gray\", double_color_bar=False,) jp_map.vector_plot(lon, lat, u_wind, v_wind, vector_interval=5, vector_scale=10,", "Name: upper_air_humidity.py Make upper level weather chart. Usage: python3 upper_air_humidity.py", "coding: utf-8 \"\"\" Name: upper_air_humidity.py Make upper level weather chart.", "= japanmap.JpMap() jp_map.contour_plot(lon, lat, height_gpm) #jp_map.shade_plot(lon, lat, temp_c, # label=\"2m", "def parse_args() -> dict: \"\"\"parse_args. set file path. Args: Returns:", "rh, label=\"relative humidity (%)\", color_bar_label_max=100, color_bar_label_min=0, color_map_type=\"gray\", double_color_bar=False,) jp_map.vector_plot(lon, lat,", "humidity (%)\", # color_bar_label_max=100, # color_bar_label_min=0, # ) if pressure", "line_value=-36, color='#b22222') outname = output_name(args[\"file\"], pressure) print(outname) jp_map.save_fig(outname, str(pressure) +", ") if pressure == 850: jp_map.color_line(lon, lat, temp_c, line_value=-6, color='#0000ff')", "meteo_tool.get_parameter('t', isobaric_surface=pressure) - 273.15 rh = meteo_tool.get_parameter('r', isobaric_surface=pressure) height_gpm =", "in enumerate(isobaric_surface): # get parameter temp_c = meteo_tool.get_parameter('t', isobaric_surface=pressure) -", "parameter temp_c = meteo_tool.get_parameter('t', isobaric_surface=pressure) - 273.15 rh = meteo_tool.get_parameter('r',", "# color_bar_label_min=lebel_min[i], # color_map_type=\"temperature\", # double_color_bar=True,) jp_map.shade_plot(lon, lat, rh, label=\"relative", "parser.parse_args() args = {\"file\": p.file} return args def output_name(ncfile: str,", "Date: 2022/01/07 \"\"\" import argparse from ncmagics import fetchtime, japanmap,", "meteotool def parse_args() -> dict: \"\"\"parse_args. set file path. Args:", "get parameter temp_c = meteo_tool.get_parameter('t', isobaric_surface=pressure) - 273.15 rh =", "jp_map.contour_plot(lon, lat, height_gpm) #jp_map.shade_plot(lon, lat, temp_c, # label=\"2m temperature ($^\\circ$C)\",", "level weather chart. Usage: python3 upper_air_humidity.py --file <ncfile> Author: <NAME>", "# color_map_type=\"temperature\", # double_color_bar=True,) jp_map.shade_plot(lon, lat, rh, label=\"relative humidity (%)\",", "jp_map.vector_plot(lon, lat, u_wind, v_wind, vector_interval=5, vector_scale=10, mode=\"wind\") #jp_map.gray_shade(lon, lat, rh,", "Author: <NAME> Date: 2022/01/07 \"\"\" import argparse from ncmagics import", "# coding: utf-8 \"\"\" Name: upper_air_humidity.py Make upper level weather", "v_wind = meteo_tool.get_parameter('v', isobaric_surface=pressure) jp_map = japanmap.JpMap() jp_map.contour_plot(lon, lat, height_gpm)", "lat, rh, label=\"relative humidity (%)\", color_bar_label_max=100, color_bar_label_min=0, color_map_type=\"gray\", double_color_bar=False,) jp_map.vector_plot(lon,", "mode=\"wind\") #jp_map.gray_shade(lon, lat, rh, # label=\"relative humidity (%)\", # color_bar_label_max=100,", "jp_map.color_line(lon, lat, temp_c, line_value=-36, color='#b22222') outname = output_name(args[\"file\"], pressure) print(outname)", "<NAME> Date: 2022/01/07 \"\"\" import argparse from ncmagics import fetchtime,", "+ str(isobaric_surface)) return outname def main(): \"\"\"main. \"\"\" args =", "color_map_type=\"temperature\", # double_color_bar=True,) jp_map.shade_plot(lon, lat, rh, label=\"relative humidity (%)\", color_bar_label_max=100,", "isobaric_surface=pressure) height_gpm = meteo_tool.get_parameter('gh', isobaric_surface=pressure) u_wind = meteo_tool.get_parameter('u', isobaric_surface=pressure) v_wind", "japanmap.JpMap() jp_map.contour_plot(lon, lat, height_gpm) #jp_map.shade_plot(lon, lat, temp_c, # label=\"2m temperature", "isobaric_surface=pressure) v_wind = meteo_tool.get_parameter('v', isobaric_surface=pressure) jp_map = japanmap.JpMap() jp_map.contour_plot(lon, lat,", "2022/01/07 \"\"\" import argparse from ncmagics import fetchtime, japanmap, meteotool", "lat, temp_c, line_value=-6, color='#0000ff') if pressure == 500: jp_map.color_line(lon, lat,", "# color_bar_label_max=label_upper[i], # color_bar_label_min=lebel_min[i], # color_map_type=\"temperature\", # double_color_bar=True,) jp_map.shade_plot(lon, lat,", "= {\"file\": p.file} return args def output_name(ncfile: str, isobaric_surface: int)", "273.15 rh = meteo_tool.get_parameter('r', isobaric_surface=pressure) height_gpm = meteo_tool.get_parameter('gh', isobaric_surface=pressure) u_wind", "python3 upper_air_humidity.py --file <ncfile> Author: <NAME> Date: 2022/01/07 \"\"\" import", "= (-30, -60) for i, pressure in enumerate(isobaric_surface): # get", "for i, pressure in enumerate(isobaric_surface): # get parameter temp_c =", "label=\"relative humidity (%)\", # color_bar_label_max=100, # color_bar_label_min=0, # ) if", "chart. Usage: python3 upper_air_humidity.py --file <ncfile> Author: <NAME> Date: 2022/01/07", "Returns: dict: \"\"\" parser = argparse.ArgumentParser() parser.add_argument(\"-f\", \"--file\", help=\"set ncfile.\",", "= meteotool.MeteoTools(args[\"file\"]) lat, lon = meteo_tool.get_lat_lon() isobaric_surface = (850, 500,", "str, isobaric_surface: int) -> str: \"\"\"output_name. Args: ncfile (str): ncfile", "-> str: \"\"\"output_name. Args: ncfile (str): ncfile isobaric_surface (int): isobaric_surface", "pressure) print(outname) jp_map.save_fig(outname, str(pressure) + \"hPa\") if __name__ == \"__main__\":", "(-30, -60) for i, pressure in enumerate(isobaric_surface): # get parameter", "850: jp_map.color_line(lon, lat, temp_c, line_value=-6, color='#0000ff') if pressure == 500:", "jp_map.shade_plot(lon, lat, rh, label=\"relative humidity (%)\", color_bar_label_max=100, color_bar_label_min=0, color_map_type=\"gray\", double_color_bar=False,)", "path. Args: Returns: dict: \"\"\" parser = argparse.ArgumentParser() parser.add_argument(\"-f\", \"--file\",", "#lebel_min = (-30, -60) for i, pressure in enumerate(isobaric_surface): #", "{\"file\": p.file} return args def output_name(ncfile: str, isobaric_surface: int) ->", "lat, temp_c, # label=\"2m temperature ($^\\circ$C)\", # color_bar_label_max=label_upper[i], # color_bar_label_min=lebel_min[i],", "meteo_tool = meteotool.MeteoTools(args[\"file\"]) lat, lon = meteo_tool.get_lat_lon() isobaric_surface = (850,", "# color_bar_label_min=0, # ) if pressure == 850: jp_map.color_line(lon, lat,", "p.file} return args def output_name(ncfile: str, isobaric_surface: int) -> str:", "== 850: jp_map.color_line(lon, lat, temp_c, line_value=-6, color='#0000ff') if pressure ==", "from ncmagics import fetchtime, japanmap, meteotool def parse_args() -> dict:", "($^\\circ$C)\", # color_bar_label_max=label_upper[i], # color_bar_label_min=lebel_min[i], # color_map_type=\"temperature\", # double_color_bar=True,) jp_map.shade_plot(lon,", "upper_air_humidity.py --file <ncfile> Author: <NAME> Date: 2022/01/07 \"\"\" import argparse", "\"\"\" parser = argparse.ArgumentParser() parser.add_argument(\"-f\", \"--file\", help=\"set ncfile.\", type=str) p", "isobaric_surface: int) -> str: \"\"\"output_name. Args: ncfile (str): ncfile isobaric_surface", "jp_map.color_line(lon, lat, temp_c, line_value=-6, color='#0000ff') if pressure == 500: jp_map.color_line(lon,", "args def output_name(ncfile: str, isobaric_surface: int) -> str: \"\"\"output_name. Args:", "upper_air_humidity.py Make upper level weather chart. Usage: python3 upper_air_humidity.py --file", "+ \"_\" + str(isobaric_surface)) return outname def main(): \"\"\"main. \"\"\"", "\"\"\" args = parse_args() meteo_tool = meteotool.MeteoTools(args[\"file\"]) lat, lon =", "label=\"relative humidity (%)\", color_bar_label_max=100, color_bar_label_min=0, color_map_type=\"gray\", double_color_bar=False,) jp_map.vector_plot(lon, lat, u_wind,", "ncfile isobaric_surface (int): isobaric_surface Returns: str: \"\"\" date_time = fetchtime.fetch_time(ncfile)", "# label=\"relative humidity (%)\", # color_bar_label_max=100, # color_bar_label_min=0, # )", "# label=\"2m temperature ($^\\circ$C)\", # color_bar_label_max=label_upper[i], # color_bar_label_min=lebel_min[i], # color_map_type=\"temperature\"," ]